function
stringlengths
61
9.1k
testmethod
stringlengths
42
143
location_fixed
stringlengths
43
98
end_buggy
int64
10
12k
location
stringlengths
43
98
function_name
stringlengths
4
73
source_buggy
stringlengths
655
442k
prompt_complete
stringlengths
433
4.3k
end_fixed
int64
10
12k
comment
stringlengths
0
763
bug_id
stringlengths
1
3
start_fixed
int64
7
12k
location_buggy
stringlengths
43
98
source_dir
stringclasses
5 values
prompt_chat
stringlengths
420
3.86k
start_buggy
int64
7
12k
classes_modified
sequence
task_id
stringlengths
64
64
function_signature
stringlengths
22
150
prompt_complete_without_signature
stringlengths
404
4.23k
project
stringclasses
17 values
indent
stringclasses
4 values
source_fixed
stringlengths
655
442k
@Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<Element>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); }
org.jsoup.nodes.ElementTest::appendMustCorrectlyMoveChildrenInsideOneParentElement
src/test/java/org/jsoup/nodes/ElementTest.java
879
src/test/java/org/jsoup/nodes/ElementTest.java
appendMustCorrectlyMoveChildrenInsideOneParentElement
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetSiblingsWithDuplicateContent() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("this", p.nextElementSibling().nextElementSibling().text()); assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testElementSiblingIndexSameContent() { Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("class", "second").text("now"); assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText(null); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testSetHtmlTitle() { Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>"); Element title = doc.getElementById("1"); title.html("good"); assertEquals("good", title.html()); title.html("<i>bad</i>"); assertEquals("&lt;i&gt;bad&lt;/i&gt;", title.html()); Element head = doc.getElementById("2"); head.html("<title><i>bad</i></title>"); assertEquals("<title>&lt;i&gt;bad&lt;/i&gt;</title>", head.html()); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testCssPath() { Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>"); Element divA = doc.select("div").get(0); Element divB = doc.select("div").get(1); Element divC = doc.select("div").get(2); assertEquals(divA.cssSelector(), "#id1"); assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); assertTrue(divA == doc.select(divA.cssSelector()).first()); assertTrue(divB == doc.select(divB.cssSelector()).first()); assertTrue(divC == doc.select(divC.cssSelector()).first()); } @Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2==div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<String>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length==3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); } @Test public void testHashAndEquals() { String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; Document doc = Jsoup.parse(doc1); Elements els = doc.select("p"); /* for (Element el : els) { System.out.println(el.hashCode() + " - " + el.outerHtml()); } 0 1534787905 - <p class="one">One</p> 1 1534787905 - <p class="one">One</p> 2 1539683239 - <p class="one">Two</p> 3 1535455211 - <p class="two">One</p> 4 1534787905 - <p class="one">One</p> 5 1534787905 - <p class="one">One</p> 6 1539683239 - <p class="one">Two</p> 7 1535455211 - <p class="two">One</p> */ assertEquals(8, els.size()); Element e0 = els.get(0); Element e1 = els.get(1); Element e2 = els.get(2); Element e3 = els.get(3); Element e4 = els.get(4); Element e5 = els.get(5); Element e6 = els.get(6); Element e7 = els.get(7); assertEquals(e0, e1); assertEquals(e0, e4); assertEquals(e0, e5); assertFalse(e0.equals(e2)); assertFalse(e0.equals(e3)); assertFalse(e0.equals(e6)); assertFalse(e0.equals(e7)); assertEquals(e0.hashCode(), e1.hashCode()); assertEquals(e0.hashCode(), e4.hashCode()); assertEquals(e0.hashCode(), e5.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } @Test public void testRelativeUrls() { String html = "<body><a href='./one.html'>One</a> <a href='two.html'>two</a> <a href='../three.html'>Three</a> <a href='//example2.com/four/'>Four</a> <a href='https://example2.com/five/'>Five</a>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("a"); assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); } @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<Element>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); } }
// You are a professional Java test case writer, please create a test case named `appendMustCorrectlyMoveChildrenInsideOneParentElement` for the issue `Jsoup-689`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-689 // // ## Issue-Title: // Bug in Element.insertChildren() // // ## Issue-Description: // When using org.jsoup.nodes.Element.insertChildren(int, Collection<? extends Node>) to move (more than one!) child-elements from one parent-element to the same parent, but different index then it produces wrong results. // // // The problem is that the first Element's 'move' leaves the siblingIndex unchanged and then the second 'move' removes a wrong element and produces some crap. Maybe calling reindexChildren() inside the loop in addChildren() fixes this. // // Version 1.8.3. // // Workaround: call remove() on the elements before passing them to insertChildren() // // // Easy Test Case: // // // // ``` // @Test // public void mustCorrectlyMoveChildrenInsideOneParentElement() { // // Document doc = new Document( "" ); // Element body = doc.appendElement( "body" ); // body.appendElement( "div1" ); // body.appendElement( "div2" ); // Element div3 = body.appendElement( "div3" ); // Element div4 = body.appendElement( "div4" ); // // ArrayList<Element> toMove = new ArrayList<Element>() { // { // add( div3 ); // add( div4 ); // } // }; // // body.insertChildren( 0, toMove ); // // String result = doc.toString().replaceAll( "\\s+", "" ); // assertEquals( "<body><div3></div3><div4></div4><div1></div1><div2></div2></body>", result ); // // } // // ``` // // // @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() {
879
49
860
src/test/java/org/jsoup/nodes/ElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-689 ## Issue-Title: Bug in Element.insertChildren() ## Issue-Description: When using org.jsoup.nodes.Element.insertChildren(int, Collection<? extends Node>) to move (more than one!) child-elements from one parent-element to the same parent, but different index then it produces wrong results. The problem is that the first Element's 'move' leaves the siblingIndex unchanged and then the second 'move' removes a wrong element and produces some crap. Maybe calling reindexChildren() inside the loop in addChildren() fixes this. Version 1.8.3. Workaround: call remove() on the elements before passing them to insertChildren() Easy Test Case: ``` @Test public void mustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document( "" ); Element body = doc.appendElement( "body" ); body.appendElement( "div1" ); body.appendElement( "div2" ); Element div3 = body.appendElement( "div3" ); Element div4 = body.appendElement( "div4" ); ArrayList<Element> toMove = new ArrayList<Element>() { { add( div3 ); add( div4 ); } }; body.insertChildren( 0, toMove ); String result = doc.toString().replaceAll( "\\s+", "" ); assertEquals( "<body><div3></div3><div4></div4><div1></div1><div2></div2></body>", result ); } ``` ``` You are a professional Java test case writer, please create a test case named `appendMustCorrectlyMoveChildrenInsideOneParentElement` for the issue `Jsoup-689`, utilizing the provided issue report information and the following function signature. ```java @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { ```
860
[ "org.jsoup.nodes.Node" ]
021c78a789592d6afbc95eeb73663d951c5109c229ab25610349c0ffef564ce1
@Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement()
// You are a professional Java test case writer, please create a test case named `appendMustCorrectlyMoveChildrenInsideOneParentElement` for the issue `Jsoup-689`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-689 // // ## Issue-Title: // Bug in Element.insertChildren() // // ## Issue-Description: // When using org.jsoup.nodes.Element.insertChildren(int, Collection<? extends Node>) to move (more than one!) child-elements from one parent-element to the same parent, but different index then it produces wrong results. // // // The problem is that the first Element's 'move' leaves the siblingIndex unchanged and then the second 'move' removes a wrong element and produces some crap. Maybe calling reindexChildren() inside the loop in addChildren() fixes this. // // Version 1.8.3. // // Workaround: call remove() on the elements before passing them to insertChildren() // // // Easy Test Case: // // // // ``` // @Test // public void mustCorrectlyMoveChildrenInsideOneParentElement() { // // Document doc = new Document( "" ); // Element body = doc.appendElement( "body" ); // body.appendElement( "div1" ); // body.appendElement( "div2" ); // Element div3 = body.appendElement( "div3" ); // Element div4 = body.appendElement( "div4" ); // // ArrayList<Element> toMove = new ArrayList<Element>() { // { // add( div3 ); // add( div4 ); // } // }; // // body.insertChildren( 0, toMove ); // // String result = doc.toString().replaceAll( "\\s+", "" ); // assertEquals( "<body><div3></div3><div4></div4><div1></div1><div2></div2></body>", result ); // // } // // ``` // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetSiblingsWithDuplicateContent() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("this", p.nextElementSibling().nextElementSibling().text()); assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testElementSiblingIndexSameContent() { Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("class", "second").text("now"); assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText(null); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testSetHtmlTitle() { Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>"); Element title = doc.getElementById("1"); title.html("good"); assertEquals("good", title.html()); title.html("<i>bad</i>"); assertEquals("&lt;i&gt;bad&lt;/i&gt;", title.html()); Element head = doc.getElementById("2"); head.html("<title><i>bad</i></title>"); assertEquals("<title>&lt;i&gt;bad&lt;/i&gt;</title>", head.html()); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testCssPath() { Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>"); Element divA = doc.select("div").get(0); Element divB = doc.select("div").get(1); Element divC = doc.select("div").get(2); assertEquals(divA.cssSelector(), "#id1"); assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); assertTrue(divA == doc.select(divA.cssSelector()).first()); assertTrue(divB == doc.select(divB.cssSelector()).first()); assertTrue(divC == doc.select(divC.cssSelector()).first()); } @Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2==div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<String>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length==3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); } @Test public void testHashAndEquals() { String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; Document doc = Jsoup.parse(doc1); Elements els = doc.select("p"); /* for (Element el : els) { System.out.println(el.hashCode() + " - " + el.outerHtml()); } 0 1534787905 - <p class="one">One</p> 1 1534787905 - <p class="one">One</p> 2 1539683239 - <p class="one">Two</p> 3 1535455211 - <p class="two">One</p> 4 1534787905 - <p class="one">One</p> 5 1534787905 - <p class="one">One</p> 6 1539683239 - <p class="one">Two</p> 7 1535455211 - <p class="two">One</p> */ assertEquals(8, els.size()); Element e0 = els.get(0); Element e1 = els.get(1); Element e2 = els.get(2); Element e3 = els.get(3); Element e4 = els.get(4); Element e5 = els.get(5); Element e6 = els.get(6); Element e7 = els.get(7); assertEquals(e0, e1); assertEquals(e0, e4); assertEquals(e0, e5); assertFalse(e0.equals(e2)); assertFalse(e0.equals(e3)); assertFalse(e0.equals(e6)); assertFalse(e0.equals(e7)); assertEquals(e0.hashCode(), e1.hashCode()); assertEquals(e0.hashCode(), e4.hashCode()); assertEquals(e0.hashCode(), e5.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } @Test public void testRelativeUrls() { String html = "<body><a href='./one.html'>One</a> <a href='two.html'>two</a> <a href='../three.html'>Three</a> <a href='//example2.com/four/'>Four</a> <a href='https://example2.com/five/'>Five</a>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("a"); assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); } @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<Element>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); } }
@Test public void testEscapeNull1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\"); } assertEquals("\\", sw.toString()); }
org.apache.commons.csv.CSVPrinterTest::testEscapeNull1
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
346
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
testEscapeNull1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.apache.commons.csv.Constants.CR; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Random; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * * * @version $Id$ */ public class CSVPrinterTest { private static final char DQUOTE_CHAR = '"'; private static final char BACKSLASH_CH = '\\'; private static final char QUOTE_CH = '\''; private static final int ITERATIONS_FOR_RANDOM_TEST = 50000; private static String printable(final String s) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { final char ch = s.charAt(i); if (ch <= ' ' || ch >= 128) { sb.append("(").append((int) ch).append(")"); } else { sb.append(ch); } } return sb.toString(); } private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); private void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = generateLines(nLines, nCol); final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[]) lines[i]); } printer.flush(); } final String result = sw.toString(); // System.out.println("### :" + printable(result)); try (final CSVParser parser = CSVParser.parse(result, format)) { final List<CSVRecord> parseResult = parser.getRecords(); final String[][] expected = lines.clone(); for (int i = 0; i < expected.length; i++) { expected[i] = expectNulls(expected[i], format); } Utils.compare("Printer output :" + printable(result), expected, parseResult); } } private void doRandom(final CSVFormat format, final int iter) throws Exception { for (int i = 0; i < iter; i++) { doOneRandom(format); } } /** * Converts an input CSV array into expected output values WRT NULLs. NULL strings are converted to null values * because the parser will convert these strings to null. */ private <T> T[] expectNulls(final T[] original, final CSVFormat csvFormat) { final T[] fixed = original.clone(); for (int i = 0; i < fixed.length; i++) { if (Objects.equals(csvFormat.getNullString(), fixed[i])) { fixed[i] = null; } } return fixed; } private Connection geH2Connection() throws SQLException, ClassNotFoundException { Class.forName("org.h2.Driver"); return DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); } private String[][] generateLines(final int nLines, final int nCol) { final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } return lines; } private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) throws IOException { CSVFormat format = baseFormat; // Use withHeaderComments first to test CSV-145 format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); format = format.withCommentMarker('#'); format = format.withHeader("Col1", "Col2"); final CSVPrinter csvPrinter = format.print(sw); csvPrinter.printRecord("A", "B"); csvPrinter.printRecord("C", "D"); csvPrinter.close(); return csvPrinter; } private String randStr() { final Random r = new Random(); final int sz = r.nextInt(20); // sz = r.nextInt(3); final char[] buf = new char[sz]; for (int i = 0; i < sz; i++) { // stick in special chars with greater frequency char ch; final int what = r.nextInt(20); switch (what) { case 0: ch = '\r'; break; case 1: ch = '\n'; break; case 2: ch = '\t'; break; case 3: ch = '\f'; break; case 4: ch = ' '; break; case 5: ch = ','; break; case 6: ch = DQUOTE_CHAR; break; case 7: ch = '\''; break; case 8: ch = BACKSLASH_CH; break; default: ch = (char) r.nextInt(300); break; // default: ch = 'a'; break; } buf[i] = ch; } return new String(buf); } private void setUpTable(final Connection connection) throws SQLException { try (final Statement statement = connection.createStatement()) { statement.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); statement.execute("insert into TEST values(1, 'r1')"); statement.execute("insert into TEST values(2, 'r2')"); } } @Test public void testDelimeterQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("'a,b,c',xyz", sw.toString()); } } @Test public void testDelimeterQuoteNONE() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuoteMode(QuoteMode.NONE); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a,b,c,xyz", sw.toString()); } } @Test public void testDisabledComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printComment("This is a comment"); assertEquals("", sw.toString()); } } @Test public void testEOLEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a!rb!nc,x\fy\bz", sw.toString()); } } @Test public void testEOLPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a\rb\nc,x\fy\bz", sw.toString()); } } @Test public void testEOLQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a\rb\nc"); printer.print("x\by\fz"); assertEquals("'a\rb\nc',x\by\fz", sw.toString()); } } @Test public void testEscapeBackslash1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeBackslash2() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\r"); } assertEquals("'\\\r'", sw.toString()); } @Test public void testEscapeBackslash3() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("X\\\r"); } assertEquals("'X\\\r'", sw.toString()); } @Test public void testEscapeBackslash4() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeBackslash5() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeNull2() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\r"); } assertEquals("\"\\\r\"", sw.toString()); } @Test public void testEscapeNull3() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("X\\\r"); } assertEquals("\"X\\\r\"", sw.toString()); } @Test public void testEscapeNull4() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull5() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testExcelPrintAllArrayOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords((Object[]) new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( (Object[]) new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testHeader() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testHeaderCommentExcel() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.EXCEL; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1,Col2\r\nA,B\r\nC,D\r\n", sw.toString()); } } @Test public void testHeaderCommentTdf() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.TDF; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1\tCol2\r\nA\tB\r\nC\tD\r\n", sw.toString()); } } @Test public void testHeaderNotSet() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception { final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), invalidFormat)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); } } assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection();) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { printer.printRecords(resultSet); } } assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { printer.printRecords(resultSet); assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } } } @Test @Ignore public void testJira135_part1() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); printer.printRecord(list); } final String expected = "\"\\\"\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part2() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\n"); printer.printRecord(list); } final String expected = "\"\\n\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part3() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135All() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); list.add("\n"); list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\"\",\"\\n\",\"\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test public void testMultiLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment\non multiple lines"); assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); } } @Test public void testMySqlNullOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.MYSQL.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.NON_NUMERIC); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\"\tNULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test public void testMySqlNullStringDefault() { assertEquals("\\N", CSVFormat.MYSQL.getNullString()); } @Test(expected = IllegalArgumentException.class) public void testNewCsvPrinterAppendableNullFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), null)) { Assert.fail("This test should have thrown an exception."); } } @Test(expected = IllegalArgumentException.class) public void testNewCSVPrinterNullAppendableFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(null, CSVFormat.DEFAULT)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.printRecord("a", null, "b"); } final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); try (final CSVParser iterable = format.parse(new StringReader(csvString))) { final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); } } @Test public void testPlainEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("abc"); assertEquals("abc", sw.toString()); } } @Test public void testPrint() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"))) { printer.printRecord("a", null, "b"); assertEquals("a,NULL,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testPrinter3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a, b", "b "); assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); } } @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\nc"); assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter6() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\r\nc"); assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter7() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", null, "b"); assertEquals("a,,b" + recordSeparator, sw.toString()); } } @Test public void testPrintOnePositiveInteger() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL))) { printer.print(Integer.MAX_VALUE); assertEquals(String.valueOf(Integer.MAX_VALUE), sw.toString()); } } @Test public void testPrintToFileWithCharsetUtf16Be() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); } @Test public void testPrintToFileWithDefaultCharset() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testPrintToPathWithDefaultCharset() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testQuoteAll() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL))) { printer.printRecord("a", "b\nc", "d"); assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); } } @Test public void testQuoteNonNumeric() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC))) { printer.printRecord("a", "b\nc", Integer.valueOf(1)); assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); } } @Test public void testRandomDefault() throws Exception { doRandom(CSVFormat.DEFAULT, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomExcel() throws Exception { doRandom(CSVFormat.EXCEL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomMySql() throws Exception { doRandom(CSVFormat.MYSQL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomRfc4180() throws Exception { doRandom(CSVFormat.RFC4180, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomTdf() throws Exception { doRandom(CSVFormat.TDF, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testSingleLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment"); assertEquals("# This is a comment" + recordSeparator, sw.toString()); } } @Test public void testSingleQuoteQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a'b'c"); printer.print("xyz"); assertEquals("'a''b''c',xyz", sw.toString()); } } @Test public void testSkipHeaderRecordFalse() throws IOException { // functionally identical to testHeader, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testSkipHeaderRecordTrue() throws IOException { // functionally identical to testHeaderNotSet, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testTrailingDelimiterOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrailingDelimiter())) { printer.printRecord("A", "B"); assertEquals("A,B,\r\n", sw.toString()); } } @Test public void testTrimOffOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim(false))) { printer.print(" A "); assertEquals("\" A \"", sw.toString()); } } @Test public void testTrimOnOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); assertEquals("A", sw.toString()); } } @Test public void testTrimOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); printer.print(" B "); assertEquals("A,B", sw.toString()); } } private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException { return CSVParser.parse(expected, format).getRecords().get(0).values(); } }
// You are a professional Java test case writer, please create a test case named `testEscapeNull1` for the issue `Csv-CSV-171`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-171 // // ## Issue-Title: // Negative numeric values in the first column are always quoted in minimal mode // // ## Issue-Description: // // Negative Numeric values are always quoted in minimal mode if (and only if) they are in the first column. // // // i.e. // // long,lat,data // // "-92.222",43.333,3 // // // Looking at the code, this is by design but seem to be for an unknown reason. // // // From v1.2 CSVPrinter line 230: // // // // TODO where did this rule come from? // // if (newRecord && (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { // // quote = true; // // } else ... // // // I propose this rule to either be remove or at a minimum be changed to: // // // TODO where did this rule come from? // // if (newRecord && (c !='-' && c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { // // quote = true; // // } else ... // // // // // @Test public void testEscapeNull1() throws IOException {
346
14
339
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
src/test/java
```markdown ## Issue-ID: Csv-CSV-171 ## Issue-Title: Negative numeric values in the first column are always quoted in minimal mode ## Issue-Description: Negative Numeric values are always quoted in minimal mode if (and only if) they are in the first column. i.e. long,lat,data "-92.222",43.333,3 Looking at the code, this is by design but seem to be for an unknown reason. From v1.2 CSVPrinter line 230: // TODO where did this rule come from? if (newRecord && (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { quote = true; } else ... I propose this rule to either be remove or at a minimum be changed to: // TODO where did this rule come from? if (newRecord && (c !='-' && c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { quote = true; } else ... ``` You are a professional Java test case writer, please create a test case named `testEscapeNull1` for the issue `Csv-CSV-171`, utilizing the provided issue report information and the following function signature. ```java @Test public void testEscapeNull1() throws IOException { ```
339
[ "org.apache.commons.csv.CSVFormat" ]
02fe4403d96ec0bdd25c23d282e89bcdffb04daeb609bf922ed558bc1139023e
@Test public void testEscapeNull1() throws IOException
// You are a professional Java test case writer, please create a test case named `testEscapeNull1` for the issue `Csv-CSV-171`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-171 // // ## Issue-Title: // Negative numeric values in the first column are always quoted in minimal mode // // ## Issue-Description: // // Negative Numeric values are always quoted in minimal mode if (and only if) they are in the first column. // // // i.e. // // long,lat,data // // "-92.222",43.333,3 // // // Looking at the code, this is by design but seem to be for an unknown reason. // // // From v1.2 CSVPrinter line 230: // // // // TODO where did this rule come from? // // if (newRecord && (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { // // quote = true; // // } else ... // // // I propose this rule to either be remove or at a minimum be changed to: // // // TODO where did this rule come from? // // if (newRecord && (c !='-' && c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { // // quote = true; // // } else ... // // // // //
Csv
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.apache.commons.csv.Constants.CR; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Random; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * * * @version $Id$ */ public class CSVPrinterTest { private static final char DQUOTE_CHAR = '"'; private static final char BACKSLASH_CH = '\\'; private static final char QUOTE_CH = '\''; private static final int ITERATIONS_FOR_RANDOM_TEST = 50000; private static String printable(final String s) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { final char ch = s.charAt(i); if (ch <= ' ' || ch >= 128) { sb.append("(").append((int) ch).append(")"); } else { sb.append(ch); } } return sb.toString(); } private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); private void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = generateLines(nLines, nCol); final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[]) lines[i]); } printer.flush(); } final String result = sw.toString(); // System.out.println("### :" + printable(result)); try (final CSVParser parser = CSVParser.parse(result, format)) { final List<CSVRecord> parseResult = parser.getRecords(); final String[][] expected = lines.clone(); for (int i = 0; i < expected.length; i++) { expected[i] = expectNulls(expected[i], format); } Utils.compare("Printer output :" + printable(result), expected, parseResult); } } private void doRandom(final CSVFormat format, final int iter) throws Exception { for (int i = 0; i < iter; i++) { doOneRandom(format); } } /** * Converts an input CSV array into expected output values WRT NULLs. NULL strings are converted to null values * because the parser will convert these strings to null. */ private <T> T[] expectNulls(final T[] original, final CSVFormat csvFormat) { final T[] fixed = original.clone(); for (int i = 0; i < fixed.length; i++) { if (Objects.equals(csvFormat.getNullString(), fixed[i])) { fixed[i] = null; } } return fixed; } private Connection geH2Connection() throws SQLException, ClassNotFoundException { Class.forName("org.h2.Driver"); return DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); } private String[][] generateLines(final int nLines, final int nCol) { final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } return lines; } private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) throws IOException { CSVFormat format = baseFormat; // Use withHeaderComments first to test CSV-145 format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); format = format.withCommentMarker('#'); format = format.withHeader("Col1", "Col2"); final CSVPrinter csvPrinter = format.print(sw); csvPrinter.printRecord("A", "B"); csvPrinter.printRecord("C", "D"); csvPrinter.close(); return csvPrinter; } private String randStr() { final Random r = new Random(); final int sz = r.nextInt(20); // sz = r.nextInt(3); final char[] buf = new char[sz]; for (int i = 0; i < sz; i++) { // stick in special chars with greater frequency char ch; final int what = r.nextInt(20); switch (what) { case 0: ch = '\r'; break; case 1: ch = '\n'; break; case 2: ch = '\t'; break; case 3: ch = '\f'; break; case 4: ch = ' '; break; case 5: ch = ','; break; case 6: ch = DQUOTE_CHAR; break; case 7: ch = '\''; break; case 8: ch = BACKSLASH_CH; break; default: ch = (char) r.nextInt(300); break; // default: ch = 'a'; break; } buf[i] = ch; } return new String(buf); } private void setUpTable(final Connection connection) throws SQLException { try (final Statement statement = connection.createStatement()) { statement.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); statement.execute("insert into TEST values(1, 'r1')"); statement.execute("insert into TEST values(2, 'r2')"); } } @Test public void testDelimeterQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("'a,b,c',xyz", sw.toString()); } } @Test public void testDelimeterQuoteNONE() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuoteMode(QuoteMode.NONE); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a,b,c,xyz", sw.toString()); } } @Test public void testDisabledComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printComment("This is a comment"); assertEquals("", sw.toString()); } } @Test public void testEOLEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a!rb!nc,x\fy\bz", sw.toString()); } } @Test public void testEOLPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a\rb\nc,x\fy\bz", sw.toString()); } } @Test public void testEOLQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a\rb\nc"); printer.print("x\by\fz"); assertEquals("'a\rb\nc',x\by\fz", sw.toString()); } } @Test public void testEscapeBackslash1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeBackslash2() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\r"); } assertEquals("'\\\r'", sw.toString()); } @Test public void testEscapeBackslash3() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("X\\\r"); } assertEquals("'X\\\r'", sw.toString()); } @Test public void testEscapeBackslash4() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeBackslash5() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeNull2() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\r"); } assertEquals("\"\\\r\"", sw.toString()); } @Test public void testEscapeNull3() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("X\\\r"); } assertEquals("\"X\\\r\"", sw.toString()); } @Test public void testEscapeNull4() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull5() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testExcelPrintAllArrayOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords((Object[]) new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( (Object[]) new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testHeader() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testHeaderCommentExcel() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.EXCEL; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1,Col2\r\nA,B\r\nC,D\r\n", sw.toString()); } } @Test public void testHeaderCommentTdf() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.TDF; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1\tCol2\r\nA\tB\r\nC\tD\r\n", sw.toString()); } } @Test public void testHeaderNotSet() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception { final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), invalidFormat)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); } } assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection();) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { printer.printRecords(resultSet); } } assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { printer.printRecords(resultSet); assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } } } @Test @Ignore public void testJira135_part1() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); printer.printRecord(list); } final String expected = "\"\\\"\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part2() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\n"); printer.printRecord(list); } final String expected = "\"\\n\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part3() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135All() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); list.add("\n"); list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\"\",\"\\n\",\"\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test public void testMultiLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment\non multiple lines"); assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); } } @Test public void testMySqlNullOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.MYSQL.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.NON_NUMERIC); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\"\tNULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test public void testMySqlNullStringDefault() { assertEquals("\\N", CSVFormat.MYSQL.getNullString()); } @Test(expected = IllegalArgumentException.class) public void testNewCsvPrinterAppendableNullFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), null)) { Assert.fail("This test should have thrown an exception."); } } @Test(expected = IllegalArgumentException.class) public void testNewCSVPrinterNullAppendableFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(null, CSVFormat.DEFAULT)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.printRecord("a", null, "b"); } final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); try (final CSVParser iterable = format.parse(new StringReader(csvString))) { final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); } } @Test public void testPlainEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("abc"); assertEquals("abc", sw.toString()); } } @Test public void testPrint() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"))) { printer.printRecord("a", null, "b"); assertEquals("a,NULL,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testPrinter3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a, b", "b "); assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); } } @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\nc"); assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter6() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\r\nc"); assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter7() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", null, "b"); assertEquals("a,,b" + recordSeparator, sw.toString()); } } @Test public void testPrintOnePositiveInteger() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL))) { printer.print(Integer.MAX_VALUE); assertEquals(String.valueOf(Integer.MAX_VALUE), sw.toString()); } } @Test public void testPrintToFileWithCharsetUtf16Be() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); } @Test public void testPrintToFileWithDefaultCharset() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testPrintToPathWithDefaultCharset() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testQuoteAll() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL))) { printer.printRecord("a", "b\nc", "d"); assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); } } @Test public void testQuoteNonNumeric() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC))) { printer.printRecord("a", "b\nc", Integer.valueOf(1)); assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); } } @Test public void testRandomDefault() throws Exception { doRandom(CSVFormat.DEFAULT, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomExcel() throws Exception { doRandom(CSVFormat.EXCEL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomMySql() throws Exception { doRandom(CSVFormat.MYSQL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomRfc4180() throws Exception { doRandom(CSVFormat.RFC4180, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomTdf() throws Exception { doRandom(CSVFormat.TDF, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testSingleLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment"); assertEquals("# This is a comment" + recordSeparator, sw.toString()); } } @Test public void testSingleQuoteQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a'b'c"); printer.print("xyz"); assertEquals("'a''b''c',xyz", sw.toString()); } } @Test public void testSkipHeaderRecordFalse() throws IOException { // functionally identical to testHeader, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testSkipHeaderRecordTrue() throws IOException { // functionally identical to testHeaderNotSet, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testTrailingDelimiterOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrailingDelimiter())) { printer.printRecord("A", "B"); assertEquals("A,B,\r\n", sw.toString()); } } @Test public void testTrimOffOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim(false))) { printer.print(" A "); assertEquals("\" A \"", sw.toString()); } } @Test public void testTrimOnOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); assertEquals("A", sw.toString()); } } @Test public void testTrimOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); printer.print(" B "); assertEquals("A,B", sw.toString()); } } private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException { return CSVParser.parse(expected, format).getRecords().get(0).values(); } }
@Test public void testChainedRemoveAttributes() { String html = "<a one two three four>Text</a>"; Document doc = Jsoup.parse(html); Element a = doc.select("a").first(); a .removeAttr("zero") .removeAttr("one") .removeAttr("two") .removeAttr("three") .removeAttr("four") .removeAttr("five"); assertEquals("<a>Text</a>", a.outerHtml()); }
org.jsoup.nodes.ElementTest::testChainedRemoveAttributes
src/test/java/org/jsoup/nodes/ElementTest.java
973
src/test/java/org/jsoup/nodes/ElementTest.java
testChainedRemoveAttributes
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetSiblingsWithDuplicateContent() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("this", p.nextElementSibling().nextElementSibling().text()); assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testElementSiblingIndexSameContent() { Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); } @Test public void testHasClassDomMethods() { Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); Element el = new Element(tag, "", attribs); attribs.put("class", "toto"); boolean hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto"); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "toto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "\ttoto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "ab"); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", " "); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", "tototo"); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", "raulpismuth "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd raulpismuth efgh "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd efgh raulpismuth"); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd efgh raulpismuth "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("CLASS", "second").text("now"); // manually specifying tag and attributes should now preserve case, regardless of parse mode assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><P CLASS=\"second\">now</P></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText(null); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testSetHtmlTitle() { Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>"); Element title = doc.getElementById("1"); title.html("good"); assertEquals("good", title.html()); title.html("<i>bad</i>"); assertEquals("&lt;i&gt;bad&lt;/i&gt;", title.html()); Element head = doc.getElementById("2"); head.html("<title><i>bad</i></title>"); assertEquals("<title>&lt;i&gt;bad&lt;/i&gt;</title>", head.html()); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testCssPath() { Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>"); Element divA = doc.select("div").get(0); Element divB = doc.select("div").get(1); Element divC = doc.select("div").get(2); assertEquals(divA.cssSelector(), "#id1"); assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); assertTrue(divA == doc.select(divA.cssSelector()).first()); assertTrue(divB == doc.select(divB.cssSelector()).first()); assertTrue(divC == doc.select(divC.cssSelector()).first()); } @Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2==div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<String>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length==3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); } @Test public void testHashAndEqualsAndValue() { // .equals and hashcode are identity. value is content. String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; Document doc = Jsoup.parse(doc1); Elements els = doc.select("p"); /* for (Element el : els) { System.out.println(el.hashCode() + " - " + el.outerHtml()); } 0 1534787905 - <p class="one">One</p> 1 1534787905 - <p class="one">One</p> 2 1539683239 - <p class="one">Two</p> 3 1535455211 - <p class="two">One</p> 4 1534787905 - <p class="one">One</p> 5 1534787905 - <p class="one">One</p> 6 1539683239 - <p class="one">Two</p> 7 1535455211 - <p class="two">One</p> */ assertEquals(8, els.size()); Element e0 = els.get(0); Element e1 = els.get(1); Element e2 = els.get(2); Element e3 = els.get(3); Element e4 = els.get(4); Element e5 = els.get(5); Element e6 = els.get(6); Element e7 = els.get(7); assertEquals(e0, e0); assertTrue(e0.hasSameValue(e1)); assertTrue(e0.hasSameValue(e4)); assertTrue(e0.hasSameValue(e5)); assertFalse(e0.equals(e2)); assertFalse(e0.hasSameValue(e2)); assertFalse(e0.hasSameValue(e3)); assertFalse(e0.hasSameValue(e6)); assertFalse(e0.hasSameValue(e7)); assertEquals(e0.hashCode(), e0.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } @Test public void testRelativeUrls() { String html = "<body><a href='./one.html'>One</a> <a href='two.html'>two</a> <a href='../three.html'>Three</a> <a href='//example2.com/four/'>Four</a> <a href='https://example2.com/five/'>Five</a>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("a"); assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); } @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<Element>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); } @Test public void testHashcodeIsStableWithContentChanges() { Element root = new Element(Tag.valueOf("root"), ""); HashSet<Element> set = new HashSet<Element>(); // Add root node: set.add(root); root.appendChild(new Element(Tag.valueOf("a"), "")); assertTrue(set.contains(root)); } @Test public void testNamespacedElements() { // Namespaces with ns:tag in HTML must be translated to ns|tag in CSS. String html = "<html><body><fb:comments /></body></html>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("fb|comments"); assertEquals(1, els.size()); assertEquals("html > body > fb|comments", els.get(0).cssSelector()); } @Test public void testChainedRemoveAttributes() { String html = "<a one two three four>Text</a>"; Document doc = Jsoup.parse(html); Element a = doc.select("a").first(); a .removeAttr("zero") .removeAttr("one") .removeAttr("two") .removeAttr("three") .removeAttr("four") .removeAttr("five"); assertEquals("<a>Text</a>", a.outerHtml()); } }
// You are a professional Java test case writer, please create a test case named `testChainedRemoveAttributes` for the issue `Jsoup-759`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-759 // // ## Issue-Title: // removeIgnoreCase ConcurrentModificationException // // ## Issue-Description: // When testing out the removeIgnoreCase method, I'm now seeing a ConcurrentModificationException with code like: element.select("abc").first().removeAttr("attr1").removeAttr("attr2"); // // // It appears to be due to using a foreach loop over the LinkedHashMap to do the removal. Changing to do the removal directly with an iterator fixes this issue. // // Like so: // // // // ``` // for (Iterator<Map.Entry<String, Attribute>> iter = attributes.entrySet().iterator(); iter.hasNext();) { // Map.Entry<String, Attribute> entry = iter.next(); // if (entry.getKey().equalsIgnoreCase("key1")) { // iter.remove(); // } // } // // ``` // // // @Test public void testChainedRemoveAttributes() {
973
57
960
src/test/java/org/jsoup/nodes/ElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-759 ## Issue-Title: removeIgnoreCase ConcurrentModificationException ## Issue-Description: When testing out the removeIgnoreCase method, I'm now seeing a ConcurrentModificationException with code like: element.select("abc").first().removeAttr("attr1").removeAttr("attr2"); It appears to be due to using a foreach loop over the LinkedHashMap to do the removal. Changing to do the removal directly with an iterator fixes this issue. Like so: ``` for (Iterator<Map.Entry<String, Attribute>> iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, Attribute> entry = iter.next(); if (entry.getKey().equalsIgnoreCase("key1")) { iter.remove(); } } ``` ``` You are a professional Java test case writer, please create a test case named `testChainedRemoveAttributes` for the issue `Jsoup-759`, utilizing the provided issue report information and the following function signature. ```java @Test public void testChainedRemoveAttributes() { ```
960
[ "org.jsoup.nodes.Attributes" ]
03861a74fcf192e0e0543153e3e1885a9c95b0146e24fe30efe83a989d95bccb
@Test public void testChainedRemoveAttributes()
// You are a professional Java test case writer, please create a test case named `testChainedRemoveAttributes` for the issue `Jsoup-759`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-759 // // ## Issue-Title: // removeIgnoreCase ConcurrentModificationException // // ## Issue-Description: // When testing out the removeIgnoreCase method, I'm now seeing a ConcurrentModificationException with code like: element.select("abc").first().removeAttr("attr1").removeAttr("attr2"); // // // It appears to be due to using a foreach loop over the LinkedHashMap to do the removal. Changing to do the removal directly with an iterator fixes this issue. // // Like so: // // // // ``` // for (Iterator<Map.Entry<String, Attribute>> iter = attributes.entrySet().iterator(); iter.hasNext();) { // Map.Entry<String, Attribute> entry = iter.next(); // if (entry.getKey().equalsIgnoreCase("key1")) { // iter.remove(); // } // } // // ``` // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetSiblingsWithDuplicateContent() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("this", p.nextElementSibling().nextElementSibling().text()); assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testElementSiblingIndexSameContent() { Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); } @Test public void testHasClassDomMethods() { Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); Element el = new Element(tag, "", attribs); attribs.put("class", "toto"); boolean hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto"); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "toto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "\ttoto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "ab"); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", " "); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", "tototo"); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", "raulpismuth "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd raulpismuth efgh "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd efgh raulpismuth"); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd efgh raulpismuth "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("CLASS", "second").text("now"); // manually specifying tag and attributes should now preserve case, regardless of parse mode assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><P CLASS=\"second\">now</P></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText(null); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testSetHtmlTitle() { Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>"); Element title = doc.getElementById("1"); title.html("good"); assertEquals("good", title.html()); title.html("<i>bad</i>"); assertEquals("&lt;i&gt;bad&lt;/i&gt;", title.html()); Element head = doc.getElementById("2"); head.html("<title><i>bad</i></title>"); assertEquals("<title>&lt;i&gt;bad&lt;/i&gt;</title>", head.html()); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testCssPath() { Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>"); Element divA = doc.select("div").get(0); Element divB = doc.select("div").get(1); Element divC = doc.select("div").get(2); assertEquals(divA.cssSelector(), "#id1"); assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); assertTrue(divA == doc.select(divA.cssSelector()).first()); assertTrue(divB == doc.select(divB.cssSelector()).first()); assertTrue(divC == doc.select(divC.cssSelector()).first()); } @Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2==div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<String>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length==3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); } @Test public void testHashAndEqualsAndValue() { // .equals and hashcode are identity. value is content. String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; Document doc = Jsoup.parse(doc1); Elements els = doc.select("p"); /* for (Element el : els) { System.out.println(el.hashCode() + " - " + el.outerHtml()); } 0 1534787905 - <p class="one">One</p> 1 1534787905 - <p class="one">One</p> 2 1539683239 - <p class="one">Two</p> 3 1535455211 - <p class="two">One</p> 4 1534787905 - <p class="one">One</p> 5 1534787905 - <p class="one">One</p> 6 1539683239 - <p class="one">Two</p> 7 1535455211 - <p class="two">One</p> */ assertEquals(8, els.size()); Element e0 = els.get(0); Element e1 = els.get(1); Element e2 = els.get(2); Element e3 = els.get(3); Element e4 = els.get(4); Element e5 = els.get(5); Element e6 = els.get(6); Element e7 = els.get(7); assertEquals(e0, e0); assertTrue(e0.hasSameValue(e1)); assertTrue(e0.hasSameValue(e4)); assertTrue(e0.hasSameValue(e5)); assertFalse(e0.equals(e2)); assertFalse(e0.hasSameValue(e2)); assertFalse(e0.hasSameValue(e3)); assertFalse(e0.hasSameValue(e6)); assertFalse(e0.hasSameValue(e7)); assertEquals(e0.hashCode(), e0.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } @Test public void testRelativeUrls() { String html = "<body><a href='./one.html'>One</a> <a href='two.html'>two</a> <a href='../three.html'>Three</a> <a href='//example2.com/four/'>Four</a> <a href='https://example2.com/five/'>Five</a>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("a"); assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); } @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<Element>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); } @Test public void testHashcodeIsStableWithContentChanges() { Element root = new Element(Tag.valueOf("root"), ""); HashSet<Element> set = new HashSet<Element>(); // Add root node: set.add(root); root.appendChild(new Element(Tag.valueOf("a"), "")); assertTrue(set.contains(root)); } @Test public void testNamespacedElements() { // Namespaces with ns:tag in HTML must be translated to ns|tag in CSS. String html = "<html><body><fb:comments /></body></html>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("fb|comments"); assertEquals(1, els.size()); assertEquals("html > body > fb|comments", els.get(0).cssSelector()); } @Test public void testChainedRemoveAttributes() { String html = "<a one two three four>Text</a>"; Document doc = Jsoup.parse(html); Element a = doc.select("a").first(); a .removeAttr("zero") .removeAttr("one") .removeAttr("two") .removeAttr("three") .removeAttr("four") .removeAttr("five"); assertEquals("<a>Text</a>", a.outerHtml()); } }
public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception { final String json = aposToQuotes("{'person_id':1234,'first_name':'John','last_name':'Doe','years_old':30,'living':true}"); final ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(json, Person.class); assertEquals(1234, person.getId()); assertNotNull(person.getName()); assertEquals("John", person.getName().getFirst()); assertEquals("Doe", person.getName().getLast()); assertEquals(30, person.getAge()); assertEquals(true, person.isAlive()); }
com.fasterxml.jackson.databind.deser.builder.BuilderWithUnwrappedTest::testWithUnwrappedAndCreatorSingleParameterAtBeginning
src/test/java/com/fasterxml/jackson/databind/deser/builder/BuilderWithUnwrappedTest.java
179
src/test/java/com/fasterxml/jackson/databind/deser/builder/BuilderWithUnwrappedTest.java
testWithUnwrappedAndCreatorSingleParameterAtBeginning
package com.fasterxml.jackson.databind.deser.builder; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; public class BuilderWithUnwrappedTest extends BaseMapTest { /* ************************************* * Mock classes ************************************* */ final static class Name { private final String first; private final String last; @JsonCreator Name( @JsonProperty("first_name") String first, @JsonProperty("last_name") String last ) { this.first = first; this.last = last; } String getFirst() { return first; } String getLast() { return last; } } @JsonDeserialize(builder = Person.Builder.class) final static class Person { private final long id; private final Name name; private final int age; private final boolean alive; private Person(Builder builder) { id = builder.id; name = builder.name; age = builder.age; alive = builder.alive; } long getId() { return id; } Name getName() { return name; } int getAge() { return age; } boolean isAlive() { return alive; } @JsonPOJOBuilder(withPrefix = "set") final static class Builder { private final long id; private Name name; private int age; private boolean alive; Builder(@JsonProperty("person_id") long id) { this.id = id; } @JsonUnwrapped void setName(Name name) { this.name = name; } @JsonProperty("years_old") void setAge(int age) { this.age = age; } @JsonProperty("living") void setAlive(boolean alive) { this.alive = alive; } Person build() { return new Person(this); } } } @JsonDeserialize(builder = Animal.Builder.class) final static class Animal { private final long id; private final Name name; private final int age; private final boolean alive; private Animal(Builder builder) { id = builder.id; name = builder.name; age = builder.age; alive = builder.alive; } long getId() { return id; } Name getName() { return name; } int getAge() { return age; } boolean isAlive() { return alive; } @JsonPOJOBuilder(withPrefix = "set") final static class Builder { private final long id; private Name name; private int age; private final boolean alive; Builder( @JsonProperty("animal_id") long id, @JsonProperty("living") boolean alive ) { this.id = id; this.alive = alive; } @JsonUnwrapped void setName(Name name) { this.name = name; } @JsonProperty("years_old") void setAge(int age) { this.age = age; } Animal build() { return new Animal(this); } } } /* ************************************* * Unit tests ************************************* */ public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception { final String json = aposToQuotes("{'person_id':1234,'first_name':'John','last_name':'Doe','years_old':30,'living':true}"); final ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(json, Person.class); assertEquals(1234, person.getId()); assertNotNull(person.getName()); assertEquals("John", person.getName().getFirst()); assertEquals("Doe", person.getName().getLast()); assertEquals(30, person.getAge()); assertEquals(true, person.isAlive()); } public void testWithUnwrappedAndCreatorSingleParameterInMiddle() throws Exception { final String json = aposToQuotes("{'first_name':'John','last_name':'Doe','person_id':1234,'years_old':30,'living':true}"); final ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(json, Person.class); assertEquals(1234, person.getId()); assertNotNull(person.getName()); assertEquals("John", person.getName().getFirst()); assertEquals("Doe", person.getName().getLast()); assertEquals(30, person.getAge()); assertEquals(true, person.isAlive()); } public void testWithUnwrappedAndCreatorSingleParameterAtEnd() throws Exception { final String json = aposToQuotes("{'first_name':'John','last_name':'Doe','years_old':30,'living':true,'person_id':1234}"); final ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(json, Person.class); assertEquals(1234, person.getId()); assertNotNull(person.getName()); assertEquals("John", person.getName().getFirst()); assertEquals("Doe", person.getName().getLast()); assertEquals(30, person.getAge()); assertEquals(true, person.isAlive()); } public void testWithUnwrappedAndCreatorMultipleParametersAtBeginning() throws Exception { final String json = aposToQuotes("{'animal_id':1234,'living':true,'first_name':'John','last_name':'Doe','years_old':30}"); final ObjectMapper mapper = new ObjectMapper(); Animal animal = mapper.readValue(json, Animal.class); assertEquals(1234, animal.getId()); assertNotNull(animal.getName()); assertEquals("John", animal.getName().getFirst()); assertEquals("Doe", animal.getName().getLast()); assertEquals(30, animal.getAge()); assertEquals(true, animal.isAlive()); } public void testWithUnwrappedAndCreatorMultipleParametersInMiddle() throws Exception { final String json = aposToQuotes("{'first_name':'John','animal_id':1234,'last_name':'Doe','living':true,'years_old':30}"); final ObjectMapper mapper = new ObjectMapper(); Animal animal = mapper.readValue(json, Animal.class); assertEquals(1234, animal.getId()); assertNotNull(animal.getName()); assertEquals("John", animal.getName().getFirst()); assertEquals("Doe", animal.getName().getLast()); assertEquals(30, animal.getAge()); assertEquals(true, animal.isAlive()); } public void testWithUnwrappedAndCreatorMultipleParametersAtEnd() throws Exception { final String json = aposToQuotes("{'first_name':'John','last_name':'Doe','years_old':30,'living':true,'animal_id':1234}"); final ObjectMapper mapper = new ObjectMapper(); Animal animal = mapper.readValue(json, Animal.class); assertEquals(1234, animal.getId()); assertNotNull(animal.getName()); assertEquals("John", animal.getName().getFirst()); assertEquals("Doe", animal.getName().getLast()); assertEquals(30, animal.getAge()); assertEquals(true, animal.isAlive()); } }
// You are a professional Java test case writer, please create a test case named `testWithUnwrappedAndCreatorSingleParameterAtBeginning` for the issue `JacksonDatabind-1573`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1573 // // ## Issue-Title: // Missing properties when deserializing using a builder class with a non-default constructor and a mutator annotated with @JsonUnwrapped // // ## Issue-Description: // When deserializing using a builder class with a non-default constructor and any number of mutator methods annotated with @JsonUnwrapped, the `BuilderBasedDeserializer::deserializeUsingPropertyBasedWithUnwrapped` method cuts short the process of adding SettableBeanProperties. // // // The logic dictates that once all properties necessary to construct the builder have been found, the builder is constructed using all known SettableBeanProperties that have been found up to that point in the tokenizing process. // // // Therefore, in the case that the builder has a single property required for construction, and that property is found anywhere other than at the end of the JSON content, any properties subsequent to the constructor property are not evaluated and are left with their default values. // // // Given the following classes: // // // // ``` // @JsonDeserialize(builder = Employee.Builder.class) // public class Employee { // private final long id; // private final Name name; // private final int age; // // private Employee(Builder builder) { // id = builder.id; // name = builder.name; // age = builder.age; // } // // public long getId() { // return id; // } // // public Name getName() { // return name; // } // // public int getAge() { // return age; // } // // @JsonPOJOBuilder(withPrefix = "set") // public static class Builder { // private final long id; // private Name name; // private int age; // // @JsonCreator // public Builder(@JsonProperty("emp\_id") long id) { // this.id = id; // } // // @JsonUnwrapped // public void setName(Name name) { // this.name = name; // } // // @JsonProperty("emp\_age") // public void setAge(int age) { // this.age = age; // } // // public Employee build() { // return new Employee(this); // } // } // } // // public class Name { // private final String first; // private final String last; // // @JsonCreator // public Name( // @JsonProperty("emp\_first\_name") String first, // @JsonProperty("emp\_last\_name") String last // ) { // this.first = first; // this.last = last; // } // // public String getFirst() { // return first; // } // // public String getLast() { // return last; // } // } // ``` // // And given the following JSON string: // // // // ``` // { // "emp\_age": 30, // "emp\_id": 1234, // "emp\_first\_name": "John", // "emp\_last\_name": "Doe" // } // ``` // // We will see the following output: // // // // ``` // Employee emp = new ObjectMapper().readValue(json, Employee.class); // // System.out.println(emp.getAge()); // public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception {
179
/* ************************************* * Unit tests ************************************* */
76
168
src/test/java/com/fasterxml/jackson/databind/deser/builder/BuilderWithUnwrappedTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1573 ## Issue-Title: Missing properties when deserializing using a builder class with a non-default constructor and a mutator annotated with @JsonUnwrapped ## Issue-Description: When deserializing using a builder class with a non-default constructor and any number of mutator methods annotated with @JsonUnwrapped, the `BuilderBasedDeserializer::deserializeUsingPropertyBasedWithUnwrapped` method cuts short the process of adding SettableBeanProperties. The logic dictates that once all properties necessary to construct the builder have been found, the builder is constructed using all known SettableBeanProperties that have been found up to that point in the tokenizing process. Therefore, in the case that the builder has a single property required for construction, and that property is found anywhere other than at the end of the JSON content, any properties subsequent to the constructor property are not evaluated and are left with their default values. Given the following classes: ``` @JsonDeserialize(builder = Employee.Builder.class) public class Employee { private final long id; private final Name name; private final int age; private Employee(Builder builder) { id = builder.id; name = builder.name; age = builder.age; } public long getId() { return id; } public Name getName() { return name; } public int getAge() { return age; } @JsonPOJOBuilder(withPrefix = "set") public static class Builder { private final long id; private Name name; private int age; @JsonCreator public Builder(@JsonProperty("emp\_id") long id) { this.id = id; } @JsonUnwrapped public void setName(Name name) { this.name = name; } @JsonProperty("emp\_age") public void setAge(int age) { this.age = age; } public Employee build() { return new Employee(this); } } } public class Name { private final String first; private final String last; @JsonCreator public Name( @JsonProperty("emp\_first\_name") String first, @JsonProperty("emp\_last\_name") String last ) { this.first = first; this.last = last; } public String getFirst() { return first; } public String getLast() { return last; } } ``` And given the following JSON string: ``` { "emp\_age": 30, "emp\_id": 1234, "emp\_first\_name": "John", "emp\_last\_name": "Doe" } ``` We will see the following output: ``` Employee emp = new ObjectMapper().readValue(json, Employee.class); System.out.println(emp.getAge()); // ``` You are a professional Java test case writer, please create a test case named `testWithUnwrappedAndCreatorSingleParameterAtBeginning` for the issue `JacksonDatabind-1573`, utilizing the provided issue report information and the following function signature. ```java public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception { ```
168
[ "com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer" ]
0401bac6c0aa608166d12da47792008573fda3176ab1774de2b9f86ea7aabd03
public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception
// You are a professional Java test case writer, please create a test case named `testWithUnwrappedAndCreatorSingleParameterAtBeginning` for the issue `JacksonDatabind-1573`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1573 // // ## Issue-Title: // Missing properties when deserializing using a builder class with a non-default constructor and a mutator annotated with @JsonUnwrapped // // ## Issue-Description: // When deserializing using a builder class with a non-default constructor and any number of mutator methods annotated with @JsonUnwrapped, the `BuilderBasedDeserializer::deserializeUsingPropertyBasedWithUnwrapped` method cuts short the process of adding SettableBeanProperties. // // // The logic dictates that once all properties necessary to construct the builder have been found, the builder is constructed using all known SettableBeanProperties that have been found up to that point in the tokenizing process. // // // Therefore, in the case that the builder has a single property required for construction, and that property is found anywhere other than at the end of the JSON content, any properties subsequent to the constructor property are not evaluated and are left with their default values. // // // Given the following classes: // // // // ``` // @JsonDeserialize(builder = Employee.Builder.class) // public class Employee { // private final long id; // private final Name name; // private final int age; // // private Employee(Builder builder) { // id = builder.id; // name = builder.name; // age = builder.age; // } // // public long getId() { // return id; // } // // public Name getName() { // return name; // } // // public int getAge() { // return age; // } // // @JsonPOJOBuilder(withPrefix = "set") // public static class Builder { // private final long id; // private Name name; // private int age; // // @JsonCreator // public Builder(@JsonProperty("emp\_id") long id) { // this.id = id; // } // // @JsonUnwrapped // public void setName(Name name) { // this.name = name; // } // // @JsonProperty("emp\_age") // public void setAge(int age) { // this.age = age; // } // // public Employee build() { // return new Employee(this); // } // } // } // // public class Name { // private final String first; // private final String last; // // @JsonCreator // public Name( // @JsonProperty("emp\_first\_name") String first, // @JsonProperty("emp\_last\_name") String last // ) { // this.first = first; // this.last = last; // } // // public String getFirst() { // return first; // } // // public String getLast() { // return last; // } // } // ``` // // And given the following JSON string: // // // // ``` // { // "emp\_age": 30, // "emp\_id": 1234, // "emp\_first\_name": "John", // "emp\_last\_name": "Doe" // } // ``` // // We will see the following output: // // // // ``` // Employee emp = new ObjectMapper().readValue(json, Employee.class); // // System.out.println(emp.getAge()); //
JacksonDatabind
package com.fasterxml.jackson.databind.deser.builder; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; public class BuilderWithUnwrappedTest extends BaseMapTest { /* ************************************* * Mock classes ************************************* */ final static class Name { private final String first; private final String last; @JsonCreator Name( @JsonProperty("first_name") String first, @JsonProperty("last_name") String last ) { this.first = first; this.last = last; } String getFirst() { return first; } String getLast() { return last; } } @JsonDeserialize(builder = Person.Builder.class) final static class Person { private final long id; private final Name name; private final int age; private final boolean alive; private Person(Builder builder) { id = builder.id; name = builder.name; age = builder.age; alive = builder.alive; } long getId() { return id; } Name getName() { return name; } int getAge() { return age; } boolean isAlive() { return alive; } @JsonPOJOBuilder(withPrefix = "set") final static class Builder { private final long id; private Name name; private int age; private boolean alive; Builder(@JsonProperty("person_id") long id) { this.id = id; } @JsonUnwrapped void setName(Name name) { this.name = name; } @JsonProperty("years_old") void setAge(int age) { this.age = age; } @JsonProperty("living") void setAlive(boolean alive) { this.alive = alive; } Person build() { return new Person(this); } } } @JsonDeserialize(builder = Animal.Builder.class) final static class Animal { private final long id; private final Name name; private final int age; private final boolean alive; private Animal(Builder builder) { id = builder.id; name = builder.name; age = builder.age; alive = builder.alive; } long getId() { return id; } Name getName() { return name; } int getAge() { return age; } boolean isAlive() { return alive; } @JsonPOJOBuilder(withPrefix = "set") final static class Builder { private final long id; private Name name; private int age; private final boolean alive; Builder( @JsonProperty("animal_id") long id, @JsonProperty("living") boolean alive ) { this.id = id; this.alive = alive; } @JsonUnwrapped void setName(Name name) { this.name = name; } @JsonProperty("years_old") void setAge(int age) { this.age = age; } Animal build() { return new Animal(this); } } } /* ************************************* * Unit tests ************************************* */ public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception { final String json = aposToQuotes("{'person_id':1234,'first_name':'John','last_name':'Doe','years_old':30,'living':true}"); final ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(json, Person.class); assertEquals(1234, person.getId()); assertNotNull(person.getName()); assertEquals("John", person.getName().getFirst()); assertEquals("Doe", person.getName().getLast()); assertEquals(30, person.getAge()); assertEquals(true, person.isAlive()); } public void testWithUnwrappedAndCreatorSingleParameterInMiddle() throws Exception { final String json = aposToQuotes("{'first_name':'John','last_name':'Doe','person_id':1234,'years_old':30,'living':true}"); final ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(json, Person.class); assertEquals(1234, person.getId()); assertNotNull(person.getName()); assertEquals("John", person.getName().getFirst()); assertEquals("Doe", person.getName().getLast()); assertEquals(30, person.getAge()); assertEquals(true, person.isAlive()); } public void testWithUnwrappedAndCreatorSingleParameterAtEnd() throws Exception { final String json = aposToQuotes("{'first_name':'John','last_name':'Doe','years_old':30,'living':true,'person_id':1234}"); final ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(json, Person.class); assertEquals(1234, person.getId()); assertNotNull(person.getName()); assertEquals("John", person.getName().getFirst()); assertEquals("Doe", person.getName().getLast()); assertEquals(30, person.getAge()); assertEquals(true, person.isAlive()); } public void testWithUnwrappedAndCreatorMultipleParametersAtBeginning() throws Exception { final String json = aposToQuotes("{'animal_id':1234,'living':true,'first_name':'John','last_name':'Doe','years_old':30}"); final ObjectMapper mapper = new ObjectMapper(); Animal animal = mapper.readValue(json, Animal.class); assertEquals(1234, animal.getId()); assertNotNull(animal.getName()); assertEquals("John", animal.getName().getFirst()); assertEquals("Doe", animal.getName().getLast()); assertEquals(30, animal.getAge()); assertEquals(true, animal.isAlive()); } public void testWithUnwrappedAndCreatorMultipleParametersInMiddle() throws Exception { final String json = aposToQuotes("{'first_name':'John','animal_id':1234,'last_name':'Doe','living':true,'years_old':30}"); final ObjectMapper mapper = new ObjectMapper(); Animal animal = mapper.readValue(json, Animal.class); assertEquals(1234, animal.getId()); assertNotNull(animal.getName()); assertEquals("John", animal.getName().getFirst()); assertEquals("Doe", animal.getName().getLast()); assertEquals(30, animal.getAge()); assertEquals(true, animal.isAlive()); } public void testWithUnwrappedAndCreatorMultipleParametersAtEnd() throws Exception { final String json = aposToQuotes("{'first_name':'John','last_name':'Doe','years_old':30,'living':true,'animal_id':1234}"); final ObjectMapper mapper = new ObjectMapper(); Animal animal = mapper.readValue(json, Animal.class); assertEquals(1234, animal.getId()); assertNotNull(animal.getName()); assertEquals("John", animal.getName().getFirst()); assertEquals("Doe", animal.getName().getLast()); assertEquals(30, animal.getAge()); assertEquals(true, animal.isAlive()); } }
@Test public void survivesPaxHeaderWithNameEndingInSlash() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-356.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("package/package.json", entry.getName()); assertNull(is.getNextTarEntry()); } finally { is.close(); } }
org.apache.commons.compress.archivers.tar.TarArchiveInputStreamTest::survivesPaxHeaderWithNameEndingInSlash
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
328
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
survivesPaxHeaderWithNameEndingInSlash
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.tar; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.apache.commons.compress.AbstractTestCase.mkdir; import static org.apache.commons.compress.AbstractTestCase.rmdir; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.Date; import java.util.Map; import java.util.TimeZone; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.utils.CharsetNames; import org.apache.commons.compress.utils.IOUtils; import org.junit.Test; public class TarArchiveInputStreamTest { @Test public void readSimplePaxHeader() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("1321711775.972059463", headers.get("atime")); tais.close(); } @Test public void secondEntryWinsWhenPaxHeaderContainsDuplicateKey() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n11 foo=baz\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("baz", headers.get("foo")); tais.close(); } @Test public void paxHeaderEntryWithEmptyValueRemovesKey() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n7 foo=\n" .getBytes(CharsetNames.UTF_8))); assertEquals(0, headers.size()); tais.close(); } @Test public void readPaxHeaderWithEmbeddedNewline() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("line1\nline2\nand3", headers.get("comment")); tais.close(); } @Test public void readNonAsciiPaxHeader() throws Exception { final String ae = "\u00e4"; final String line = "11 path="+ ae + "\n"; assertEquals(11, line.getBytes(CharsetNames.UTF_8).length); final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals(ae, headers.get("path")); tais.close(); } @Test public void workaroundForBrokenTimeHeader() throws Exception { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(getFile("simple-aix-native-tar.tar"))); TarArchiveEntry tae = in.getNextTarEntry(); tae = in.getNextTarEntry(); assertEquals("sample/link-to-txt-file.lnk", tae.getName()); assertEquals(new Date(0), tae.getLastModifiedDate()); assertTrue(tae.isSymbolicLink()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } } @Test public void datePriorToEpochInGNUFormat() throws Exception { datePriorToEpoch("preepoch-star.tar"); } @Test public void datePriorToEpochInPAXFormat() throws Exception { datePriorToEpoch("preepoch-posix.tar"); } private void datePriorToEpoch(final String archive) throws Exception { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(getFile(archive))); final TarArchiveEntry tae = in.getNextTarEntry(); assertEquals("foo", tae.getName()); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.set(1969, 11, 31, 23, 59, 59); cal.set(Calendar.MILLISECOND, 0); assertEquals(cal.getTime(), tae.getLastModifiedDate()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } } @Test public void testCompress197() throws Exception { final TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar"); try { TarArchiveEntry entry = tar.getNextTarEntry(); while (entry != null) { entry = tar.getNextTarEntry(); } } catch (final IOException e) { fail("COMPRESS-197: " + e.getMessage()); } finally { tar.close(); } } @Test public void shouldUseSpecifiedEncodingWhenReadingGNULongNames() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final String encoding = CharsetNames.UTF_16; final String name = "1234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789" + "01234567890\u00e4"; final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos, encoding); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry t = new TarArchiveEntry(name); t.setSize(1); tos.putArchiveEntry(t); tos.write(30); tos.closeArchiveEntry(); tos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); final TarArchiveInputStream tis = new TarArchiveInputStream(bis, encoding); t = tis.getNextTarEntry(); assertEquals(name, t.getName()); tis.close(); } @Test public void shouldConsumeArchiveCompletely() throws Exception { final InputStream is = TarArchiveInputStreamTest.class .getResourceAsStream("/archive_with_trailer.tar"); final TarArchiveInputStream tar = new TarArchiveInputStream(is); while (tar.getNextTarEntry() != null) { // just consume the archive } final byte[] expected = new byte[] { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n' }; final byte[] actual = new byte[expected.length]; is.read(actual); assertArrayEquals(expected, actual); tar.close(); } @Test public void readsArchiveCompletely_COMPRESS245() throws Exception { final InputStream is = TarArchiveInputStreamTest.class .getResourceAsStream("/COMPRESS-245.tar.gz"); try { final InputStream gin = new GZIPInputStream(is); final TarArchiveInputStream tar = new TarArchiveInputStream(gin); int count = 0; TarArchiveEntry entry = tar.getNextTarEntry(); while (entry != null) { count++; entry = tar.getNextTarEntry(); } assertEquals(31, count); tar.close(); } catch (final IOException e) { fail("COMPRESS-245: " + e.getMessage()); } finally { is.close(); } } @Test(expected = IOException.class) public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception { final File dir = mkdir("COMPRESS-279"); final TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar"); FileOutputStream out = null; try { TarArchiveEntry entry = is.getNextTarEntry(); int count = 0; while (entry != null) { out = new FileOutputStream(new File(dir, String.valueOf(count))); IOUtils.copy(is, out); out.close(); out = null; count++; entry = is.getNextTarEntry(); } } finally { is.close(); if (out != null) { out.close(); } rmdir(dir); } } @Test public void shouldReadBigGid() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos); tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); TarArchiveEntry t = new TarArchiveEntry("name"); t.setGroupId(4294967294l); t.setSize(1); tos.putArchiveEntry(t); tos.write(30); tos.closeArchiveEntry(); tos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); final TarArchiveInputStream tis = new TarArchiveInputStream(bis); t = tis.getNextTarEntry(); assertEquals(4294967294l, t.getLongGroupId()); tis.close(); } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-324" */ @Test public void shouldReadGNULongNameEntryWithWrongName() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-324.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890.txt", entry.getName()); } finally { is.close(); } } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-355" */ @Test public void survivesBlankLinesInPaxHeader() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-355.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("package/package.json", entry.getName()); assertNull(is.getNextTarEntry()); } finally { is.close(); } } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-356" */ @Test public void survivesPaxHeaderWithNameEndingInSlash() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-356.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("package/package.json", entry.getName()); assertNull(is.getNextTarEntry()); } finally { is.close(); } } private TarArchiveInputStream getTestStream(final String name) { return new TarArchiveInputStream( TarArchiveInputStreamTest.class.getResourceAsStream(name)); } }
// You are a professional Java test case writer, please create a test case named `survivesPaxHeaderWithNameEndingInSlash` for the issue `Compress-COMPRESS-356`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-356 // // ## Issue-Title: // PAX header entry name ending with / causes problems // // ## Issue-Description: // // There seems to be a problem when a PAX header entry (link flag is 'x') has a name ending with "/". The TarArchiveEntry.isDirectory() check ends up returning true because of the trailing slash which means no content can be read from the entry. PAX header parsing effectively finds nothing and the stream is not advanced; this leaves the stream in a bad state as the next entry's header is actually read from the header contents. // // // If the name is modified to remove the trailing slash when the link flag indicates a PAX header everything seems to work fine. That would be one potential fix in parseTarHeader. Changing isDirectory to return false if isPaxHeader is true (before the trailing "/" check) would probably also fix the issue (though I can't verify that in the debugger like I can with changing the name). // // // So far I have only seen this when using Docker to save images that contain a yum database. For example: // // // // // ``` // docker pull centos:latest && docker save centos:latest | tar x --include "*/layer.tar" // // ``` // // // Will produce at least one "layer.tar" that exhibits this issue. If I come across a smaller TAR for testing I will attach it. // // // // // @Test public void survivesPaxHeaderWithNameEndingInSlash() throws Exception {
328
/** * @link "https://issues.apache.org/jira/browse/COMPRESS-356" */
38
318
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-356 ## Issue-Title: PAX header entry name ending with / causes problems ## Issue-Description: There seems to be a problem when a PAX header entry (link flag is 'x') has a name ending with "/". The TarArchiveEntry.isDirectory() check ends up returning true because of the trailing slash which means no content can be read from the entry. PAX header parsing effectively finds nothing and the stream is not advanced; this leaves the stream in a bad state as the next entry's header is actually read from the header contents. If the name is modified to remove the trailing slash when the link flag indicates a PAX header everything seems to work fine. That would be one potential fix in parseTarHeader. Changing isDirectory to return false if isPaxHeader is true (before the trailing "/" check) would probably also fix the issue (though I can't verify that in the debugger like I can with changing the name). So far I have only seen this when using Docker to save images that contain a yum database. For example: ``` docker pull centos:latest && docker save centos:latest | tar x --include "*/layer.tar" ``` Will produce at least one "layer.tar" that exhibits this issue. If I come across a smaller TAR for testing I will attach it. ``` You are a professional Java test case writer, please create a test case named `survivesPaxHeaderWithNameEndingInSlash` for the issue `Compress-COMPRESS-356`, utilizing the provided issue report information and the following function signature. ```java @Test public void survivesPaxHeaderWithNameEndingInSlash() throws Exception { ```
318
[ "org.apache.commons.compress.archivers.tar.TarArchiveEntry" ]
0415194838d24fbbc7c6bba450f676fa746588c1e44179aae34c4601d66b3b6b
@Test public void survivesPaxHeaderWithNameEndingInSlash() throws Exception
// You are a professional Java test case writer, please create a test case named `survivesPaxHeaderWithNameEndingInSlash` for the issue `Compress-COMPRESS-356`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-356 // // ## Issue-Title: // PAX header entry name ending with / causes problems // // ## Issue-Description: // // There seems to be a problem when a PAX header entry (link flag is 'x') has a name ending with "/". The TarArchiveEntry.isDirectory() check ends up returning true because of the trailing slash which means no content can be read from the entry. PAX header parsing effectively finds nothing and the stream is not advanced; this leaves the stream in a bad state as the next entry's header is actually read from the header contents. // // // If the name is modified to remove the trailing slash when the link flag indicates a PAX header everything seems to work fine. That would be one potential fix in parseTarHeader. Changing isDirectory to return false if isPaxHeader is true (before the trailing "/" check) would probably also fix the issue (though I can't verify that in the debugger like I can with changing the name). // // // So far I have only seen this when using Docker to save images that contain a yum database. For example: // // // // // ``` // docker pull centos:latest && docker save centos:latest | tar x --include "*/layer.tar" // // ``` // // // Will produce at least one "layer.tar" that exhibits this issue. If I come across a smaller TAR for testing I will attach it. // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.tar; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.apache.commons.compress.AbstractTestCase.mkdir; import static org.apache.commons.compress.AbstractTestCase.rmdir; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.Date; import java.util.Map; import java.util.TimeZone; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.utils.CharsetNames; import org.apache.commons.compress.utils.IOUtils; import org.junit.Test; public class TarArchiveInputStreamTest { @Test public void readSimplePaxHeader() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("1321711775.972059463", headers.get("atime")); tais.close(); } @Test public void secondEntryWinsWhenPaxHeaderContainsDuplicateKey() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n11 foo=baz\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("baz", headers.get("foo")); tais.close(); } @Test public void paxHeaderEntryWithEmptyValueRemovesKey() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n7 foo=\n" .getBytes(CharsetNames.UTF_8))); assertEquals(0, headers.size()); tais.close(); } @Test public void readPaxHeaderWithEmbeddedNewline() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("line1\nline2\nand3", headers.get("comment")); tais.close(); } @Test public void readNonAsciiPaxHeader() throws Exception { final String ae = "\u00e4"; final String line = "11 path="+ ae + "\n"; assertEquals(11, line.getBytes(CharsetNames.UTF_8).length); final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals(ae, headers.get("path")); tais.close(); } @Test public void workaroundForBrokenTimeHeader() throws Exception { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(getFile("simple-aix-native-tar.tar"))); TarArchiveEntry tae = in.getNextTarEntry(); tae = in.getNextTarEntry(); assertEquals("sample/link-to-txt-file.lnk", tae.getName()); assertEquals(new Date(0), tae.getLastModifiedDate()); assertTrue(tae.isSymbolicLink()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } } @Test public void datePriorToEpochInGNUFormat() throws Exception { datePriorToEpoch("preepoch-star.tar"); } @Test public void datePriorToEpochInPAXFormat() throws Exception { datePriorToEpoch("preepoch-posix.tar"); } private void datePriorToEpoch(final String archive) throws Exception { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(getFile(archive))); final TarArchiveEntry tae = in.getNextTarEntry(); assertEquals("foo", tae.getName()); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.set(1969, 11, 31, 23, 59, 59); cal.set(Calendar.MILLISECOND, 0); assertEquals(cal.getTime(), tae.getLastModifiedDate()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } } @Test public void testCompress197() throws Exception { final TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar"); try { TarArchiveEntry entry = tar.getNextTarEntry(); while (entry != null) { entry = tar.getNextTarEntry(); } } catch (final IOException e) { fail("COMPRESS-197: " + e.getMessage()); } finally { tar.close(); } } @Test public void shouldUseSpecifiedEncodingWhenReadingGNULongNames() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final String encoding = CharsetNames.UTF_16; final String name = "1234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789" + "01234567890\u00e4"; final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos, encoding); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry t = new TarArchiveEntry(name); t.setSize(1); tos.putArchiveEntry(t); tos.write(30); tos.closeArchiveEntry(); tos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); final TarArchiveInputStream tis = new TarArchiveInputStream(bis, encoding); t = tis.getNextTarEntry(); assertEquals(name, t.getName()); tis.close(); } @Test public void shouldConsumeArchiveCompletely() throws Exception { final InputStream is = TarArchiveInputStreamTest.class .getResourceAsStream("/archive_with_trailer.tar"); final TarArchiveInputStream tar = new TarArchiveInputStream(is); while (tar.getNextTarEntry() != null) { // just consume the archive } final byte[] expected = new byte[] { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n' }; final byte[] actual = new byte[expected.length]; is.read(actual); assertArrayEquals(expected, actual); tar.close(); } @Test public void readsArchiveCompletely_COMPRESS245() throws Exception { final InputStream is = TarArchiveInputStreamTest.class .getResourceAsStream("/COMPRESS-245.tar.gz"); try { final InputStream gin = new GZIPInputStream(is); final TarArchiveInputStream tar = new TarArchiveInputStream(gin); int count = 0; TarArchiveEntry entry = tar.getNextTarEntry(); while (entry != null) { count++; entry = tar.getNextTarEntry(); } assertEquals(31, count); tar.close(); } catch (final IOException e) { fail("COMPRESS-245: " + e.getMessage()); } finally { is.close(); } } @Test(expected = IOException.class) public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception { final File dir = mkdir("COMPRESS-279"); final TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar"); FileOutputStream out = null; try { TarArchiveEntry entry = is.getNextTarEntry(); int count = 0; while (entry != null) { out = new FileOutputStream(new File(dir, String.valueOf(count))); IOUtils.copy(is, out); out.close(); out = null; count++; entry = is.getNextTarEntry(); } } finally { is.close(); if (out != null) { out.close(); } rmdir(dir); } } @Test public void shouldReadBigGid() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos); tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); TarArchiveEntry t = new TarArchiveEntry("name"); t.setGroupId(4294967294l); t.setSize(1); tos.putArchiveEntry(t); tos.write(30); tos.closeArchiveEntry(); tos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); final TarArchiveInputStream tis = new TarArchiveInputStream(bis); t = tis.getNextTarEntry(); assertEquals(4294967294l, t.getLongGroupId()); tis.close(); } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-324" */ @Test public void shouldReadGNULongNameEntryWithWrongName() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-324.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890.txt", entry.getName()); } finally { is.close(); } } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-355" */ @Test public void survivesBlankLinesInPaxHeader() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-355.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("package/package.json", entry.getName()); assertNull(is.getNextTarEntry()); } finally { is.close(); } } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-356" */ @Test public void survivesPaxHeaderWithNameEndingInSlash() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-356.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("package/package.json", entry.getName()); assertNull(is.getNextTarEntry()); } finally { is.close(); } } private TarArchiveInputStream getTestStream(final String name) { return new TarArchiveInputStream( TarArchiveInputStreamTest.class.getResourceAsStream(name)); } }
@Test public void testReadingOfFirstStoredEntry() throws Exception { ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-264.zip"))); try { ZipArchiveEntry ze = in.getNextZipEntry(); assertEquals(5, ze.getSize()); assertArrayEquals(new byte[] {'d', 'a', 't', 'a', '\n'}, IOUtils.toByteArray(in)); } finally { in.close(); } }
org.apache.commons.compress.archivers.zip.ZipArchiveInputStreamTest::testReadingOfFirstStoredEntry
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
170
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
testReadingOfFirstStoredEntry
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import org.apache.commons.compress.utils.IOUtils; import org.junit.Test; public class ZipArchiveInputStreamTest { /** * @see "https://issues.apache.org/jira/browse/COMPRESS-176" */ @Test public void winzipBackSlashWorkaround() throws Exception { ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(getFile("test-winzip.zip"))); ZipArchiveEntry zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); assertEquals("\u00e4/", zae.getName()); } finally { if (in != null) { in.close(); } } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-189" */ @Test public void properUseOfInflater() throws Exception { ZipFile zf = null; ZipArchiveInputStream in = null; try { zf = new ZipFile(getFile("COMPRESS-189.zip")); ZipArchiveEntry zae = zf.getEntry("USD0558682-20080101.ZIP"); in = new ZipArchiveInputStream(new BufferedInputStream(zf.getInputStream(zae))); ZipArchiveEntry innerEntry; while ((innerEntry = in.getNextZipEntry()) != null) { if (innerEntry.getName().endsWith("XML")) { assertTrue(0 < in.read()); } } } finally { if (zf != null) { zf.close(); } if (in != null) { in.close(); } } } @Test public void shouldConsumeArchiveCompletely() throws Exception { InputStream is = ZipArchiveInputStreamTest.class .getResourceAsStream("/archive_with_trailer.zip"); ZipArchiveInputStream zip = new ZipArchiveInputStream(is); while (zip.getNextZipEntry() != null) { // just consume the archive } byte[] expected = new byte[] { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n' }; byte[] actual = new byte[expected.length]; is.read(actual); assertArrayEquals(expected, actual); zip.close(); } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-219" */ @Test public void shouldReadNestedZip() throws IOException { ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-219.zip"))); extractZipInputStream(in); } finally { if (in != null) { in.close(); } } } private void extractZipInputStream(final ZipArchiveInputStream in) throws IOException { ZipArchiveEntry zae = in.getNextZipEntry(); while (zae != null) { if (zae.getName().endsWith(".zip")) { extractZipInputStream(new ZipArchiveInputStream(in)); } zae = in.getNextZipEntry(); } } @Test public void testUnshrinkEntry() throws Exception { ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("SHRUNK.ZIP"))); ZipArchiveEntry entry = in.getNextZipEntry(); assertEquals("method", ZipMethod.UNSHRINKING.getCode(), entry.getMethod()); assertTrue(in.canReadEntryData(entry)); FileInputStream original = new FileInputStream(getFile("test1.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in)); } finally { original.close(); } entry = in.getNextZipEntry(); assertEquals("method", ZipMethod.UNSHRINKING.getCode(), entry.getMethod()); assertTrue(in.canReadEntryData(entry)); original = new FileInputStream(getFile("test2.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in)); } finally { original.close(); } } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-264" * >COMPRESS-264</a>. */ @Test public void testReadingOfFirstStoredEntry() throws Exception { ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-264.zip"))); try { ZipArchiveEntry ze = in.getNextZipEntry(); assertEquals(5, ze.getSize()); assertArrayEquals(new byte[] {'d', 'a', 't', 'a', '\n'}, IOUtils.toByteArray(in)); } finally { in.close(); } } }
// You are a professional Java test case writer, please create a test case named `testReadingOfFirstStoredEntry` for the issue `Compress-COMPRESS-264`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-264 // // ## Issue-Title: // ZIP reads correctly with commons-compress 1.6, gives NUL bytes in 1.7 // // ## Issue-Description: // // When running the code below, commons-compress 1.6 writes: // // // Content of test.txt: // // data // // // By comparison, commons-compress 1.7 writes // // // Content of test.txt: // // @@@@^@ // // // package com.example.jrn; // // import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; // // import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; // // import java.io.ByteArrayInputStream; // // import java.io.IOException; // // import java.lang.System; // // /\*\* // // // * Hello world! // // \* // // \*/ // // public class App { // // public static void main(String[] args) { // // byte[] zip = // { // (byte)0x50, (byte)0x4b, (byte)0x03, (byte)0x04, (byte)0x0a, (byte)0x00, // (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x7b, // (byte)0xd1, (byte)0x42, (byte)0x82, (byte)0xc5, (byte)0xc1, (byte)0xe6, // (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05, (byte)0x00, // (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x1c, (byte)0x00, // (byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x2e, (byte)0x74, // (byte)0x78, (byte)0x74, (byte)0x55, (byte)0x54, (byte)0x09, (byte)0x00, // (byte)0x03, (byte)0x56, (byte)0x62, (byte)0xbf, (byte)0x51, (byte)0x2a, // (byte)0x63, (byte)0xbf, (byte)0x51, (byte)0x75, (byte)0x78, (byte)0x0b, // (byte)0x00, (byte)0x01, (byte)0x04, (byte)0x01, (byte)0xff, (byte)0x01, // (byte)0x00, (byte)0x04, (byte)0x88, (byte)0x13, (byte)0x00, (byte)0x00, // (byte)0x64, (byte)0x61, (byte)0x74, (byte)0x61, (byte)0x0a, (byte)0x50, // (byte)0x4b, (byte)0x01, (byte)0x02, (byte)0x1e, (byte)0x03, (byte)0x0a, // (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, // (byte)0x7b, (byte)0xd1, (byte)0x42, (byte)0x82, (byte)0xc5, (byte)0xc1, // (byte)0xe6, (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05, // (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x18, // (byte)0x00, (byte)0x00, (byte)0x00 @Test public void testReadingOfFirstStoredEntry() throws Exception {
170
/** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-264" * >COMPRESS-264</a>. */
25
158
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-264 ## Issue-Title: ZIP reads correctly with commons-compress 1.6, gives NUL bytes in 1.7 ## Issue-Description: When running the code below, commons-compress 1.6 writes: Content of test.txt: data By comparison, commons-compress 1.7 writes Content of test.txt: @@@@^@ package com.example.jrn; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.System; /\*\* * Hello world! \* \*/ public class App { public static void main(String[] args) { byte[] zip = { (byte)0x50, (byte)0x4b, (byte)0x03, (byte)0x04, (byte)0x0a, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x7b, (byte)0xd1, (byte)0x42, (byte)0x82, (byte)0xc5, (byte)0xc1, (byte)0xe6, (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x1c, (byte)0x00, (byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x2e, (byte)0x74, (byte)0x78, (byte)0x74, (byte)0x55, (byte)0x54, (byte)0x09, (byte)0x00, (byte)0x03, (byte)0x56, (byte)0x62, (byte)0xbf, (byte)0x51, (byte)0x2a, (byte)0x63, (byte)0xbf, (byte)0x51, (byte)0x75, (byte)0x78, (byte)0x0b, (byte)0x00, (byte)0x01, (byte)0x04, (byte)0x01, (byte)0xff, (byte)0x01, (byte)0x00, (byte)0x04, (byte)0x88, (byte)0x13, (byte)0x00, (byte)0x00, (byte)0x64, (byte)0x61, (byte)0x74, (byte)0x61, (byte)0x0a, (byte)0x50, (byte)0x4b, (byte)0x01, (byte)0x02, (byte)0x1e, (byte)0x03, (byte)0x0a, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x7b, (byte)0xd1, (byte)0x42, (byte)0x82, (byte)0xc5, (byte)0xc1, (byte)0xe6, (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x18, (byte)0x00, (byte)0x00, (byte)0x00 ``` You are a professional Java test case writer, please create a test case named `testReadingOfFirstStoredEntry` for the issue `Compress-COMPRESS-264`, utilizing the provided issue report information and the following function signature. ```java @Test public void testReadingOfFirstStoredEntry() throws Exception { ```
158
[ "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream" ]
050b4d4132e91fd034ea46a90712ff55907adde1c1012bec705211fb26cb04ce
@Test public void testReadingOfFirstStoredEntry() throws Exception
// You are a professional Java test case writer, please create a test case named `testReadingOfFirstStoredEntry` for the issue `Compress-COMPRESS-264`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-264 // // ## Issue-Title: // ZIP reads correctly with commons-compress 1.6, gives NUL bytes in 1.7 // // ## Issue-Description: // // When running the code below, commons-compress 1.6 writes: // // // Content of test.txt: // // data // // // By comparison, commons-compress 1.7 writes // // // Content of test.txt: // // @@@@^@ // // // package com.example.jrn; // // import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; // // import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; // // import java.io.ByteArrayInputStream; // // import java.io.IOException; // // import java.lang.System; // // /\*\* // // // * Hello world! // // \* // // \*/ // // public class App { // // public static void main(String[] args) { // // byte[] zip = // { // (byte)0x50, (byte)0x4b, (byte)0x03, (byte)0x04, (byte)0x0a, (byte)0x00, // (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x7b, // (byte)0xd1, (byte)0x42, (byte)0x82, (byte)0xc5, (byte)0xc1, (byte)0xe6, // (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05, (byte)0x00, // (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x1c, (byte)0x00, // (byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x2e, (byte)0x74, // (byte)0x78, (byte)0x74, (byte)0x55, (byte)0x54, (byte)0x09, (byte)0x00, // (byte)0x03, (byte)0x56, (byte)0x62, (byte)0xbf, (byte)0x51, (byte)0x2a, // (byte)0x63, (byte)0xbf, (byte)0x51, (byte)0x75, (byte)0x78, (byte)0x0b, // (byte)0x00, (byte)0x01, (byte)0x04, (byte)0x01, (byte)0xff, (byte)0x01, // (byte)0x00, (byte)0x04, (byte)0x88, (byte)0x13, (byte)0x00, (byte)0x00, // (byte)0x64, (byte)0x61, (byte)0x74, (byte)0x61, (byte)0x0a, (byte)0x50, // (byte)0x4b, (byte)0x01, (byte)0x02, (byte)0x1e, (byte)0x03, (byte)0x0a, // (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, // (byte)0x7b, (byte)0xd1, (byte)0x42, (byte)0x82, (byte)0xc5, (byte)0xc1, // (byte)0xe6, (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05, // (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x18, // (byte)0x00, (byte)0x00, (byte)0x00
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import org.apache.commons.compress.utils.IOUtils; import org.junit.Test; public class ZipArchiveInputStreamTest { /** * @see "https://issues.apache.org/jira/browse/COMPRESS-176" */ @Test public void winzipBackSlashWorkaround() throws Exception { ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(getFile("test-winzip.zip"))); ZipArchiveEntry zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); assertEquals("\u00e4/", zae.getName()); } finally { if (in != null) { in.close(); } } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-189" */ @Test public void properUseOfInflater() throws Exception { ZipFile zf = null; ZipArchiveInputStream in = null; try { zf = new ZipFile(getFile("COMPRESS-189.zip")); ZipArchiveEntry zae = zf.getEntry("USD0558682-20080101.ZIP"); in = new ZipArchiveInputStream(new BufferedInputStream(zf.getInputStream(zae))); ZipArchiveEntry innerEntry; while ((innerEntry = in.getNextZipEntry()) != null) { if (innerEntry.getName().endsWith("XML")) { assertTrue(0 < in.read()); } } } finally { if (zf != null) { zf.close(); } if (in != null) { in.close(); } } } @Test public void shouldConsumeArchiveCompletely() throws Exception { InputStream is = ZipArchiveInputStreamTest.class .getResourceAsStream("/archive_with_trailer.zip"); ZipArchiveInputStream zip = new ZipArchiveInputStream(is); while (zip.getNextZipEntry() != null) { // just consume the archive } byte[] expected = new byte[] { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n' }; byte[] actual = new byte[expected.length]; is.read(actual); assertArrayEquals(expected, actual); zip.close(); } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-219" */ @Test public void shouldReadNestedZip() throws IOException { ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-219.zip"))); extractZipInputStream(in); } finally { if (in != null) { in.close(); } } } private void extractZipInputStream(final ZipArchiveInputStream in) throws IOException { ZipArchiveEntry zae = in.getNextZipEntry(); while (zae != null) { if (zae.getName().endsWith(".zip")) { extractZipInputStream(new ZipArchiveInputStream(in)); } zae = in.getNextZipEntry(); } } @Test public void testUnshrinkEntry() throws Exception { ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("SHRUNK.ZIP"))); ZipArchiveEntry entry = in.getNextZipEntry(); assertEquals("method", ZipMethod.UNSHRINKING.getCode(), entry.getMethod()); assertTrue(in.canReadEntryData(entry)); FileInputStream original = new FileInputStream(getFile("test1.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in)); } finally { original.close(); } entry = in.getNextZipEntry(); assertEquals("method", ZipMethod.UNSHRINKING.getCode(), entry.getMethod()); assertTrue(in.canReadEntryData(entry)); original = new FileInputStream(getFile("test2.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in)); } finally { original.close(); } } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-264" * >COMPRESS-264</a>. */ @Test public void testReadingOfFirstStoredEntry() throws Exception { ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile("COMPRESS-264.zip"))); try { ZipArchiveEntry ze = in.getNextZipEntry(); assertEquals(5, ze.getSize()); assertArrayEquals(new byte[] {'d', 'a', 't', 'a', '\n'}, IOUtils.toByteArray(in)); } finally { in.close(); } } }
public void testBug4944818() { test( "var getDomServices_ = function(self) {\n" + " if (!self.domServices_) {\n" + " self.domServices_ = goog$component$DomServices.get(" + " self.appContext_);\n" + " }\n" + "\n" + " return self.domServices_;\n" + "};\n" + "\n" + "var getOwnerWin_ = function(self) {\n" + " return getDomServices_(self).getDomHelper().getWindow();\n" + "};\n" + "\n" + "HangoutStarter.prototype.launchHangout = function() {\n" + " var self = a.b;\n" + " var myUrl = new goog.Uri(getOwnerWin_(self).location.href);\n" + "};", "HangoutStarter.prototype.launchHangout = function() { " + " var self$$2 = a.b;" + " var JSCompiler_temp_const$$0 = goog.Uri;" + " var JSCompiler_inline_result$$1;" + " {" + " var self$$inline_2 = self$$2;" + " if (!self$$inline_2.domServices_) {" + " self$$inline_2.domServices_ = goog$component$DomServices.get(" + " self$$inline_2.appContext_);" + " }" + " JSCompiler_inline_result$$1=self$$inline_2.domServices_;" + " }" + " var myUrl = new JSCompiler_temp_const$$0(" + " JSCompiler_inline_result$$1.getDomHelper()." + " getWindow().location.href)" + "}"); }
com.google.javascript.jscomp.InlineFunctionsTest::testBug4944818
test/com/google/javascript/jscomp/InlineFunctionsTest.java
2,093
test/com/google/javascript/jscomp/InlineFunctionsTest.java
testBug4944818
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Inline function tests. * @author johnlenz@google.com (john lenz) */ public class InlineFunctionsTest extends CompilerTestCase { boolean allowGlobalFunctionInlining = true; boolean allowBlockInlining = true; final boolean allowExpressionDecomposition = true; final boolean allowFunctionExpressionInlining = true; final boolean allowLocalFunctionInlining = true; boolean assumeStrictThis = false; boolean assumeMinimumCapture = false; public InlineFunctionsTest() { this.enableNormalize(); this.enableMarkNoSideEffects(); } @Override protected void setUp() throws Exception { super.setUp(); super.enableLineNumberCheck(true); allowGlobalFunctionInlining = true; allowBlockInlining = true; assumeStrictThis = false; assumeMinimumCapture = false; } @Override protected CompilerPass getProcessor(Compiler compiler) { compiler.resetUniqueNameId(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), allowGlobalFunctionInlining, allowLocalFunctionInlining, allowBlockInlining, assumeStrictThis, assumeMinimumCapture); } /** * Returns the number of times the pass should be run before results are * verified. */ @Override protected int getNumRepetitions() { // Some inlining can only be done in multiple passes. return 3; } public void testInlineEmptyFunction1() { // Empty function, no params. test("function foo(){}" + "foo();", "void 0;"); } public void testInlineEmptyFunction2() { // Empty function, params with no side-effects. test("function foo(){}" + "foo(1, new Date, function(){});", "void 0;"); } public void testInlineEmptyFunction3() { // Empty function, multiple references. test("function foo(){}" + "foo();foo();foo();", "void 0;void 0;void 0"); } public void testInlineEmptyFunction4() { // Empty function, params with side-effects forces block inlining. test("function foo(){}" + "foo(x());", "{var JSCompiler_inline_anon_param_0=x();}"); } public void testInlineEmptyFunction5() { // Empty function, call params with side-effects in expression can not // be inlined. allowBlockInlining = false; testSame("function foo(){}" + "foo(x());"); } public void testInlineFunctions1() { // As simple a test as we can get. test("function foo(){ return 4 }" + "foo();", "4"); } public void testInlineFunctions2() { // inline simple constants // NOTE: CD is not inlined. test("var t;var AB=function(){return 4};" + "function BC(){return 6;}" + "CD=function(x){return x + 5};x=CD(3);y=AB();z=BC();", "var t;CD=function(x){return x+5};x=CD(3);y=4;z=6" ); } public void testInlineFunctions3() { // inline simple constants test("var t;var AB=function(){return 4};" + "function BC(){return 6;}" + "var CD=function(x){return x + 5};x=CD(3);y=AB();z=BC();", "var t;x=3+5;y=4;z=6"); } public void testInlineFunctions4() { // don't inline if there are multiple definitions (need DFA for that). test("var t; var AB = function() { return 4 }; " + "function BC() { return 6; }" + "CD = 0;" + "CD = function(x) { return x + 5 }; x = CD(3); y = AB(); z = BC();", "var t;CD=0;CD=function(x){return x+5};x=CD(3);y=4;z=6"); } public void testInlineFunctions5() { // inline additions test("var FOO_FN=function(x,y) { return \"de\" + x + \"nu\" + y };" + "var a = FOO_FN(\"ez\", \"ts\")", "var a=\"de\"+\"ez\"+\"nu\"+\"ts\""); } public void testInlineFunctions6() { // more complex inlines test("function BAR_FN(x, y, z) { return z(foo(x + y)) }" + "alert(BAR_FN(1, 2, baz))", "alert(baz(foo(1+2)))"); } public void testInlineFunctions7() { // inlines appearing multiple times test("function FN(x,y,z){return x+x+y}" + "var b=FN(1,2,3)", "var b=1+1+2"); } public void testInlineFunctions8() { // check correct parenthesization test("function MUL(x,y){return x*y}function ADD(x,y){return x+y}" + "var a=1+MUL(2,3);var b=2*ADD(3,4)", "var a=1+2*3;var b=2*(3+4)"); } public void testInlineFunctions9() { // don't inline if the input parameter is modified. test("function INC(x){return x++}" + "var y=INC(i)", "var y;{var x$$inline_0=i;" + "y=x$$inline_0++}"); } public void testInlineFunctions10() { test("function INC(x){return x++}" + "var y=INC(i);y=INC(i)", "var y;" + "{var x$$inline_0=i;" + "y=x$$inline_0++}" + "{var x$$inline_2=i;" + "y=x$$inline_2++}"); } public void testInlineFunctions11() { test("function f(x){return x}" + "var y=f(i)", "var y=i"); } public void testInlineFunctions12() { // don't inline if the input parameter has side-effects. allowBlockInlining = false; test("function f(x){return x}" + "var y=f(i)", "var y=i"); testSame("function f(x){return x}" + "var y=f(i++)"); } public void testInlineFunctions13() { // inline as block if the input parameter has side-effects. test("function f(x){return x}" + "var y=f(i++)", "var y;{var x$$inline_0=i++;y=x$$inline_0}"); } public void testInlineFunctions14() { // don't remove functions that are referenced on other ways test("function FOO(x){return x}var BAR=function(y){return y}" + ";b=FOO;a(BAR);x=FOO(1);y=BAR(2)", "function FOO(x){return x}var BAR=function(y){return y}" + ";b=FOO;a(BAR);x=1;y=2"); } public void testInlineFunctions15a() { // closure factories: do inline into global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "var d=c+function(a){return a+1}"); } public void testInlineFunctions15b() { assumeMinimumCapture = false; // closure factories: don't inline closure with locals into global scope. test("function foo(){var x;return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "function foo(){var x;return function(a){return a+1}}" + "var d=c+foo()"); assumeMinimumCapture = true; test("function foo(){var x;return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "var JSCompiler_temp_const$$0 = c;\n" + "var JSCompiler_inline_result$$1;\n" + "{\n" + "var x$$inline_2;\n" + "JSCompiler_inline_result$$1 = " + " function(a$$inline_3){ return a$$inline_3+1 };\n" + "}" + "var d=JSCompiler_temp_const$$0 + JSCompiler_inline_result$$1"); } public void testInlineFunctions15c() { assumeMinimumCapture = false; // closure factories: don't inline into non-global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function foo(){return function(a){return a+1}}" + "function _x(){ var d=c+foo() }"); assumeMinimumCapture = true; // closure factories: don't inline into non-global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function _x(){var d=c+function(a){return a+1}}"); } public void testInlineFunctions15d() { assumeMinimumCapture = false; // closure factories: don't inline functions with vars. test("function foo(){var x; return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function foo(){var x; return function(a){return a+1}}" + "function _x(){ var d=c+foo() }"); assumeMinimumCapture = true; // closure factories: don't inline functions with vars. test("function foo(){var x; return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function _x() { \n" + " var JSCompiler_temp_const$$0 = c;\n" + " var JSCompiler_inline_result$$1;\n" + " {\n" + " var x$$inline_2;\n" + " JSCompiler_inline_result$$1 = " + " function(a$$inline_3) {return a$$inline_3+1};\n" + " }\n" + " var d = JSCompiler_temp_const$$0+JSCompiler_inline_result$$1\n" + "}"); } public void testInlineFunctions16a() { assumeMinimumCapture = false; testSame("function foo(b){return window.bar(function(){c(b)})}" + "var d=foo(e)"); assumeMinimumCapture = true; test( "function foo(b){return window.bar(function(){c(b)})}" + "var d=foo(e)", "var d;{var b$$inline_0=e;" + "d=window.bar(function(){c(b$$inline_0)})}"); } public void testInlineFunctions16b() { test("function foo(){return window.bar(function(){c()})}" + "var d=foo(e)", "var d=window.bar(function(){c()})"); } public void testInlineFunctions17() { // don't inline recursive functions testSame("function foo(x){return x*x+foo(3)}var bar=foo(4)"); } public void testInlineFunctions18() { // TRICKY ... test nested inlines allowBlockInlining = false; test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=foo(bar(1),e)", "var d=c+e"); } public void testInlineFunctions19() { // TRICKY ... test nested inlines // with block inlining possible test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=foo(bar(1),e)", "var d;{d=c+e}"); } public void testInlineFunctions20() { // Make sure both orderings work allowBlockInlining = false; test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=bar(foo(1,e));", "var d=c"); } public void testInlineFunctions21() { // with block inlining possible test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=bar(foo(1,e))", "var d;{d=c}"); } public void testInlineFunctions22() { // Another tricky case ... test nested compiler inlines test("function plex(a){if(a) return 0;else return 1;}" + "function foo(a, b){return bar(a+b)}" + "function bar(d){return plex(d)}" + "var d=foo(1,2)", "var d;{JSCompiler_inline_label_plex_1:{" + "if(1+2){" + "d=0;break JSCompiler_inline_label_plex_1}" + "else{" + "d=1;break JSCompiler_inline_label_plex_1}d=void 0}}"); } public void testInlineFunctions23() { // Test both orderings again test("function complex(a){if(a) return 0;else return 1;}" + "function bar(d){return complex(d)}" + "function foo(a, b){return bar(a+b)}" + "var d=foo(1,2)", "var d;{JSCompiler_inline_label_complex_1:{" + "if(1+2){" + "d=0;break JSCompiler_inline_label_complex_1" + "}else{" + "d=1;break JSCompiler_inline_label_complex_1" + "}d=void 0}}"); } public void testInlineFunctions24() { // Don't inline functions with 'arguments' or 'this' testSame("function foo(x){return this}foo(1)"); } public void testInlineFunctions25() { testSame("function foo(){return arguments[0]}foo()"); } public void testInlineFunctions26() { // Don't inline external functions testSame("function _foo(x){return x}_foo(1)"); } public void testInlineFunctions27() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {y: 1, z: foo(2)};", "var window={};" + "var JSCompiler_inline_result$$0;" + "{" + " window.bar++;" + " JSCompiler_inline_result$$0 = 3;" + "}" + "var x = {y: 1, z: JSCompiler_inline_result$$0};"); } public void testInlineFunctions28() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {y: alert(), z: foo(2)};", "var window = {};" + "var JSCompiler_temp_const$$0 = alert();" + "var JSCompiler_inline_result$$1;" + "{" + " window.bar++;" + " JSCompiler_inline_result$$1 = 3;}" + "var x = {" + " y: JSCompiler_temp_const$$0," + " z: JSCompiler_inline_result$$1" + "};"); } public void testInlineFunctions29() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {a: alert(), b: alert2(), c: foo(2)};", "var window = {};" + "var JSCompiler_temp_const$$1 = alert();" + "var JSCompiler_temp_const$$0 = alert2();" + "var JSCompiler_inline_result$$2;" + "{" + " window.bar++;" + " JSCompiler_inline_result$$2 = 3;}" + "var x = {" + " a: JSCompiler_temp_const$$1," + " b: JSCompiler_temp_const$$0," + " c: JSCompiler_inline_result$$2" + "};"); } public void testInlineFunctions30() { // As simple a test as we can get. testSame("function foo(){ return eval() }" + "foo();"); } public void testInlineFunctions31() { // Don't introduce a duplicate label in the same scope test("function foo(){ lab:{4;} }" + "lab:{foo();}", "lab:{{JSCompiler_inline_label_0:{4}}}"); } public void testMixedModeInlining1() { // Base line tests, direct inlining test("function foo(){return 1}" + "foo();", "1;"); } public void testMixedModeInlining2() { // Base line tests, block inlining. Block inlining is needed by // possible-side-effect parameter. test("function foo(){return 1}" + "foo(x());", "{var JSCompiler_inline_anon_param_0=x();1}"); } public void testMixedModeInlining3() { // Inline using both modes. test("function foo(){return 1}" + "foo();foo(x());", "1;{var JSCompiler_inline_anon_param_0=x();1}"); } public void testMixedModeInlining4() { // Inline using both modes. Alternating. Second call of each type has // side-effect-less parameter, this is thrown away. test("function foo(){return 1}" + "foo();foo(x());" + "foo(1);foo(1,x());", "1;{var JSCompiler_inline_anon_param_0=x();1}" + "1;{var JSCompiler_inline_anon_param_4=x();1}"); } public void testMixedModeInliningCosting1() { // Inline using both modes. Costing estimates. // Base line. test( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "foo(1,2);" + "foo(2,3)", "1+2+1+2+4+5+6+7+8+9+1+2+3+4+5;" + "2+3+2+3+4+5+6+7+8+9+1+2+3+4+5"); } public void testMixedModeInliningCosting2() { // Don't inline here because the function definition can not be eliminated. // TODO(johnlenz): Should we add constant removing to the unit test? testSame( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "foo(1,2);" + "foo(2,3,x())"); } public void testMixedModeInliningCosting3() { // Do inline here because the function definition can be eliminated. test( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+10}" + "foo(1,2);" + "foo(2,3,x())", "1+2+1+2+4+5+6+7+8+9+1+2+3+10;" + "{var JSCompiler_inline_anon_param_2=x();" + "2+3+2+3+4+5+6+7+8+9+1+2+3+10}"); } public void testMixedModeInliningCosting4() { // Threshold test. testSame( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+101}" + "foo(1,2);" + "foo(2,3,x())"); } public void testNoInlineIfParametersModified1() { // Assignment test("function f(x){return x=1}f(undefined)", "{var x$$inline_0=undefined;" + "x$$inline_0=1}"); } public void testNoInlineIfParametersModified2() { test("function f(x){return (x)=1;}f(2)", "{var x$$inline_0=2;" + "x$$inline_0=1}"); } public void testNoInlineIfParametersModified3() { // Assignment variant. test("function f(x){return x*=2}f(2)", "{var x$$inline_0=2;" + "x$$inline_0*=2}"); } public void testNoInlineIfParametersModified4() { // Assignment in if. test("function f(x){return x?(x=2):0}f(2)", "{var x$$inline_0=2;" + "x$$inline_0?(" + "x$$inline_0=2):0}"); } public void testNoInlineIfParametersModified5() { // Assignment in if, multiple params test("function f(x,y){return x?(y=2):0}f(2,undefined)", "{var y$$inline_1=undefined;2?(" + "y$$inline_1=2):0}"); } public void testNoInlineIfParametersModified6() { test("function f(x,y){return x?(y=2):0}f(2)", "{var y$$inline_1=void 0;2?(" + "y$$inline_1=2):0}"); } public void testNoInlineIfParametersModified7() { // Increment test("function f(a){return++a<++a}f(1)", "{var a$$inline_0=1;" + "++a$$inline_0<" + "++a$$inline_0}"); } public void testNoInlineIfParametersModified8() { // OK, object parameter modified. test("function f(a){return a.x=2}f(o)", "o.x=2"); } public void testNoInlineIfParametersModified9() { // OK, array parameter modified. test("function f(a){return a[2]=2}f(o)", "o[2]=2"); } public void testInlineNeverPartialSubtitution1() { test("function f(z){return x.y.z;}f(1)", "x.y.z"); } public void testInlineNeverPartialSubtitution2() { test("function f(z){return x.y[z];}f(a)", "x.y[a]"); } public void testInlineNeverMutateConstants() { test("function f(x){return x=1}f(undefined)", "{var x$$inline_0=undefined;" + "x$$inline_0=1}"); } public void testInlineNeverOverrideNewValues() { test("function f(a){return++a<++a}f(1)", "{var a$$inline_0=1;" + "++a$$inline_0<++a$$inline_0}"); } public void testInlineMutableArgsReferencedOnce() { test("function foo(x){return x;}foo([])", "[]"); } public void testNoInlineMutableArgs1() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo([])"); } public void testNoInlineMutableArgs2() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo(new Date)"); } public void testNoInlineMutableArgs3() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo(true&&new Date)"); } public void testNoInlineMutableArgs4() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo({})"); } public void testInlineBlockMutableArgs1() { test("function foo(x){x+x}foo([])", "{var x$$inline_0=[];" + "x$$inline_0+x$$inline_0}"); } public void testInlineBlockMutableArgs2() { test("function foo(x){x+x}foo(new Date)", "{var x$$inline_0=new Date;" + "x$$inline_0+x$$inline_0}"); } public void testInlineBlockMutableArgs3() { test("function foo(x){x+x}foo(true&&new Date)", "{var x$$inline_0=true&&new Date;" + "x$$inline_0+x$$inline_0}"); } public void testInlineBlockMutableArgs4() { test("function foo(x){x+x}foo({})", "{var x$$inline_0={};" + "x$$inline_0+x$$inline_0}"); } public void testShadowVariables1() { // The Normalize pass now guarantees that that globals are never shadowed // by locals. // "foo" is inlined here as its parameter "a" doesn't conflict. // "bar" is assigned a new name. test("var a=0;" + "function foo(a){return 3+a}" + "function bar(){var a=foo(4)}" + "bar();", "var a=0;" + "{var a$$inline_0=3+4}"); } public void testShadowVariables2() { // "foo" is inlined here as its parameter "a" doesn't conflict. // "bar" is inlined as its uses global "a", and does introduce any new // globals. test("var a=0;" + "function foo(a){return 3+a}" + "function bar(){a=foo(4)}" + "bar()", "var a=0;" + "{a=3+4}"); } public void testShadowVariables3() { // "foo" is inlined into exported "_bar", aliasing foo's "a". test("var a=0;" + "function foo(){var a=2;return 3+a}" + "function _bar(){a=foo()}", "var a=0;" + "function _bar(){{var a$$inline_0=2;" + "a=3+a$$inline_0}}"); } public void testShadowVariables4() { // "foo" is inlined. // block access to global "a". test("var a=0;" + "function foo(){return 3+a}" + "function _bar(a){a=foo(4)+a}", "var a=0;function _bar(a$$1){" + "a$$1=" + "3+a+a$$1}"); } public void testShadowVariables5() { // Can't yet inline multiple statements functions into expressions // (though some are possible using the COMMA operator). allowBlockInlining = false; testSame("var a=0;" + "function foo(){var a=4;return 3+a}" + "function _bar(a){a=foo(4)+a}"); } public void testShadowVariables6() { test("var a=0;" + "function foo(){var a=4;return 3+a}" + "function _bar(a){a=foo(4)}", "var a=0;function _bar(a$$2){{" + "var a$$inline_0=4;" + "a$$2=3+a$$inline_0}}"); } public void testShadowVariables7() { assumeMinimumCapture = false; test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_0=5;{a}}" ); assumeMinimumCapture = true; test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_1=5;{a}}" ); } public void testShadowVariables8() { // this should be inlined test("var a=0;" + "function foo(){return 3}" + "function _bar(){var a=foo()}", "var a=0;" + "function _bar(){var a=3}"); } public void testShadowVariables9() { // this should be inlined too [even if the global is not declared] test("function foo(){return 3}" + "function _bar(){var a=foo()}", "function _bar(){var a=3}"); } public void testShadowVariables10() { // callee var must be renamed. test("var a;function foo(){return a}" + "function _bar(){var a=foo()}", "var a;function _bar(){var a$$1=a}"); } public void testShadowVariables11() { // The call has a local variable // which collides with the function being inlined test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var a=foo();alert(a)}", "var a=0;var b=1;" + "function _bar(){var a$$1=a+a;" + "alert(a$$1)}" ); } public void testShadowVariables12() { // 2 globals colliding test("var a=0;var b=1;" + "function foo(){return a+b}" + "function _bar(){var a=foo(),b;alert(a)}", "var a=0;var b=1;" + "function _bar(){var a$$1=a+b," + "b$$1;" + "alert(a$$1)}"); } public void testShadowVariables13() { // The only change is to remove the collision test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var c=foo();alert(c)}", "var a=0;var b=1;" + "function _bar(){var c=a+a;alert(c)}"); } public void testShadowVariables14() { // There is a collision even though it is not read. test("var a=0;var b=1;" + "function foo(){return a+b}" + "function _bar(){var c=foo(),b;alert(c)}", "var a=0;var b=1;" + "function _bar(){var c=a+b," + "b$$1;alert(c)}"); } public void testShadowVariables15() { // Both parent and child reference a global test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var c=foo();alert(c+a)}", "var a=0;var b=1;" + "function _bar(){var c=a+a;alert(c+a)}"); } public void testShadowVariables16() { assumeMinimumCapture = false; // Inline functions defined as a child of the CALL node. test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_0=5;{a}}" ); assumeMinimumCapture = true; // Inline functions defined as a child of the CALL node. test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_1=5;{a}}" ); } public void testShadowVariables17() { test("var a=0;" + "function bar(){return a+a}" + "function foo(){return bar()}" + "function _goo(){var a=2;var x=foo();}", "var a=0;" + "function _goo(){var a$$1=2;var x=a+a}"); } public void testShadowVariables18() { test("var a=0;" + "function bar(){return a+a}" + "function foo(){var a=3;return bar()}" + "function _goo(){var a=2;var x=foo();}", "var a=0;" + "function _goo(){var a$$2=2;var x;" + "{var a$$inline_0=3;x=a+a}}"); } public void testCostBasedInlining1() { testSame( "function foo(a){return a}" + "foo=new Function(\"return 1\");" + "foo(1)"); } public void testCostBasedInlining2() { // Baseline complexity tests. // Single call, function not removed. test( "function foo(a){return a}" + "var b=foo;" + "function _t1(){return foo(1)}", "function foo(a){return a}" + "var b=foo;" + "function _t1(){return 1}"); } public void testCostBasedInlining3() { // Two calls, function not removed. test( "function foo(a,b){return a+b}" + "var b=foo;" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function foo(a,b){return a+b}" + "var b=foo;" + "function _t1(){return 1+2}" + "function _t2(){return 2+3}"); } public void testCostBasedInlining4() { // Two calls, function not removed. // Here there isn't enough savings to justify inlining. testSame( "function foo(a,b){return a+b+a+b}" + "var b=foo;" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}"); } public void testCostBasedInlining5() { // Here there is enough savings to justify inlining. test( "function foo(a,b){return a+b+a+b}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function _t1(){return 1+2+1+2}" + "function _t2(){return 2+3+2+3}"); } public void testCostBasedInlining6() { // Here we have a threshold test. // Do inline here: test( "function foo(a,b){return a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function _t1(){return 1+2+1+2+1+2+1+2+4+5+6+7+8+9+1+2+3+4+5}" + "function _t2(){return 2+3+2+3+2+3+2+3+4+5+6+7+8+9+1+2+3+4+5}"); } public void testCostBasedInlining7() { // Don't inline here (not enough savings): testSame( "function foo(a,b){" + " return a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2+3+4+5+6}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}"); } public void testCostBasedInlining8() { // Verify multiple references in the same statement: // Here "f" is not known to be removable, as it is a used as parameter // and is not known to be side-effect free. The first call to f() can // not be inlined on the first pass (as the call to f() as a parameter // prevents this). However, the call to f() would be inlinable, if it // is small enough to be inlined without removing the function declaration. // but it is not in this first test. allowBlockInlining = false; testSame("function f(a){return 1 + a + a;}" + "var a = f(f(1));"); } public void testCostBasedInlining9() { // Here both direct and block inlining is used. The call to f as a // parameter is inlined directly, which the call to f with f as a parameter // is inlined using block inlining. test("function f(a){return 1 + a + a;}" + "var a = f(f(1));", "var a;" + "{var a$$inline_0=1+1+1;" + "a=1+a$$inline_0+a$$inline_0}"); } public void testCostBasedInlining10() { // But it is small enough here, and on the second iteration, the remaining // call to f() is inlined, as there is no longer a possible side-effect-ing // parameter. allowBlockInlining = false; test("function f(a){return a + a;}" + "var a = f(f(1));", "var a= 1+1+(1+1);"); } public void testCostBasedInlining11() { // With block inlining test("function f(a){return a + a;}" + "var a = f(f(1))", "var a;" + "{var a$$inline_0=1+1;" + "a=a$$inline_0+a$$inline_0}"); } public void testCostBasedInlining12() { test("function f(a){return 1 + a + a;}" + "var a = f(1) + f(2);", "var a=1+1+1+(1+2+2)"); } public void testCostBasedInliningComplex1() { testSame( "function foo(a){a()}" + "foo=new Function(\"return 1\");" + "foo(1)"); } public void testCostBasedInliningComplex2() { // Baseline complexity tests. // Single call, function not removed. test( "function foo(a){a()}" + "var b=foo;" + "function _t1(){foo(x)}", "function foo(a){a()}" + "var b=foo;" + "function _t1(){{x()}}"); } public void testCostBasedInliningComplex3() { // Two calls, function not removed. test( "function foo(a,b){a+b}" + "var b=foo;" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function foo(a,b){a+b}" + "var b=foo;" + "function _t1(){{1+2}}" + "function _t2(){{2+3}}"); } public void testCostBasedInliningComplex4() { // Two calls, function not removed. // Here there isn't enough savings to justify inlining. testSame( "function foo(a,b){a+b+a+b}" + "var b=foo;" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}"); } public void testCostBasedInliningComplex5() { // Here there is enough savings to justify inlining. test( "function foo(a,b){a+b+a+b}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function _t1(){{1+2+1+2}}" + "function _t2(){{2+3+2+3}}"); } public void testCostBasedInliningComplex6() { // Here we have a threshold test. // Do inline here: test( "function foo(a,b){a+b+a+b+a+b+a+b+4+5+6+7+8+9+1}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function _t1(){{1+2+1+2+1+2+1+2+4+5+6+7+8+9+1}}" + "function _t2(){{2+3+2+3+2+3+2+3+4+5+6+7+8+9+1}}"); } public void testCostBasedInliningComplex7() { // Don't inline here (not enough savings): testSame( "function foo(a,b){a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}"); } public void testCostBasedInliningComplex8() { // Verify multiple references in the same statement. testSame("function _f(a){1+a+a}" + "a=_f(1)+_f(1)"); } public void testCostBasedInliningComplex9() { test("function f(a){1 + a + a;}" + "f(1);f(2);", "{1+1+1}{1+2+2}"); } public void testDoubleInlining1() { allowBlockInlining = false; test("var foo = function(a) { return getWindow(a); };" + "var bar = function(b) { return b; };" + "foo(bar(x));", "getWindow(x)"); } public void testDoubleInlining2() { test("var foo = function(a) { return getWindow(a); };" + "var bar = function(b) { return b; };" + "foo(bar(x));", "{getWindow(x)}"); } public void testNoInlineOfNonGlobalFunction1() { test("var g;function _f(){function g(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction2() { test("var g;function _f(){var g=function(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction3() { test("var g;function _f(){var g=function(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction4() { test("var g;function _f(){function g(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineMaskedFunction() { // Normalization makes this test of marginal value. // The unreferenced function is removed. test("var g=function(){return 0};" + "function _f(g){return g()}", "function _f(g$$1){return g$$1()}"); } public void testNoInlineNonFunction() { testSame("var g=3;function _f(){return g()}"); } public void testInlineCall() { test("function f(g) { return g.h(); } f('x');", "\"x\".h()"); } public void testInlineFunctionWithArgsMismatch1() { test("function f(g) { return g; } f();", "void 0"); } public void testInlineFunctionWithArgsMismatch2() { test("function f() { return 0; } f(1);", "0"); } public void testInlineFunctionWithArgsMismatch3() { test("function f(one, two, three) { return one + two + three; } f(1);", "1+void 0+void 0"); } public void testInlineFunctionWithArgsMismatch4() { test("function f(one, two, three) { return one + two + three; }" + "f(1,2,3,4,5);", "1+2+3"); } public void testArgumentsWithSideEffectsNeverInlined1() { allowBlockInlining = false; testSame("function f(){return 0} f(new goo());"); } public void testArgumentsWithSideEffectsNeverInlined2() { allowBlockInlining = false; testSame("function f(g,h){return h+g}f(g(),h());"); } public void testOneSideEffectCallDoesNotRuinOthers() { allowBlockInlining = false; test("function f(){return 0}f(new goo());f()", "function f(){return 0}f(new goo());0"); } public void testComplexInlineNoResultNoParamCall1() { test("function f(){a()}f()", "{a()}"); } public void testComplexInlineNoResultNoParamCall2() { test("function f(){if (true){return;}else;} f();", "{JSCompiler_inline_label_f_0:{" + "if(true)break JSCompiler_inline_label_f_0;else;}}"); } public void testComplexInlineNoResultNoParamCall3() { // We now allow vars in the global space. // Don't inline into vars into global scope. // testSame("function f(){a();b();var z=1+1}f()"); // But do inline into functions test("function f(){a();b();var z=1+1}function _foo(){f()}", "function _foo(){{a();b();var z$$inline_0=1+1}}"); } public void testComplexInlineNoResultWithParamCall1() { test("function f(x){a(x)}f(1)", "{a(1)}"); } public void testComplexInlineNoResultWithParamCall2() { test("function f(x,y){a(x)}var b=1;f(1,b)", "var b=1;{a(1)}"); } public void testComplexInlineNoResultWithParamCall3() { test("function f(x,y){if (x) y(); return true;}var b=1;f(1,b)", "var b=1;{if(1)b();true}"); } public void testComplexInline1() { test("function f(){if (true){return;}else;} z=f();", "{JSCompiler_inline_label_f_0:" + "{if(true){z=void 0;" + "break JSCompiler_inline_label_f_0}else;z=void 0}}"); } public void testComplexInline2() { test("function f(){if (true){return;}else return;} z=f();", "{JSCompiler_inline_label_f_0:{if(true){z=void 0;" + "break JSCompiler_inline_label_f_0}else{z=void 0;" + "break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInline3() { test("function f(){if (true){return 1;}else return 0;} z=f();", "{JSCompiler_inline_label_f_0:{if(true){z=1;" + "break JSCompiler_inline_label_f_0}else{z=0;" + "break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInline4() { test("function f(x){a(x)} z = f(1)", "{a(1);z=void 0}"); } public void testComplexInline5() { test("function f(x,y){a(x)}var b=1;z=f(1,b)", "var b=1;{a(1);z=void 0}"); } public void testComplexInline6() { test("function f(x,y){if (x) y(); return true;}var b=1;z=f(1,b)", "var b=1;{if(1)b();z=true}"); } public void testComplexInline7() { test("function f(x,y){if (x) return y(); else return true;}" + "var b=1;z=f(1,b)", "var b=1;{JSCompiler_inline_label_f_2:{if(1){z=b();" + "break JSCompiler_inline_label_f_2}else{z=true;" + "break JSCompiler_inline_label_f_2}z=void 0}}"); } public void testComplexInline8() { test("function f(x){a(x)}var z=f(1)", "var z;{a(1);z=void 0}"); } public void testComplexInlineVars1() { test("function f(){if (true){return;}else;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{" + "if(true){z=void 0;break JSCompiler_inline_label_f_0}else;z=void 0}}"); } public void testComplexInlineVars2() { test("function f(){if (true){return;}else return;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{" + "if(true){z=void 0;break JSCompiler_inline_label_f_0" + "}else{" + "z=void 0;break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInlineVars3() { test("function f(){if (true){return 1;}else return 0;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{if(true){" + "z=1;break JSCompiler_inline_label_f_0" + "}else{" + "z=0;break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInlineVars4() { test("function f(x){a(x)}var z = f(1)", "var z;{a(1);z=void 0}"); } public void testComplexInlineVars5() { test("function f(x,y){a(x)}var b=1;var z=f(1,b)", "var b=1;var z;{a(1);z=void 0}"); } public void testComplexInlineVars6() { test("function f(x,y){if (x) y(); return true;}var b=1;var z=f(1,b)", "var b=1;var z;{if(1)b();z=true}"); } public void testComplexInlineVars7() { test("function f(x,y){if (x) return y(); else return true;}" + "var b=1;var z=f(1,b)", "var b=1;var z;" + "{JSCompiler_inline_label_f_2:{if(1){z=b();" + "break JSCompiler_inline_label_f_2" + "}else{" + "z=true;break JSCompiler_inline_label_f_2}z=void 0}}"); } public void testComplexInlineVars8() { test("function f(x){a(x)}var x;var z=f(1)", "var x;var z;{a(1);z=void 0}"); } public void testComplexInlineVars9() { test("function f(x){a(x)}var x;var z=f(1);var y", "var x;var z;{a(1);z=void 0}var y"); } public void testComplexInlineVars10() { test("function f(x){a(x)}var x=blah();var z=f(1);var y=blah();", "var x=blah();var z;{a(1);z=void 0}var y=blah()"); } public void testComplexInlineVars11() { test("function f(x){a(x)}var x=blah();var z=f(1);var y;", "var x=blah();var z;{a(1);z=void 0}var y"); } public void testComplexInlineVars12() { test("function f(x){a(x)}var x;var z=f(1);var y=blah();", "var x;var z;{a(1);z=void 0}var y=blah()"); } public void testComplexInlineInExpresssions1() { test("function f(){a()}var z=f()", "var z;{a();z=void 0}"); } public void testComplexInlineInExpresssions2() { test("function f(){a()}c=z=f()", "var JSCompiler_inline_result$$0;" + "{a();JSCompiler_inline_result$$0=void 0;}" + "c=z=JSCompiler_inline_result$$0"); } public void testComplexInlineInExpresssions3() { test("function f(){a()}c=z=f()", "var JSCompiler_inline_result$$0;" + "{a();JSCompiler_inline_result$$0=void 0;}" + "c=z=JSCompiler_inline_result$$0"); } public void testComplexInlineInExpresssions4() { test("function f(){a()}if(z=f());", "var JSCompiler_inline_result$$0;" + "{a();JSCompiler_inline_result$$0=void 0;}" + "if(z=JSCompiler_inline_result$$0);"); } public void testComplexInlineInExpresssions5() { test("function f(){a()}if(z.y=f());", "var JSCompiler_temp_const$$0=z;" + "var JSCompiler_inline_result$$1;" + "{a();JSCompiler_inline_result$$1=void 0;}" + "if(JSCompiler_temp_const$$0.y=JSCompiler_inline_result$$1);"); } public void testComplexNoInline1() { testSame("function f(){a()}while(z=f())continue"); } public void testComplexNoInline2() { testSame("function f(){a()}do;while(z=f())"); } public void testComplexSample() { String result = "" + "{{" + "var styleSheet$$inline_2=null;" + "if(goog$userAgent$IE)" + "styleSheet$$inline_2=0;" + "else " + "var head$$inline_3=0;" + "{" + "var element$$inline_4=" + "styleSheet$$inline_2;" + "var stylesString$$inline_5=a;" + "if(goog$userAgent$IE)" + "element$$inline_4.cssText=" + "stylesString$$inline_5;" + "else " + "{" + "var propToSet$$inline_6=" + "\"innerText\";" + "element$$inline_4[" + "propToSet$$inline_6]=" + "stylesString$$inline_5" + "}" + "}" + "styleSheet$$inline_2" + "}}"; test("var foo = function(stylesString, opt_element) { " + "var styleSheet = null;" + "if (goog$userAgent$IE)" + "styleSheet = 0;" + "else " + "var head = 0;" + "" + "goo$zoo(styleSheet, stylesString);" + "return styleSheet;" + " };\n " + "var goo$zoo = function(element, stylesString) {" + "if (goog$userAgent$IE)" + "element.cssText = stylesString;" + "else {" + "var propToSet = 'innerText';" + "element[propToSet] = stylesString;" + "}" + "};" + "(function(){foo(a,b);})();", result); } public void testComplexSampleNoInline() { testSame( "foo=function(stylesString,opt_element){" + "var styleSheet=null;" + "if(goog$userAgent$IE)" + "styleSheet=0;" + "else " + "var head=0;" + "" + "goo$zoo(styleSheet,stylesString);" + "return styleSheet" + "};" + "goo$zoo=function(element,stylesString){" + "if(goog$userAgent$IE)" + "element.cssText=stylesString;" + "else{" + "var propToSet=goog$userAgent$WEBKIT?\"innerText\":\"innerHTML\";" + "element[propToSet]=stylesString" + "}" + "}"); } // Test redefinition of parameter name. public void testComplexNoVarSub() { test( "function foo(x){" + "var x;" + "y=x" + "}" + "foo(1)", "{y=1}" ); } public void testComplexFunctionWithFunctionDefinition1() { test("function f(){call(function(){return})}f()", "{call(function(){return})}"); } public void testComplexFunctionWithFunctionDefinition2() { assumeMinimumCapture = false; // Don't inline if local names might be captured. testSame("function f(a){call(function(){return})}f()"); assumeMinimumCapture = true; test("(function(){" + "var f = function(a){call(function(){return a})};f()})()", "{{var a$$inline_0=void 0;call(function(){return a$$inline_0})}}"); } public void testComplexFunctionWithFunctionDefinition2a() { assumeMinimumCapture = false; // Don't inline if local names might be captured. testSame("(function(){" + "var f = function(a){call(function(){return a})};f()})()"); assumeMinimumCapture = true; test("(function(){" + "var f = function(a){call(function(){return a})};f()})()", "{{var a$$inline_0=void 0;call(function(){return a$$inline_0})}}"); } public void testComplexFunctionWithFunctionDefinition3() { assumeMinimumCapture = false; // Don't inline if local names might need to be captured. testSame("function f(){var a; call(function(){return a})}f()"); assumeMinimumCapture = true; test("function f(){var a; call(function(){return a})}f()", "{var a$$inline_0;call(function(){return a$$inline_0})}"); } public void testDecomposePlusEquals() { test("function f(){a=1;return 1} var x = 1; x += f()", "var x = 1;" + "var JSCompiler_temp_const$$0 = x;" + "var JSCompiler_inline_result$$1;" + "{a=1;" + " JSCompiler_inline_result$$1=1}" + "x = JSCompiler_temp_const$$0 + JSCompiler_inline_result$$1;"); } public void testDecomposeFunctionExpressionInCall() { test( "(function(map){descriptions_=map})(\n" + "function(){\n" + "var ret={};\n" + "ret[ONE]='a';\n" + "ret[TWO]='b';\n" + "return ret\n" + "}()\n" + ");", "var JSCompiler_inline_result$$0;" + "{" + "var ret$$inline_1={};\n" + "ret$$inline_1[ONE]='a';\n" + "ret$$inline_1[TWO]='b';\n" + "JSCompiler_inline_result$$0 = ret$$inline_1;\n" + "}" + "{" + "descriptions_=JSCompiler_inline_result$$0;" + "}" ); } public void testInlineConstructor1() { test("function f() {} function _g() {f.call(this)}", "function _g() {void 0}"); } public void testInlineConstructor2() { test("function f() {} f.prototype.a = 0; function _g() {f.call(this)}", "function f() {} f.prototype.a = 0; function _g() {void 0}"); } public void testInlineConstructor3() { test("function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {f.call(this)}", "function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {{x.call(this)}}"); } public void testInlineConstructor4() { test("function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {var t = f.call(this)}", "function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {var t; {x.call(this); t = void 0}}"); } public void testFunctionExpressionInlining1() { test("(function(){})()", "void 0"); } public void testFunctionExpressionInlining2() { test("(function(){foo()})()", "{foo()}"); } public void testFunctionExpressionInlining3() { test("var a = (function(){return foo()})()", "var a = foo()"); } public void testFunctionExpressionInlining4() { test("var a; a = 1 + (function(){return foo()})()", "var a; a = 1 + foo()"); } public void testFunctionExpressionCallInlining1() { test("(function(){}).call(this)", "void 0"); } public void testFunctionExpressionCallInlining2() { test("(function(){foo(this)}).call(this)", "{foo(this)}"); } public void testFunctionExpressionCallInlining3() { test("var a = (function(){return foo(this)}).call(this)", "var a = foo(this)"); } public void testFunctionExpressionCallInlining4() { test("var a; a = 1 + (function(){return foo(this)}).call(this)", "var a; a = 1 + foo(this)"); } public void testFunctionExpressionCallInlining5() { test("a:(function(){return foo()})()", "a:foo()"); } public void testFunctionExpressionCallInlining6() { test("a:(function(){return foo()}).call(this)", "a:foo()"); } public void testFunctionExpressionCallInlining7() { test("a:(function(){})()", "a:void 0"); } public void testFunctionExpressionCallInlining8() { test("a:(function(){}).call(this)", "a:void 0"); } public void testFunctionExpressionCallInlining9() { // ... with unused recursive name. test("(function foo(){})()", "void 0"); } public void testFunctionExpressionCallInlining10() { // ... with unused recursive name. test("(function foo(){}).call(this)", "void 0"); } public void testFunctionExpressionCallInlining11a() { // Inline functions that return inner functions. test("((function(){return function(){foo()}})())();", "{foo()}"); } public void testFunctionExpressionCallInlining11b() { assumeMinimumCapture = false; // Can't inline functions that return inner functions and have local names. testSame("((function(){var a; return function(){foo()}})())();"); assumeMinimumCapture = true; test( "((function(){var a; return function(){foo()}})())();", "var JSCompiler_inline_result$$0;" + "{var a$$inline_1;" + "JSCompiler_inline_result$$0=function(){foo()};}" + "JSCompiler_inline_result$$0()"); } public void testFunctionExpressionCallInlining11c() { // TODO(johnlenz): Can inline, not temps needed. assumeMinimumCapture = false; testSame("function _x() {" + " ((function(){return function(){foo()}})())();" + "}"); assumeMinimumCapture = true; test( "function _x() {" + " ((function(){return function(){foo()}})())();" + "}", "function _x() {" + " {foo()}" + "}"); } public void testFunctionExpressionCallInlining11d() { // TODO(johnlenz): Can inline into a function containing eval, if // no names are introduced. assumeMinimumCapture = false; testSame("function _x() {" + " eval();" + " ((function(){return function(){foo()}})())();" + "}"); assumeMinimumCapture = true; test( "function _x() {" + " eval();" + " ((function(){return function(){foo()}})())();" + "}", "function _x() {" + " eval();" + " {foo()}" + "}"); } public void testFunctionExpressionCallInlining11e() { // No, don't inline into a function containing eval, // if temps are introduced. assumeMinimumCapture = false; testSame("function _x() {" + " eval();" + " ((function(a){return function(){foo()}})())();" + "}"); assumeMinimumCapture = true; test("function _x() {" + " eval();" + " ((function(a){return function(){foo()}})())();" + "}", "function _x() {" + " eval();" + " {foo();}" + "}"); } public void testFunctionExpressionCallInlining12() { // Can't inline functions that recurse. testSame("(function foo(){foo()})()"); } public void testFunctionExpressionOmega() { // ... with unused recursive name. test("(function (f){f(f)})(function(f){f(f)})", "{var f$$inline_0=function(f$$1){f$$1(f$$1)};" + "{{f$$inline_0(f$$inline_0)}}}"); } public void testLocalFunctionInlining1() { test("function _f(){ function g() {} g() }", "function _f(){ void 0 }"); } public void testLocalFunctionInlining2() { test("function _f(){ function g() {foo(); bar();} g() }", "function _f(){ {foo(); bar();} }"); } public void testLocalFunctionInlining3() { test("function _f(){ function g() {foo(); bar();} g() }", "function _f(){ {foo(); bar();} }"); } public void testLocalFunctionInlining4() { test("function _f(){ function g() {return 1} return g() }", "function _f(){ return 1 }"); } public void testLocalFunctionInlining5() { testSame("function _f(){ function g() {this;} g() }"); } public void testLocalFunctionInlining6() { testSame("function _f(){ function g() {this;} return g; }"); } public void testLocalFunctionInliningOnly1() { this.allowGlobalFunctionInlining = true; test("function f(){} f()", "void 0;"); this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); } public void testLocalFunctionInliningOnly2() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("function f(){ function g() {return 1} return g() }; f();", "function f(){ return 1 }; f();"); } public void testLocalFunctionInliningOnly3() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("(function(){ function g() {return 1} return g() })();", "(function(){ return 1 })();"); } public void testLocalFunctionInliningOnly4() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("(function(){ return (function() {return 1})() })();", "(function(){ return 1 })();"); } public void testInlineWithThis1() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){} f.call();"); testSame("function f(){this} f.call();"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){} f.call();", "{}"); test("function f(){this} f.call();", "{void 0;}"); } public void testInlineWithThis2() { // "this" can always be replaced with "this" assumeStrictThis = false; test("function f(){} f.call(this);", "void 0"); assumeStrictThis = true; test("function f(){} f.call(this);", "void 0"); } public void testInlineWithThis3() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){} f.call([]);"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){} f.call([]);", "{}"); } public void testInlineWithThis4() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){} f.call(new g);"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){} f.call(new g);", "{var JSCompiler_inline_this_0=new g}"); } public void testInlineWithThis5() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){} f.call(g());"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){} f.call(g());", "{var JSCompiler_inline_this_0=g()}"); } public void testInlineWithThis6() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){this} f.call(new g);"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){this} f.call(new g);", "{var JSCompiler_inline_this_0=new g;JSCompiler_inline_this_0}"); } public void testInlineWithThis7() { assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(a){a=1;this} f.call();", "{var a$$inline_0=void 0; a$$inline_0=1; void 0;}"); test("function f(a){a=1;this} f.call(x, x);", "{var a$$inline_0=x; a$$inline_0=1; x;}"); } // http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator public void testFunctionExpressionYCombinator() { assumeMinimumCapture = false; testSame( "var factorial = ((function(M) {\n" + " return ((function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " })\n" + " (function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " }));\n" + " })\n" + " (function(f) {\n" + " return function(n) {\n" + " if (n === 0)\n" + " return 1;\n" + " else\n" + " return n * f(n - 1);\n" + " };\n" + " }));\n" + "\n" + "factorial(5)\n"); assumeMinimumCapture = true; test( "var factorial = ((function(M) {\n" + " return ((function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " })\n" + " (function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " }));\n" + " })\n" + " (function(f) {\n" + " return function(n) {\n" + " if (n === 0)\n" + " return 1;\n" + " else\n" + " return n * f(n - 1);\n" + " };\n" + " }));\n" + "\n" + "factorial(5)\n", "var factorial;\n" + "{\n" + "var M$$inline_4 = function(f$$2) {\n" + " return function(n){if(n===0)return 1;else return n*f$$2(n-1)}\n" + "};\n" + "{\n" + "var f$$inline_0=function(f$$inline_7){\n" + " return M$$inline_4(\n" + " function(arg$$inline_8){\n" + " return f$$inline_7(f$$inline_7)(arg$$inline_8)\n" + " })\n" + "};\n" + "factorial=M$$inline_4(\n" + " function(arg$$inline_1){\n" + " return f$$inline_0(f$$inline_0)(arg$$inline_1)\n" + "});\n" + "}\n" + "}" + "factorial(5)"); } public void testRenamePropertyFunction() { testSame("function JSCompiler_renameProperty(x) {return x} " + "JSCompiler_renameProperty('foo')"); } public void testReplacePropertyFunction() { // baseline: an alias doesn't prevents declaration removal, but not // inlining. test("function f(x) {return x} " + "foo(window, f); f(1)", "function f(x) {return x} " + "foo(window, f); 1"); // a reference passed to JSCompiler_ObjectPropertyString prevents inlining // as well. testSame("function f(x) {return x} " + "new JSCompiler_ObjectPropertyString(window, f); f(1)"); } public void testInlineWithClosureContainingThis() { test("(function (){return f(function(){return this})})();", "f(function(){return this})"); } public void testIssue5159924a() { test("function f() { if (x()) return y() }\n" + "while(1){ var m = f() || z() }", "for(;1;) {" + " var JSCompiler_inline_result$$0;" + " {" + " JSCompiler_inline_label_f_1: {" + " if(x()) {" + " JSCompiler_inline_result$$0 = y();" + " break JSCompiler_inline_label_f_1" + " }" + " JSCompiler_inline_result$$0 = void 0;" + " }" + " }" + " var m=JSCompiler_inline_result$$0 || z()" + "}"); } public void testIssue5159924b() { test("function f() { if (x()) return y() }\n" + "while(1){ var m = f() }", "for(;1;){" + " var m;" + " {" + " JSCompiler_inline_label_f_0: { " + " if(x()) {" + " m = y();" + " break JSCompiler_inline_label_f_0" + " }" + " m = void 0" + " }" + " }" + "}"); } public void testInlineObject() { new StringCompare().testInlineObject(); } private static class StringCompare extends CompilerTestCase { private boolean allowGlobalFunctionInlining = true; StringCompare() { super("", false); this.enableNormalize(); this.enableMarkNoSideEffects(); } @Override public void setUp() throws Exception { super.setUp(); super.enableLineNumberCheck(true); allowGlobalFunctionInlining = true; } @Override protected CompilerPass getProcessor(Compiler compiler) { compiler.resetUniqueNameId(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), allowGlobalFunctionInlining, true, // allowLocalFunctionInlining true, // allowBlockInlining true, // assumeStrictThis true); // assumeMinimumCapture } public void testInlineObject() { allowGlobalFunctionInlining = false; // TODO(johnlenz): normalize the AST so an AST comparison can be done. // As is, the expected AST does not match the actual correct result: // The AST matches "g.a()" with a FREE_CALL annotation, but this as // expected string would fail as it won't be mark as a free call. // "(0,g.a)()" matches the output, but not the resulting AST. test("function inner(){function f(){return g.a}(f())()}", "function inner(){(0,g.a)()}"); } } public void testBug4944818() { test( "var getDomServices_ = function(self) {\n" + " if (!self.domServices_) {\n" + " self.domServices_ = goog$component$DomServices.get(" + " self.appContext_);\n" + " }\n" + "\n" + " return self.domServices_;\n" + "};\n" + "\n" + "var getOwnerWin_ = function(self) {\n" + " return getDomServices_(self).getDomHelper().getWindow();\n" + "};\n" + "\n" + "HangoutStarter.prototype.launchHangout = function() {\n" + " var self = a.b;\n" + " var myUrl = new goog.Uri(getOwnerWin_(self).location.href);\n" + "};", "HangoutStarter.prototype.launchHangout = function() { " + " var self$$2 = a.b;" + " var JSCompiler_temp_const$$0 = goog.Uri;" + " var JSCompiler_inline_result$$1;" + " {" + " var self$$inline_2 = self$$2;" + " if (!self$$inline_2.domServices_) {" + " self$$inline_2.domServices_ = goog$component$DomServices.get(" + " self$$inline_2.appContext_);" + " }" + " JSCompiler_inline_result$$1=self$$inline_2.domServices_;" + " }" + " var myUrl = new JSCompiler_temp_const$$0(" + " JSCompiler_inline_result$$1.getDomHelper()." + " getWindow().location.href)" + "}"); } public void testIssue423() { assumeMinimumCapture = false; test( "(function($) {\n" + " $.fn.multicheck = function(options) {\n" + " initialize.call(this, options);\n" + " };\n" + "\n" + " function initialize(options) {\n" + " options.checkboxes = $(this).siblings(':checkbox');\n" + " preload_check_all.call(this);\n" + " }\n" + "\n" + " function preload_check_all() {\n" + " $(this).data('checkboxes');\n" + " }\n" + "})(jQuery)", "(function($){" + " $.fn.multicheck=function(options$$1){" + " {" + " options$$1.checkboxes=$(this).siblings(\":checkbox\");" + " {" + " $(this).data(\"checkboxes\")" + " }" + " }" + " }" + "})(jQuery)"); assumeMinimumCapture = true; test( "(function($) {\n" + " $.fn.multicheck = function(options) {\n" + " initialize.call(this, options);\n" + " };\n" + "\n" + " function initialize(options) {\n" + " options.checkboxes = $(this).siblings(':checkbox');\n" + " preload_check_all.call(this);\n" + " }\n" + "\n" + " function preload_check_all() {\n" + " $(this).data('checkboxes');\n" + " }\n" + "})(jQuery)", "{var $$$inline_0=jQuery;\n" + "$$$inline_0.fn.multicheck=function(options$$inline_4){\n" + " {options$$inline_4.checkboxes=" + "$$$inline_0(this).siblings(\":checkbox\");\n" + " {$$$inline_0(this).data(\"checkboxes\")}" + " }\n" + "}\n" + "}"); } public void testIssue728() { String f = "var f = function() { return false; };"; StringBuilder calls = new StringBuilder(); StringBuilder folded = new StringBuilder(); for (int i = 0; i < 30; i++) { calls.append("if (!f()) alert('x');"); folded.append("if (!false) alert('x');"); } test(f + calls, folded.toString()); } public void testAnonymous1() { assumeMinimumCapture = false; test("(function(){var a=10;(function(){var b=a;a++;alert(b)})()})();", "{var a$$inline_0=10;" + "{var b$$inline_1=a$$inline_0;" + "a$$inline_0++;alert(b$$inline_1)}}"); assumeMinimumCapture = true; test("(function(){var a=10;(function(){var b=a;a++;alert(b)})()})();", "{var a$$inline_2=10;" + "{var b$$inline_0=a$$inline_2;" + "a$$inline_2++;alert(b$$inline_0)}}"); } public void testAnonymous2() { testSame("(function(){eval();(function(){var b=a;a++;alert(b)})()})();"); } public void testAnonymous3() { // Introducing a new value into is tricky assumeMinimumCapture = false; testSame("(function(){var a=10;(function(){arguments;})()})();"); assumeMinimumCapture = true; test("(function(){var a=10;(function(){arguments;})()})();", "{var a$$inline_0=10;(function(){arguments;})();}"); test("(function(){(function(){arguments;})()})();", "{(function(){arguments;})()}"); } public void testLoopWithFunctionWithFunction() { assumeMinimumCapture = true; test("function _testLocalVariableInLoop_() {\n" + " var result = 0;\n" + " function foo() {\n" + " var arr = [1, 2, 3, 4, 5];\n" + " for (var i = 0, l = arr.length; i < l; i++) {\n" + " var j = arr[i];\n" + // don't inline this function, because the correct behavior depends // captured values. " (function() {\n" + " var k = j;\n" + " setTimeout(function() { result += k; }, 5 * i);\n" + " })();\n" + " }\n" + " }\n" + " foo();\n" + "}", "function _testLocalVariableInLoop_(){\n" + " var result=0;\n" + " {" + " var arr$$inline_0=[1,2,3,4,5];\n" + " var i$$inline_1=0;\n" + " var l$$inline_2=arr$$inline_0.length;\n" + " for(;i$$inline_1<l$$inline_2;i$$inline_1++){\n" + " var j$$inline_3=arr$$inline_0[i$$inline_1];\n" + " (function(){\n" + " var k$$inline_4=j$$inline_3;\n" + " setTimeout(function(){result+=k$$inline_4},5*i$$inline_1)\n" + " })()\n" + " }\n" + " }\n" + "}"); } public void testMethodWithFunctionWithFunction() { assumeMinimumCapture = true; test("function _testLocalVariable_() {\n" + " var result = 0;\n" + " function foo() {\n" + " var j = [i];\n" + " (function(j) {\n" + " setTimeout(function() { result += j; }, 5 * i);\n" + " })(j);\n" + " j = null;" + " }\n" + " foo();\n" + "}", "function _testLocalVariable_(){\n" + " var result=0;\n" + " {\n" + " var j$$inline_2=[i];\n" + " {\n" + " var j$$inline_0=j$$inline_2;\n" + // this temp is needed. " setTimeout(function(){result+=j$$inline_0},5*i);\n" + " }\n" + " j$$inline_2=null\n" + // because this value can be modified later. " }\n" + "}"); } // Inline a single reference function into deeper modules public void testCrossModuleInlining1() { test(createModuleChain( // m1 "function foo(){return f(1)+g(2)+h(3);}", // m2 "foo()" ), new String[] { // m1 "", // m2 "f(1)+g(2)+h(3);" } ); } // Inline a single reference function into shallow modules, only if it // is cheaper than the call itself. public void testCrossModuleInlining2() { testSame(createModuleChain( // m1 "foo()", // m2 "function foo(){return f(1)+g(2)+h(3);}" ) ); test(createModuleChain( // m1 "foo()", // m2 "function foo(){return f();}" ), new String[] { // m1 "f();", // m2 "" } ); } // Inline a multi-reference functions into shallow modules, only if it // is cheaper than the call itself. public void testCrossModuleInlining3() { testSame(createModuleChain( // m1 "foo()", // m2 "function foo(){return f(1)+g(2)+h(3);}", // m3 "foo()" ) ); test(createModuleChain( // m1 "foo()", // m2 "function foo(){return f();}", // m3 "foo()" ), new String[] { // m1 "f();", // m2 "", // m3 "f();" } ); } public void test6671158() { test( "function f() {return g()}" + "function Y(a){a.loader_()}" + "function _Z(){}" + "function _X() { new _Z(a,b, Y(singleton), f()) }", "function _Z(){}" + "function _X(){" + " var JSCompiler_temp_const$$2=_Z;" + " var JSCompiler_temp_const$$1=a;" + " var JSCompiler_temp_const$$0=b;" + " var JSCompiler_inline_result$$3;" + " {" + " singleton.loader_();" + " JSCompiler_inline_result$$3=void 0;" + " }" + " new JSCompiler_temp_const$$2(" + " JSCompiler_temp_const$$1," + " JSCompiler_temp_const$$0," + " JSCompiler_inline_result$$3," + " g())}"); } public void test8609285a() { test( "function f(x){ for(x in y){} } f()", "{var x$$inline_0=void 0;for(x$$inline_0 in y);}"); } public void test8609285b() { test( "function f(x){ for(var x in y){} } f()", "{var x$$inline_0=void 0;for(x$$inline_0 in y);}"); } }
// You are a professional Java test case writer, please create a test case named `testBug4944818` for the issue `Closure-1101`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1101 // // ## Issue-Title: // Erroneous optimization in ADVANCED_OPTIMIZATIONS mode // // ## Issue-Description: // **What steps will reproduce the problem?** // // 1. Create a file input.js with the following "minimal" test case: // // window["anchor"] = function (obj, modifiesProp) { // return (function (saved) { // return modifiesProp(obj) + saved; // })(obj["prop"]); // } // // 2. Compile it with: // // java -jar .../build/compiler.jar \ // --compilation\_level ADVANCED\_OPTIMIZATIONS \ // --warning\_level VERBOSE \ // --externs window.js \ // --js input.js \ // --js\_output\_file output.js // // 3. That's all! // // What is the expected output? // // window.foo=function(a,b){var HOLD=a.prop;return b(a)+HOLD}; // // What do you see instead? // // window.foo=function(a,b){return b(a)+a.prop}; // // Note how this is semantically very different if modifiesProp/b (whose // semantics are unknown to the compiler) side-effects a.prop. // // The evaluation order of + is well-defined in EcmaScript 5, but even // then, this happens even if one substitutes the , (comma) operator. // // **What version of the product are you using? On what operating system?** // // Git HEAD // // commit 4a62ee4bca02169dd77a6f26ed64a624b3f05f95 // Author: Chad Killingsworth <chadkillingsworth@missouristate.edu> // Date: Wed Sep 25 14:52:28 2013 -0500 // // Add history.state to html5 externs // // on Linux. // // public void testBug4944818() {
2,093
115
2,058
test/com/google/javascript/jscomp/InlineFunctionsTest.java
test
```markdown ## Issue-ID: Closure-1101 ## Issue-Title: Erroneous optimization in ADVANCED_OPTIMIZATIONS mode ## Issue-Description: **What steps will reproduce the problem?** 1. Create a file input.js with the following "minimal" test case: window["anchor"] = function (obj, modifiesProp) { return (function (saved) { return modifiesProp(obj) + saved; })(obj["prop"]); } 2. Compile it with: java -jar .../build/compiler.jar \ --compilation\_level ADVANCED\_OPTIMIZATIONS \ --warning\_level VERBOSE \ --externs window.js \ --js input.js \ --js\_output\_file output.js 3. That's all! What is the expected output? window.foo=function(a,b){var HOLD=a.prop;return b(a)+HOLD}; What do you see instead? window.foo=function(a,b){return b(a)+a.prop}; Note how this is semantically very different if modifiesProp/b (whose semantics are unknown to the compiler) side-effects a.prop. The evaluation order of + is well-defined in EcmaScript 5, but even then, this happens even if one substitutes the , (comma) operator. **What version of the product are you using? On what operating system?** Git HEAD commit 4a62ee4bca02169dd77a6f26ed64a624b3f05f95 Author: Chad Killingsworth <chadkillingsworth@missouristate.edu> Date: Wed Sep 25 14:52:28 2013 -0500 Add history.state to html5 externs on Linux. ``` You are a professional Java test case writer, please create a test case named `testBug4944818` for the issue `Closure-1101`, utilizing the provided issue report information and the following function signature. ```java public void testBug4944818() { ```
2,058
[ "com.google.javascript.jscomp.FunctionInjector" ]
0547be5ae0ee0bb59db0bd6db5e5b39ba3eb97b4572678f7c8ca2d9687baeea0
public void testBug4944818()
// You are a professional Java test case writer, please create a test case named `testBug4944818` for the issue `Closure-1101`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1101 // // ## Issue-Title: // Erroneous optimization in ADVANCED_OPTIMIZATIONS mode // // ## Issue-Description: // **What steps will reproduce the problem?** // // 1. Create a file input.js with the following "minimal" test case: // // window["anchor"] = function (obj, modifiesProp) { // return (function (saved) { // return modifiesProp(obj) + saved; // })(obj["prop"]); // } // // 2. Compile it with: // // java -jar .../build/compiler.jar \ // --compilation\_level ADVANCED\_OPTIMIZATIONS \ // --warning\_level VERBOSE \ // --externs window.js \ // --js input.js \ // --js\_output\_file output.js // // 3. That's all! // // What is the expected output? // // window.foo=function(a,b){var HOLD=a.prop;return b(a)+HOLD}; // // What do you see instead? // // window.foo=function(a,b){return b(a)+a.prop}; // // Note how this is semantically very different if modifiesProp/b (whose // semantics are unknown to the compiler) side-effects a.prop. // // The evaluation order of + is well-defined in EcmaScript 5, but even // then, this happens even if one substitutes the , (comma) operator. // // **What version of the product are you using? On what operating system?** // // Git HEAD // // commit 4a62ee4bca02169dd77a6f26ed64a624b3f05f95 // Author: Chad Killingsworth <chadkillingsworth@missouristate.edu> // Date: Wed Sep 25 14:52:28 2013 -0500 // // Add history.state to html5 externs // // on Linux. // //
Closure
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Inline function tests. * @author johnlenz@google.com (john lenz) */ public class InlineFunctionsTest extends CompilerTestCase { boolean allowGlobalFunctionInlining = true; boolean allowBlockInlining = true; final boolean allowExpressionDecomposition = true; final boolean allowFunctionExpressionInlining = true; final boolean allowLocalFunctionInlining = true; boolean assumeStrictThis = false; boolean assumeMinimumCapture = false; public InlineFunctionsTest() { this.enableNormalize(); this.enableMarkNoSideEffects(); } @Override protected void setUp() throws Exception { super.setUp(); super.enableLineNumberCheck(true); allowGlobalFunctionInlining = true; allowBlockInlining = true; assumeStrictThis = false; assumeMinimumCapture = false; } @Override protected CompilerPass getProcessor(Compiler compiler) { compiler.resetUniqueNameId(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), allowGlobalFunctionInlining, allowLocalFunctionInlining, allowBlockInlining, assumeStrictThis, assumeMinimumCapture); } /** * Returns the number of times the pass should be run before results are * verified. */ @Override protected int getNumRepetitions() { // Some inlining can only be done in multiple passes. return 3; } public void testInlineEmptyFunction1() { // Empty function, no params. test("function foo(){}" + "foo();", "void 0;"); } public void testInlineEmptyFunction2() { // Empty function, params with no side-effects. test("function foo(){}" + "foo(1, new Date, function(){});", "void 0;"); } public void testInlineEmptyFunction3() { // Empty function, multiple references. test("function foo(){}" + "foo();foo();foo();", "void 0;void 0;void 0"); } public void testInlineEmptyFunction4() { // Empty function, params with side-effects forces block inlining. test("function foo(){}" + "foo(x());", "{var JSCompiler_inline_anon_param_0=x();}"); } public void testInlineEmptyFunction5() { // Empty function, call params with side-effects in expression can not // be inlined. allowBlockInlining = false; testSame("function foo(){}" + "foo(x());"); } public void testInlineFunctions1() { // As simple a test as we can get. test("function foo(){ return 4 }" + "foo();", "4"); } public void testInlineFunctions2() { // inline simple constants // NOTE: CD is not inlined. test("var t;var AB=function(){return 4};" + "function BC(){return 6;}" + "CD=function(x){return x + 5};x=CD(3);y=AB();z=BC();", "var t;CD=function(x){return x+5};x=CD(3);y=4;z=6" ); } public void testInlineFunctions3() { // inline simple constants test("var t;var AB=function(){return 4};" + "function BC(){return 6;}" + "var CD=function(x){return x + 5};x=CD(3);y=AB();z=BC();", "var t;x=3+5;y=4;z=6"); } public void testInlineFunctions4() { // don't inline if there are multiple definitions (need DFA for that). test("var t; var AB = function() { return 4 }; " + "function BC() { return 6; }" + "CD = 0;" + "CD = function(x) { return x + 5 }; x = CD(3); y = AB(); z = BC();", "var t;CD=0;CD=function(x){return x+5};x=CD(3);y=4;z=6"); } public void testInlineFunctions5() { // inline additions test("var FOO_FN=function(x,y) { return \"de\" + x + \"nu\" + y };" + "var a = FOO_FN(\"ez\", \"ts\")", "var a=\"de\"+\"ez\"+\"nu\"+\"ts\""); } public void testInlineFunctions6() { // more complex inlines test("function BAR_FN(x, y, z) { return z(foo(x + y)) }" + "alert(BAR_FN(1, 2, baz))", "alert(baz(foo(1+2)))"); } public void testInlineFunctions7() { // inlines appearing multiple times test("function FN(x,y,z){return x+x+y}" + "var b=FN(1,2,3)", "var b=1+1+2"); } public void testInlineFunctions8() { // check correct parenthesization test("function MUL(x,y){return x*y}function ADD(x,y){return x+y}" + "var a=1+MUL(2,3);var b=2*ADD(3,4)", "var a=1+2*3;var b=2*(3+4)"); } public void testInlineFunctions9() { // don't inline if the input parameter is modified. test("function INC(x){return x++}" + "var y=INC(i)", "var y;{var x$$inline_0=i;" + "y=x$$inline_0++}"); } public void testInlineFunctions10() { test("function INC(x){return x++}" + "var y=INC(i);y=INC(i)", "var y;" + "{var x$$inline_0=i;" + "y=x$$inline_0++}" + "{var x$$inline_2=i;" + "y=x$$inline_2++}"); } public void testInlineFunctions11() { test("function f(x){return x}" + "var y=f(i)", "var y=i"); } public void testInlineFunctions12() { // don't inline if the input parameter has side-effects. allowBlockInlining = false; test("function f(x){return x}" + "var y=f(i)", "var y=i"); testSame("function f(x){return x}" + "var y=f(i++)"); } public void testInlineFunctions13() { // inline as block if the input parameter has side-effects. test("function f(x){return x}" + "var y=f(i++)", "var y;{var x$$inline_0=i++;y=x$$inline_0}"); } public void testInlineFunctions14() { // don't remove functions that are referenced on other ways test("function FOO(x){return x}var BAR=function(y){return y}" + ";b=FOO;a(BAR);x=FOO(1);y=BAR(2)", "function FOO(x){return x}var BAR=function(y){return y}" + ";b=FOO;a(BAR);x=1;y=2"); } public void testInlineFunctions15a() { // closure factories: do inline into global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "var d=c+function(a){return a+1}"); } public void testInlineFunctions15b() { assumeMinimumCapture = false; // closure factories: don't inline closure with locals into global scope. test("function foo(){var x;return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "function foo(){var x;return function(a){return a+1}}" + "var d=c+foo()"); assumeMinimumCapture = true; test("function foo(){var x;return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "var JSCompiler_temp_const$$0 = c;\n" + "var JSCompiler_inline_result$$1;\n" + "{\n" + "var x$$inline_2;\n" + "JSCompiler_inline_result$$1 = " + " function(a$$inline_3){ return a$$inline_3+1 };\n" + "}" + "var d=JSCompiler_temp_const$$0 + JSCompiler_inline_result$$1"); } public void testInlineFunctions15c() { assumeMinimumCapture = false; // closure factories: don't inline into non-global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function foo(){return function(a){return a+1}}" + "function _x(){ var d=c+foo() }"); assumeMinimumCapture = true; // closure factories: don't inline into non-global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function _x(){var d=c+function(a){return a+1}}"); } public void testInlineFunctions15d() { assumeMinimumCapture = false; // closure factories: don't inline functions with vars. test("function foo(){var x; return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function foo(){var x; return function(a){return a+1}}" + "function _x(){ var d=c+foo() }"); assumeMinimumCapture = true; // closure factories: don't inline functions with vars. test("function foo(){var x; return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function _x() { \n" + " var JSCompiler_temp_const$$0 = c;\n" + " var JSCompiler_inline_result$$1;\n" + " {\n" + " var x$$inline_2;\n" + " JSCompiler_inline_result$$1 = " + " function(a$$inline_3) {return a$$inline_3+1};\n" + " }\n" + " var d = JSCompiler_temp_const$$0+JSCompiler_inline_result$$1\n" + "}"); } public void testInlineFunctions16a() { assumeMinimumCapture = false; testSame("function foo(b){return window.bar(function(){c(b)})}" + "var d=foo(e)"); assumeMinimumCapture = true; test( "function foo(b){return window.bar(function(){c(b)})}" + "var d=foo(e)", "var d;{var b$$inline_0=e;" + "d=window.bar(function(){c(b$$inline_0)})}"); } public void testInlineFunctions16b() { test("function foo(){return window.bar(function(){c()})}" + "var d=foo(e)", "var d=window.bar(function(){c()})"); } public void testInlineFunctions17() { // don't inline recursive functions testSame("function foo(x){return x*x+foo(3)}var bar=foo(4)"); } public void testInlineFunctions18() { // TRICKY ... test nested inlines allowBlockInlining = false; test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=foo(bar(1),e)", "var d=c+e"); } public void testInlineFunctions19() { // TRICKY ... test nested inlines // with block inlining possible test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=foo(bar(1),e)", "var d;{d=c+e}"); } public void testInlineFunctions20() { // Make sure both orderings work allowBlockInlining = false; test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=bar(foo(1,e));", "var d=c"); } public void testInlineFunctions21() { // with block inlining possible test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=bar(foo(1,e))", "var d;{d=c}"); } public void testInlineFunctions22() { // Another tricky case ... test nested compiler inlines test("function plex(a){if(a) return 0;else return 1;}" + "function foo(a, b){return bar(a+b)}" + "function bar(d){return plex(d)}" + "var d=foo(1,2)", "var d;{JSCompiler_inline_label_plex_1:{" + "if(1+2){" + "d=0;break JSCompiler_inline_label_plex_1}" + "else{" + "d=1;break JSCompiler_inline_label_plex_1}d=void 0}}"); } public void testInlineFunctions23() { // Test both orderings again test("function complex(a){if(a) return 0;else return 1;}" + "function bar(d){return complex(d)}" + "function foo(a, b){return bar(a+b)}" + "var d=foo(1,2)", "var d;{JSCompiler_inline_label_complex_1:{" + "if(1+2){" + "d=0;break JSCompiler_inline_label_complex_1" + "}else{" + "d=1;break JSCompiler_inline_label_complex_1" + "}d=void 0}}"); } public void testInlineFunctions24() { // Don't inline functions with 'arguments' or 'this' testSame("function foo(x){return this}foo(1)"); } public void testInlineFunctions25() { testSame("function foo(){return arguments[0]}foo()"); } public void testInlineFunctions26() { // Don't inline external functions testSame("function _foo(x){return x}_foo(1)"); } public void testInlineFunctions27() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {y: 1, z: foo(2)};", "var window={};" + "var JSCompiler_inline_result$$0;" + "{" + " window.bar++;" + " JSCompiler_inline_result$$0 = 3;" + "}" + "var x = {y: 1, z: JSCompiler_inline_result$$0};"); } public void testInlineFunctions28() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {y: alert(), z: foo(2)};", "var window = {};" + "var JSCompiler_temp_const$$0 = alert();" + "var JSCompiler_inline_result$$1;" + "{" + " window.bar++;" + " JSCompiler_inline_result$$1 = 3;}" + "var x = {" + " y: JSCompiler_temp_const$$0," + " z: JSCompiler_inline_result$$1" + "};"); } public void testInlineFunctions29() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {a: alert(), b: alert2(), c: foo(2)};", "var window = {};" + "var JSCompiler_temp_const$$1 = alert();" + "var JSCompiler_temp_const$$0 = alert2();" + "var JSCompiler_inline_result$$2;" + "{" + " window.bar++;" + " JSCompiler_inline_result$$2 = 3;}" + "var x = {" + " a: JSCompiler_temp_const$$1," + " b: JSCompiler_temp_const$$0," + " c: JSCompiler_inline_result$$2" + "};"); } public void testInlineFunctions30() { // As simple a test as we can get. testSame("function foo(){ return eval() }" + "foo();"); } public void testInlineFunctions31() { // Don't introduce a duplicate label in the same scope test("function foo(){ lab:{4;} }" + "lab:{foo();}", "lab:{{JSCompiler_inline_label_0:{4}}}"); } public void testMixedModeInlining1() { // Base line tests, direct inlining test("function foo(){return 1}" + "foo();", "1;"); } public void testMixedModeInlining2() { // Base line tests, block inlining. Block inlining is needed by // possible-side-effect parameter. test("function foo(){return 1}" + "foo(x());", "{var JSCompiler_inline_anon_param_0=x();1}"); } public void testMixedModeInlining3() { // Inline using both modes. test("function foo(){return 1}" + "foo();foo(x());", "1;{var JSCompiler_inline_anon_param_0=x();1}"); } public void testMixedModeInlining4() { // Inline using both modes. Alternating. Second call of each type has // side-effect-less parameter, this is thrown away. test("function foo(){return 1}" + "foo();foo(x());" + "foo(1);foo(1,x());", "1;{var JSCompiler_inline_anon_param_0=x();1}" + "1;{var JSCompiler_inline_anon_param_4=x();1}"); } public void testMixedModeInliningCosting1() { // Inline using both modes. Costing estimates. // Base line. test( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "foo(1,2);" + "foo(2,3)", "1+2+1+2+4+5+6+7+8+9+1+2+3+4+5;" + "2+3+2+3+4+5+6+7+8+9+1+2+3+4+5"); } public void testMixedModeInliningCosting2() { // Don't inline here because the function definition can not be eliminated. // TODO(johnlenz): Should we add constant removing to the unit test? testSame( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "foo(1,2);" + "foo(2,3,x())"); } public void testMixedModeInliningCosting3() { // Do inline here because the function definition can be eliminated. test( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+10}" + "foo(1,2);" + "foo(2,3,x())", "1+2+1+2+4+5+6+7+8+9+1+2+3+10;" + "{var JSCompiler_inline_anon_param_2=x();" + "2+3+2+3+4+5+6+7+8+9+1+2+3+10}"); } public void testMixedModeInliningCosting4() { // Threshold test. testSame( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+101}" + "foo(1,2);" + "foo(2,3,x())"); } public void testNoInlineIfParametersModified1() { // Assignment test("function f(x){return x=1}f(undefined)", "{var x$$inline_0=undefined;" + "x$$inline_0=1}"); } public void testNoInlineIfParametersModified2() { test("function f(x){return (x)=1;}f(2)", "{var x$$inline_0=2;" + "x$$inline_0=1}"); } public void testNoInlineIfParametersModified3() { // Assignment variant. test("function f(x){return x*=2}f(2)", "{var x$$inline_0=2;" + "x$$inline_0*=2}"); } public void testNoInlineIfParametersModified4() { // Assignment in if. test("function f(x){return x?(x=2):0}f(2)", "{var x$$inline_0=2;" + "x$$inline_0?(" + "x$$inline_0=2):0}"); } public void testNoInlineIfParametersModified5() { // Assignment in if, multiple params test("function f(x,y){return x?(y=2):0}f(2,undefined)", "{var y$$inline_1=undefined;2?(" + "y$$inline_1=2):0}"); } public void testNoInlineIfParametersModified6() { test("function f(x,y){return x?(y=2):0}f(2)", "{var y$$inline_1=void 0;2?(" + "y$$inline_1=2):0}"); } public void testNoInlineIfParametersModified7() { // Increment test("function f(a){return++a<++a}f(1)", "{var a$$inline_0=1;" + "++a$$inline_0<" + "++a$$inline_0}"); } public void testNoInlineIfParametersModified8() { // OK, object parameter modified. test("function f(a){return a.x=2}f(o)", "o.x=2"); } public void testNoInlineIfParametersModified9() { // OK, array parameter modified. test("function f(a){return a[2]=2}f(o)", "o[2]=2"); } public void testInlineNeverPartialSubtitution1() { test("function f(z){return x.y.z;}f(1)", "x.y.z"); } public void testInlineNeverPartialSubtitution2() { test("function f(z){return x.y[z];}f(a)", "x.y[a]"); } public void testInlineNeverMutateConstants() { test("function f(x){return x=1}f(undefined)", "{var x$$inline_0=undefined;" + "x$$inline_0=1}"); } public void testInlineNeverOverrideNewValues() { test("function f(a){return++a<++a}f(1)", "{var a$$inline_0=1;" + "++a$$inline_0<++a$$inline_0}"); } public void testInlineMutableArgsReferencedOnce() { test("function foo(x){return x;}foo([])", "[]"); } public void testNoInlineMutableArgs1() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo([])"); } public void testNoInlineMutableArgs2() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo(new Date)"); } public void testNoInlineMutableArgs3() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo(true&&new Date)"); } public void testNoInlineMutableArgs4() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo({})"); } public void testInlineBlockMutableArgs1() { test("function foo(x){x+x}foo([])", "{var x$$inline_0=[];" + "x$$inline_0+x$$inline_0}"); } public void testInlineBlockMutableArgs2() { test("function foo(x){x+x}foo(new Date)", "{var x$$inline_0=new Date;" + "x$$inline_0+x$$inline_0}"); } public void testInlineBlockMutableArgs3() { test("function foo(x){x+x}foo(true&&new Date)", "{var x$$inline_0=true&&new Date;" + "x$$inline_0+x$$inline_0}"); } public void testInlineBlockMutableArgs4() { test("function foo(x){x+x}foo({})", "{var x$$inline_0={};" + "x$$inline_0+x$$inline_0}"); } public void testShadowVariables1() { // The Normalize pass now guarantees that that globals are never shadowed // by locals. // "foo" is inlined here as its parameter "a" doesn't conflict. // "bar" is assigned a new name. test("var a=0;" + "function foo(a){return 3+a}" + "function bar(){var a=foo(4)}" + "bar();", "var a=0;" + "{var a$$inline_0=3+4}"); } public void testShadowVariables2() { // "foo" is inlined here as its parameter "a" doesn't conflict. // "bar" is inlined as its uses global "a", and does introduce any new // globals. test("var a=0;" + "function foo(a){return 3+a}" + "function bar(){a=foo(4)}" + "bar()", "var a=0;" + "{a=3+4}"); } public void testShadowVariables3() { // "foo" is inlined into exported "_bar", aliasing foo's "a". test("var a=0;" + "function foo(){var a=2;return 3+a}" + "function _bar(){a=foo()}", "var a=0;" + "function _bar(){{var a$$inline_0=2;" + "a=3+a$$inline_0}}"); } public void testShadowVariables4() { // "foo" is inlined. // block access to global "a". test("var a=0;" + "function foo(){return 3+a}" + "function _bar(a){a=foo(4)+a}", "var a=0;function _bar(a$$1){" + "a$$1=" + "3+a+a$$1}"); } public void testShadowVariables5() { // Can't yet inline multiple statements functions into expressions // (though some are possible using the COMMA operator). allowBlockInlining = false; testSame("var a=0;" + "function foo(){var a=4;return 3+a}" + "function _bar(a){a=foo(4)+a}"); } public void testShadowVariables6() { test("var a=0;" + "function foo(){var a=4;return 3+a}" + "function _bar(a){a=foo(4)}", "var a=0;function _bar(a$$2){{" + "var a$$inline_0=4;" + "a$$2=3+a$$inline_0}}"); } public void testShadowVariables7() { assumeMinimumCapture = false; test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_0=5;{a}}" ); assumeMinimumCapture = true; test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_1=5;{a}}" ); } public void testShadowVariables8() { // this should be inlined test("var a=0;" + "function foo(){return 3}" + "function _bar(){var a=foo()}", "var a=0;" + "function _bar(){var a=3}"); } public void testShadowVariables9() { // this should be inlined too [even if the global is not declared] test("function foo(){return 3}" + "function _bar(){var a=foo()}", "function _bar(){var a=3}"); } public void testShadowVariables10() { // callee var must be renamed. test("var a;function foo(){return a}" + "function _bar(){var a=foo()}", "var a;function _bar(){var a$$1=a}"); } public void testShadowVariables11() { // The call has a local variable // which collides with the function being inlined test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var a=foo();alert(a)}", "var a=0;var b=1;" + "function _bar(){var a$$1=a+a;" + "alert(a$$1)}" ); } public void testShadowVariables12() { // 2 globals colliding test("var a=0;var b=1;" + "function foo(){return a+b}" + "function _bar(){var a=foo(),b;alert(a)}", "var a=0;var b=1;" + "function _bar(){var a$$1=a+b," + "b$$1;" + "alert(a$$1)}"); } public void testShadowVariables13() { // The only change is to remove the collision test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var c=foo();alert(c)}", "var a=0;var b=1;" + "function _bar(){var c=a+a;alert(c)}"); } public void testShadowVariables14() { // There is a collision even though it is not read. test("var a=0;var b=1;" + "function foo(){return a+b}" + "function _bar(){var c=foo(),b;alert(c)}", "var a=0;var b=1;" + "function _bar(){var c=a+b," + "b$$1;alert(c)}"); } public void testShadowVariables15() { // Both parent and child reference a global test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var c=foo();alert(c+a)}", "var a=0;var b=1;" + "function _bar(){var c=a+a;alert(c+a)}"); } public void testShadowVariables16() { assumeMinimumCapture = false; // Inline functions defined as a child of the CALL node. test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_0=5;{a}}" ); assumeMinimumCapture = true; // Inline functions defined as a child of the CALL node. test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_1=5;{a}}" ); } public void testShadowVariables17() { test("var a=0;" + "function bar(){return a+a}" + "function foo(){return bar()}" + "function _goo(){var a=2;var x=foo();}", "var a=0;" + "function _goo(){var a$$1=2;var x=a+a}"); } public void testShadowVariables18() { test("var a=0;" + "function bar(){return a+a}" + "function foo(){var a=3;return bar()}" + "function _goo(){var a=2;var x=foo();}", "var a=0;" + "function _goo(){var a$$2=2;var x;" + "{var a$$inline_0=3;x=a+a}}"); } public void testCostBasedInlining1() { testSame( "function foo(a){return a}" + "foo=new Function(\"return 1\");" + "foo(1)"); } public void testCostBasedInlining2() { // Baseline complexity tests. // Single call, function not removed. test( "function foo(a){return a}" + "var b=foo;" + "function _t1(){return foo(1)}", "function foo(a){return a}" + "var b=foo;" + "function _t1(){return 1}"); } public void testCostBasedInlining3() { // Two calls, function not removed. test( "function foo(a,b){return a+b}" + "var b=foo;" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function foo(a,b){return a+b}" + "var b=foo;" + "function _t1(){return 1+2}" + "function _t2(){return 2+3}"); } public void testCostBasedInlining4() { // Two calls, function not removed. // Here there isn't enough savings to justify inlining. testSame( "function foo(a,b){return a+b+a+b}" + "var b=foo;" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}"); } public void testCostBasedInlining5() { // Here there is enough savings to justify inlining. test( "function foo(a,b){return a+b+a+b}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function _t1(){return 1+2+1+2}" + "function _t2(){return 2+3+2+3}"); } public void testCostBasedInlining6() { // Here we have a threshold test. // Do inline here: test( "function foo(a,b){return a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function _t1(){return 1+2+1+2+1+2+1+2+4+5+6+7+8+9+1+2+3+4+5}" + "function _t2(){return 2+3+2+3+2+3+2+3+4+5+6+7+8+9+1+2+3+4+5}"); } public void testCostBasedInlining7() { // Don't inline here (not enough savings): testSame( "function foo(a,b){" + " return a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2+3+4+5+6}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}"); } public void testCostBasedInlining8() { // Verify multiple references in the same statement: // Here "f" is not known to be removable, as it is a used as parameter // and is not known to be side-effect free. The first call to f() can // not be inlined on the first pass (as the call to f() as a parameter // prevents this). However, the call to f() would be inlinable, if it // is small enough to be inlined without removing the function declaration. // but it is not in this first test. allowBlockInlining = false; testSame("function f(a){return 1 + a + a;}" + "var a = f(f(1));"); } public void testCostBasedInlining9() { // Here both direct and block inlining is used. The call to f as a // parameter is inlined directly, which the call to f with f as a parameter // is inlined using block inlining. test("function f(a){return 1 + a + a;}" + "var a = f(f(1));", "var a;" + "{var a$$inline_0=1+1+1;" + "a=1+a$$inline_0+a$$inline_0}"); } public void testCostBasedInlining10() { // But it is small enough here, and on the second iteration, the remaining // call to f() is inlined, as there is no longer a possible side-effect-ing // parameter. allowBlockInlining = false; test("function f(a){return a + a;}" + "var a = f(f(1));", "var a= 1+1+(1+1);"); } public void testCostBasedInlining11() { // With block inlining test("function f(a){return a + a;}" + "var a = f(f(1))", "var a;" + "{var a$$inline_0=1+1;" + "a=a$$inline_0+a$$inline_0}"); } public void testCostBasedInlining12() { test("function f(a){return 1 + a + a;}" + "var a = f(1) + f(2);", "var a=1+1+1+(1+2+2)"); } public void testCostBasedInliningComplex1() { testSame( "function foo(a){a()}" + "foo=new Function(\"return 1\");" + "foo(1)"); } public void testCostBasedInliningComplex2() { // Baseline complexity tests. // Single call, function not removed. test( "function foo(a){a()}" + "var b=foo;" + "function _t1(){foo(x)}", "function foo(a){a()}" + "var b=foo;" + "function _t1(){{x()}}"); } public void testCostBasedInliningComplex3() { // Two calls, function not removed. test( "function foo(a,b){a+b}" + "var b=foo;" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function foo(a,b){a+b}" + "var b=foo;" + "function _t1(){{1+2}}" + "function _t2(){{2+3}}"); } public void testCostBasedInliningComplex4() { // Two calls, function not removed. // Here there isn't enough savings to justify inlining. testSame( "function foo(a,b){a+b+a+b}" + "var b=foo;" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}"); } public void testCostBasedInliningComplex5() { // Here there is enough savings to justify inlining. test( "function foo(a,b){a+b+a+b}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function _t1(){{1+2+1+2}}" + "function _t2(){{2+3+2+3}}"); } public void testCostBasedInliningComplex6() { // Here we have a threshold test. // Do inline here: test( "function foo(a,b){a+b+a+b+a+b+a+b+4+5+6+7+8+9+1}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function _t1(){{1+2+1+2+1+2+1+2+4+5+6+7+8+9+1}}" + "function _t2(){{2+3+2+3+2+3+2+3+4+5+6+7+8+9+1}}"); } public void testCostBasedInliningComplex7() { // Don't inline here (not enough savings): testSame( "function foo(a,b){a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}"); } public void testCostBasedInliningComplex8() { // Verify multiple references in the same statement. testSame("function _f(a){1+a+a}" + "a=_f(1)+_f(1)"); } public void testCostBasedInliningComplex9() { test("function f(a){1 + a + a;}" + "f(1);f(2);", "{1+1+1}{1+2+2}"); } public void testDoubleInlining1() { allowBlockInlining = false; test("var foo = function(a) { return getWindow(a); };" + "var bar = function(b) { return b; };" + "foo(bar(x));", "getWindow(x)"); } public void testDoubleInlining2() { test("var foo = function(a) { return getWindow(a); };" + "var bar = function(b) { return b; };" + "foo(bar(x));", "{getWindow(x)}"); } public void testNoInlineOfNonGlobalFunction1() { test("var g;function _f(){function g(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction2() { test("var g;function _f(){var g=function(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction3() { test("var g;function _f(){var g=function(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction4() { test("var g;function _f(){function g(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineMaskedFunction() { // Normalization makes this test of marginal value. // The unreferenced function is removed. test("var g=function(){return 0};" + "function _f(g){return g()}", "function _f(g$$1){return g$$1()}"); } public void testNoInlineNonFunction() { testSame("var g=3;function _f(){return g()}"); } public void testInlineCall() { test("function f(g) { return g.h(); } f('x');", "\"x\".h()"); } public void testInlineFunctionWithArgsMismatch1() { test("function f(g) { return g; } f();", "void 0"); } public void testInlineFunctionWithArgsMismatch2() { test("function f() { return 0; } f(1);", "0"); } public void testInlineFunctionWithArgsMismatch3() { test("function f(one, two, three) { return one + two + three; } f(1);", "1+void 0+void 0"); } public void testInlineFunctionWithArgsMismatch4() { test("function f(one, two, three) { return one + two + three; }" + "f(1,2,3,4,5);", "1+2+3"); } public void testArgumentsWithSideEffectsNeverInlined1() { allowBlockInlining = false; testSame("function f(){return 0} f(new goo());"); } public void testArgumentsWithSideEffectsNeverInlined2() { allowBlockInlining = false; testSame("function f(g,h){return h+g}f(g(),h());"); } public void testOneSideEffectCallDoesNotRuinOthers() { allowBlockInlining = false; test("function f(){return 0}f(new goo());f()", "function f(){return 0}f(new goo());0"); } public void testComplexInlineNoResultNoParamCall1() { test("function f(){a()}f()", "{a()}"); } public void testComplexInlineNoResultNoParamCall2() { test("function f(){if (true){return;}else;} f();", "{JSCompiler_inline_label_f_0:{" + "if(true)break JSCompiler_inline_label_f_0;else;}}"); } public void testComplexInlineNoResultNoParamCall3() { // We now allow vars in the global space. // Don't inline into vars into global scope. // testSame("function f(){a();b();var z=1+1}f()"); // But do inline into functions test("function f(){a();b();var z=1+1}function _foo(){f()}", "function _foo(){{a();b();var z$$inline_0=1+1}}"); } public void testComplexInlineNoResultWithParamCall1() { test("function f(x){a(x)}f(1)", "{a(1)}"); } public void testComplexInlineNoResultWithParamCall2() { test("function f(x,y){a(x)}var b=1;f(1,b)", "var b=1;{a(1)}"); } public void testComplexInlineNoResultWithParamCall3() { test("function f(x,y){if (x) y(); return true;}var b=1;f(1,b)", "var b=1;{if(1)b();true}"); } public void testComplexInline1() { test("function f(){if (true){return;}else;} z=f();", "{JSCompiler_inline_label_f_0:" + "{if(true){z=void 0;" + "break JSCompiler_inline_label_f_0}else;z=void 0}}"); } public void testComplexInline2() { test("function f(){if (true){return;}else return;} z=f();", "{JSCompiler_inline_label_f_0:{if(true){z=void 0;" + "break JSCompiler_inline_label_f_0}else{z=void 0;" + "break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInline3() { test("function f(){if (true){return 1;}else return 0;} z=f();", "{JSCompiler_inline_label_f_0:{if(true){z=1;" + "break JSCompiler_inline_label_f_0}else{z=0;" + "break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInline4() { test("function f(x){a(x)} z = f(1)", "{a(1);z=void 0}"); } public void testComplexInline5() { test("function f(x,y){a(x)}var b=1;z=f(1,b)", "var b=1;{a(1);z=void 0}"); } public void testComplexInline6() { test("function f(x,y){if (x) y(); return true;}var b=1;z=f(1,b)", "var b=1;{if(1)b();z=true}"); } public void testComplexInline7() { test("function f(x,y){if (x) return y(); else return true;}" + "var b=1;z=f(1,b)", "var b=1;{JSCompiler_inline_label_f_2:{if(1){z=b();" + "break JSCompiler_inline_label_f_2}else{z=true;" + "break JSCompiler_inline_label_f_2}z=void 0}}"); } public void testComplexInline8() { test("function f(x){a(x)}var z=f(1)", "var z;{a(1);z=void 0}"); } public void testComplexInlineVars1() { test("function f(){if (true){return;}else;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{" + "if(true){z=void 0;break JSCompiler_inline_label_f_0}else;z=void 0}}"); } public void testComplexInlineVars2() { test("function f(){if (true){return;}else return;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{" + "if(true){z=void 0;break JSCompiler_inline_label_f_0" + "}else{" + "z=void 0;break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInlineVars3() { test("function f(){if (true){return 1;}else return 0;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{if(true){" + "z=1;break JSCompiler_inline_label_f_0" + "}else{" + "z=0;break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInlineVars4() { test("function f(x){a(x)}var z = f(1)", "var z;{a(1);z=void 0}"); } public void testComplexInlineVars5() { test("function f(x,y){a(x)}var b=1;var z=f(1,b)", "var b=1;var z;{a(1);z=void 0}"); } public void testComplexInlineVars6() { test("function f(x,y){if (x) y(); return true;}var b=1;var z=f(1,b)", "var b=1;var z;{if(1)b();z=true}"); } public void testComplexInlineVars7() { test("function f(x,y){if (x) return y(); else return true;}" + "var b=1;var z=f(1,b)", "var b=1;var z;" + "{JSCompiler_inline_label_f_2:{if(1){z=b();" + "break JSCompiler_inline_label_f_2" + "}else{" + "z=true;break JSCompiler_inline_label_f_2}z=void 0}}"); } public void testComplexInlineVars8() { test("function f(x){a(x)}var x;var z=f(1)", "var x;var z;{a(1);z=void 0}"); } public void testComplexInlineVars9() { test("function f(x){a(x)}var x;var z=f(1);var y", "var x;var z;{a(1);z=void 0}var y"); } public void testComplexInlineVars10() { test("function f(x){a(x)}var x=blah();var z=f(1);var y=blah();", "var x=blah();var z;{a(1);z=void 0}var y=blah()"); } public void testComplexInlineVars11() { test("function f(x){a(x)}var x=blah();var z=f(1);var y;", "var x=blah();var z;{a(1);z=void 0}var y"); } public void testComplexInlineVars12() { test("function f(x){a(x)}var x;var z=f(1);var y=blah();", "var x;var z;{a(1);z=void 0}var y=blah()"); } public void testComplexInlineInExpresssions1() { test("function f(){a()}var z=f()", "var z;{a();z=void 0}"); } public void testComplexInlineInExpresssions2() { test("function f(){a()}c=z=f()", "var JSCompiler_inline_result$$0;" + "{a();JSCompiler_inline_result$$0=void 0;}" + "c=z=JSCompiler_inline_result$$0"); } public void testComplexInlineInExpresssions3() { test("function f(){a()}c=z=f()", "var JSCompiler_inline_result$$0;" + "{a();JSCompiler_inline_result$$0=void 0;}" + "c=z=JSCompiler_inline_result$$0"); } public void testComplexInlineInExpresssions4() { test("function f(){a()}if(z=f());", "var JSCompiler_inline_result$$0;" + "{a();JSCompiler_inline_result$$0=void 0;}" + "if(z=JSCompiler_inline_result$$0);"); } public void testComplexInlineInExpresssions5() { test("function f(){a()}if(z.y=f());", "var JSCompiler_temp_const$$0=z;" + "var JSCompiler_inline_result$$1;" + "{a();JSCompiler_inline_result$$1=void 0;}" + "if(JSCompiler_temp_const$$0.y=JSCompiler_inline_result$$1);"); } public void testComplexNoInline1() { testSame("function f(){a()}while(z=f())continue"); } public void testComplexNoInline2() { testSame("function f(){a()}do;while(z=f())"); } public void testComplexSample() { String result = "" + "{{" + "var styleSheet$$inline_2=null;" + "if(goog$userAgent$IE)" + "styleSheet$$inline_2=0;" + "else " + "var head$$inline_3=0;" + "{" + "var element$$inline_4=" + "styleSheet$$inline_2;" + "var stylesString$$inline_5=a;" + "if(goog$userAgent$IE)" + "element$$inline_4.cssText=" + "stylesString$$inline_5;" + "else " + "{" + "var propToSet$$inline_6=" + "\"innerText\";" + "element$$inline_4[" + "propToSet$$inline_6]=" + "stylesString$$inline_5" + "}" + "}" + "styleSheet$$inline_2" + "}}"; test("var foo = function(stylesString, opt_element) { " + "var styleSheet = null;" + "if (goog$userAgent$IE)" + "styleSheet = 0;" + "else " + "var head = 0;" + "" + "goo$zoo(styleSheet, stylesString);" + "return styleSheet;" + " };\n " + "var goo$zoo = function(element, stylesString) {" + "if (goog$userAgent$IE)" + "element.cssText = stylesString;" + "else {" + "var propToSet = 'innerText';" + "element[propToSet] = stylesString;" + "}" + "};" + "(function(){foo(a,b);})();", result); } public void testComplexSampleNoInline() { testSame( "foo=function(stylesString,opt_element){" + "var styleSheet=null;" + "if(goog$userAgent$IE)" + "styleSheet=0;" + "else " + "var head=0;" + "" + "goo$zoo(styleSheet,stylesString);" + "return styleSheet" + "};" + "goo$zoo=function(element,stylesString){" + "if(goog$userAgent$IE)" + "element.cssText=stylesString;" + "else{" + "var propToSet=goog$userAgent$WEBKIT?\"innerText\":\"innerHTML\";" + "element[propToSet]=stylesString" + "}" + "}"); } // Test redefinition of parameter name. public void testComplexNoVarSub() { test( "function foo(x){" + "var x;" + "y=x" + "}" + "foo(1)", "{y=1}" ); } public void testComplexFunctionWithFunctionDefinition1() { test("function f(){call(function(){return})}f()", "{call(function(){return})}"); } public void testComplexFunctionWithFunctionDefinition2() { assumeMinimumCapture = false; // Don't inline if local names might be captured. testSame("function f(a){call(function(){return})}f()"); assumeMinimumCapture = true; test("(function(){" + "var f = function(a){call(function(){return a})};f()})()", "{{var a$$inline_0=void 0;call(function(){return a$$inline_0})}}"); } public void testComplexFunctionWithFunctionDefinition2a() { assumeMinimumCapture = false; // Don't inline if local names might be captured. testSame("(function(){" + "var f = function(a){call(function(){return a})};f()})()"); assumeMinimumCapture = true; test("(function(){" + "var f = function(a){call(function(){return a})};f()})()", "{{var a$$inline_0=void 0;call(function(){return a$$inline_0})}}"); } public void testComplexFunctionWithFunctionDefinition3() { assumeMinimumCapture = false; // Don't inline if local names might need to be captured. testSame("function f(){var a; call(function(){return a})}f()"); assumeMinimumCapture = true; test("function f(){var a; call(function(){return a})}f()", "{var a$$inline_0;call(function(){return a$$inline_0})}"); } public void testDecomposePlusEquals() { test("function f(){a=1;return 1} var x = 1; x += f()", "var x = 1;" + "var JSCompiler_temp_const$$0 = x;" + "var JSCompiler_inline_result$$1;" + "{a=1;" + " JSCompiler_inline_result$$1=1}" + "x = JSCompiler_temp_const$$0 + JSCompiler_inline_result$$1;"); } public void testDecomposeFunctionExpressionInCall() { test( "(function(map){descriptions_=map})(\n" + "function(){\n" + "var ret={};\n" + "ret[ONE]='a';\n" + "ret[TWO]='b';\n" + "return ret\n" + "}()\n" + ");", "var JSCompiler_inline_result$$0;" + "{" + "var ret$$inline_1={};\n" + "ret$$inline_1[ONE]='a';\n" + "ret$$inline_1[TWO]='b';\n" + "JSCompiler_inline_result$$0 = ret$$inline_1;\n" + "}" + "{" + "descriptions_=JSCompiler_inline_result$$0;" + "}" ); } public void testInlineConstructor1() { test("function f() {} function _g() {f.call(this)}", "function _g() {void 0}"); } public void testInlineConstructor2() { test("function f() {} f.prototype.a = 0; function _g() {f.call(this)}", "function f() {} f.prototype.a = 0; function _g() {void 0}"); } public void testInlineConstructor3() { test("function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {f.call(this)}", "function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {{x.call(this)}}"); } public void testInlineConstructor4() { test("function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {var t = f.call(this)}", "function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {var t; {x.call(this); t = void 0}}"); } public void testFunctionExpressionInlining1() { test("(function(){})()", "void 0"); } public void testFunctionExpressionInlining2() { test("(function(){foo()})()", "{foo()}"); } public void testFunctionExpressionInlining3() { test("var a = (function(){return foo()})()", "var a = foo()"); } public void testFunctionExpressionInlining4() { test("var a; a = 1 + (function(){return foo()})()", "var a; a = 1 + foo()"); } public void testFunctionExpressionCallInlining1() { test("(function(){}).call(this)", "void 0"); } public void testFunctionExpressionCallInlining2() { test("(function(){foo(this)}).call(this)", "{foo(this)}"); } public void testFunctionExpressionCallInlining3() { test("var a = (function(){return foo(this)}).call(this)", "var a = foo(this)"); } public void testFunctionExpressionCallInlining4() { test("var a; a = 1 + (function(){return foo(this)}).call(this)", "var a; a = 1 + foo(this)"); } public void testFunctionExpressionCallInlining5() { test("a:(function(){return foo()})()", "a:foo()"); } public void testFunctionExpressionCallInlining6() { test("a:(function(){return foo()}).call(this)", "a:foo()"); } public void testFunctionExpressionCallInlining7() { test("a:(function(){})()", "a:void 0"); } public void testFunctionExpressionCallInlining8() { test("a:(function(){}).call(this)", "a:void 0"); } public void testFunctionExpressionCallInlining9() { // ... with unused recursive name. test("(function foo(){})()", "void 0"); } public void testFunctionExpressionCallInlining10() { // ... with unused recursive name. test("(function foo(){}).call(this)", "void 0"); } public void testFunctionExpressionCallInlining11a() { // Inline functions that return inner functions. test("((function(){return function(){foo()}})())();", "{foo()}"); } public void testFunctionExpressionCallInlining11b() { assumeMinimumCapture = false; // Can't inline functions that return inner functions and have local names. testSame("((function(){var a; return function(){foo()}})())();"); assumeMinimumCapture = true; test( "((function(){var a; return function(){foo()}})())();", "var JSCompiler_inline_result$$0;" + "{var a$$inline_1;" + "JSCompiler_inline_result$$0=function(){foo()};}" + "JSCompiler_inline_result$$0()"); } public void testFunctionExpressionCallInlining11c() { // TODO(johnlenz): Can inline, not temps needed. assumeMinimumCapture = false; testSame("function _x() {" + " ((function(){return function(){foo()}})())();" + "}"); assumeMinimumCapture = true; test( "function _x() {" + " ((function(){return function(){foo()}})())();" + "}", "function _x() {" + " {foo()}" + "}"); } public void testFunctionExpressionCallInlining11d() { // TODO(johnlenz): Can inline into a function containing eval, if // no names are introduced. assumeMinimumCapture = false; testSame("function _x() {" + " eval();" + " ((function(){return function(){foo()}})())();" + "}"); assumeMinimumCapture = true; test( "function _x() {" + " eval();" + " ((function(){return function(){foo()}})())();" + "}", "function _x() {" + " eval();" + " {foo()}" + "}"); } public void testFunctionExpressionCallInlining11e() { // No, don't inline into a function containing eval, // if temps are introduced. assumeMinimumCapture = false; testSame("function _x() {" + " eval();" + " ((function(a){return function(){foo()}})())();" + "}"); assumeMinimumCapture = true; test("function _x() {" + " eval();" + " ((function(a){return function(){foo()}})())();" + "}", "function _x() {" + " eval();" + " {foo();}" + "}"); } public void testFunctionExpressionCallInlining12() { // Can't inline functions that recurse. testSame("(function foo(){foo()})()"); } public void testFunctionExpressionOmega() { // ... with unused recursive name. test("(function (f){f(f)})(function(f){f(f)})", "{var f$$inline_0=function(f$$1){f$$1(f$$1)};" + "{{f$$inline_0(f$$inline_0)}}}"); } public void testLocalFunctionInlining1() { test("function _f(){ function g() {} g() }", "function _f(){ void 0 }"); } public void testLocalFunctionInlining2() { test("function _f(){ function g() {foo(); bar();} g() }", "function _f(){ {foo(); bar();} }"); } public void testLocalFunctionInlining3() { test("function _f(){ function g() {foo(); bar();} g() }", "function _f(){ {foo(); bar();} }"); } public void testLocalFunctionInlining4() { test("function _f(){ function g() {return 1} return g() }", "function _f(){ return 1 }"); } public void testLocalFunctionInlining5() { testSame("function _f(){ function g() {this;} g() }"); } public void testLocalFunctionInlining6() { testSame("function _f(){ function g() {this;} return g; }"); } public void testLocalFunctionInliningOnly1() { this.allowGlobalFunctionInlining = true; test("function f(){} f()", "void 0;"); this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); } public void testLocalFunctionInliningOnly2() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("function f(){ function g() {return 1} return g() }; f();", "function f(){ return 1 }; f();"); } public void testLocalFunctionInliningOnly3() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("(function(){ function g() {return 1} return g() })();", "(function(){ return 1 })();"); } public void testLocalFunctionInliningOnly4() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("(function(){ return (function() {return 1})() })();", "(function(){ return 1 })();"); } public void testInlineWithThis1() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){} f.call();"); testSame("function f(){this} f.call();"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){} f.call();", "{}"); test("function f(){this} f.call();", "{void 0;}"); } public void testInlineWithThis2() { // "this" can always be replaced with "this" assumeStrictThis = false; test("function f(){} f.call(this);", "void 0"); assumeStrictThis = true; test("function f(){} f.call(this);", "void 0"); } public void testInlineWithThis3() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){} f.call([]);"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){} f.call([]);", "{}"); } public void testInlineWithThis4() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){} f.call(new g);"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){} f.call(new g);", "{var JSCompiler_inline_this_0=new g}"); } public void testInlineWithThis5() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){} f.call(g());"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){} f.call(g());", "{var JSCompiler_inline_this_0=g()}"); } public void testInlineWithThis6() { assumeStrictThis = false; // If no "this" is provided it might need to be coerced to the global // "this". testSame("function f(){this} f.call(new g);"); assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(){this} f.call(new g);", "{var JSCompiler_inline_this_0=new g;JSCompiler_inline_this_0}"); } public void testInlineWithThis7() { assumeStrictThis = true; // In strict mode, "this" is never coerced so we can use the provided value. test("function f(a){a=1;this} f.call();", "{var a$$inline_0=void 0; a$$inline_0=1; void 0;}"); test("function f(a){a=1;this} f.call(x, x);", "{var a$$inline_0=x; a$$inline_0=1; x;}"); } // http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator public void testFunctionExpressionYCombinator() { assumeMinimumCapture = false; testSame( "var factorial = ((function(M) {\n" + " return ((function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " })\n" + " (function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " }));\n" + " })\n" + " (function(f) {\n" + " return function(n) {\n" + " if (n === 0)\n" + " return 1;\n" + " else\n" + " return n * f(n - 1);\n" + " };\n" + " }));\n" + "\n" + "factorial(5)\n"); assumeMinimumCapture = true; test( "var factorial = ((function(M) {\n" + " return ((function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " })\n" + " (function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " }));\n" + " })\n" + " (function(f) {\n" + " return function(n) {\n" + " if (n === 0)\n" + " return 1;\n" + " else\n" + " return n * f(n - 1);\n" + " };\n" + " }));\n" + "\n" + "factorial(5)\n", "var factorial;\n" + "{\n" + "var M$$inline_4 = function(f$$2) {\n" + " return function(n){if(n===0)return 1;else return n*f$$2(n-1)}\n" + "};\n" + "{\n" + "var f$$inline_0=function(f$$inline_7){\n" + " return M$$inline_4(\n" + " function(arg$$inline_8){\n" + " return f$$inline_7(f$$inline_7)(arg$$inline_8)\n" + " })\n" + "};\n" + "factorial=M$$inline_4(\n" + " function(arg$$inline_1){\n" + " return f$$inline_0(f$$inline_0)(arg$$inline_1)\n" + "});\n" + "}\n" + "}" + "factorial(5)"); } public void testRenamePropertyFunction() { testSame("function JSCompiler_renameProperty(x) {return x} " + "JSCompiler_renameProperty('foo')"); } public void testReplacePropertyFunction() { // baseline: an alias doesn't prevents declaration removal, but not // inlining. test("function f(x) {return x} " + "foo(window, f); f(1)", "function f(x) {return x} " + "foo(window, f); 1"); // a reference passed to JSCompiler_ObjectPropertyString prevents inlining // as well. testSame("function f(x) {return x} " + "new JSCompiler_ObjectPropertyString(window, f); f(1)"); } public void testInlineWithClosureContainingThis() { test("(function (){return f(function(){return this})})();", "f(function(){return this})"); } public void testIssue5159924a() { test("function f() { if (x()) return y() }\n" + "while(1){ var m = f() || z() }", "for(;1;) {" + " var JSCompiler_inline_result$$0;" + " {" + " JSCompiler_inline_label_f_1: {" + " if(x()) {" + " JSCompiler_inline_result$$0 = y();" + " break JSCompiler_inline_label_f_1" + " }" + " JSCompiler_inline_result$$0 = void 0;" + " }" + " }" + " var m=JSCompiler_inline_result$$0 || z()" + "}"); } public void testIssue5159924b() { test("function f() { if (x()) return y() }\n" + "while(1){ var m = f() }", "for(;1;){" + " var m;" + " {" + " JSCompiler_inline_label_f_0: { " + " if(x()) {" + " m = y();" + " break JSCompiler_inline_label_f_0" + " }" + " m = void 0" + " }" + " }" + "}"); } public void testInlineObject() { new StringCompare().testInlineObject(); } private static class StringCompare extends CompilerTestCase { private boolean allowGlobalFunctionInlining = true; StringCompare() { super("", false); this.enableNormalize(); this.enableMarkNoSideEffects(); } @Override public void setUp() throws Exception { super.setUp(); super.enableLineNumberCheck(true); allowGlobalFunctionInlining = true; } @Override protected CompilerPass getProcessor(Compiler compiler) { compiler.resetUniqueNameId(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), allowGlobalFunctionInlining, true, // allowLocalFunctionInlining true, // allowBlockInlining true, // assumeStrictThis true); // assumeMinimumCapture } public void testInlineObject() { allowGlobalFunctionInlining = false; // TODO(johnlenz): normalize the AST so an AST comparison can be done. // As is, the expected AST does not match the actual correct result: // The AST matches "g.a()" with a FREE_CALL annotation, but this as // expected string would fail as it won't be mark as a free call. // "(0,g.a)()" matches the output, but not the resulting AST. test("function inner(){function f(){return g.a}(f())()}", "function inner(){(0,g.a)()}"); } } public void testBug4944818() { test( "var getDomServices_ = function(self) {\n" + " if (!self.domServices_) {\n" + " self.domServices_ = goog$component$DomServices.get(" + " self.appContext_);\n" + " }\n" + "\n" + " return self.domServices_;\n" + "};\n" + "\n" + "var getOwnerWin_ = function(self) {\n" + " return getDomServices_(self).getDomHelper().getWindow();\n" + "};\n" + "\n" + "HangoutStarter.prototype.launchHangout = function() {\n" + " var self = a.b;\n" + " var myUrl = new goog.Uri(getOwnerWin_(self).location.href);\n" + "};", "HangoutStarter.prototype.launchHangout = function() { " + " var self$$2 = a.b;" + " var JSCompiler_temp_const$$0 = goog.Uri;" + " var JSCompiler_inline_result$$1;" + " {" + " var self$$inline_2 = self$$2;" + " if (!self$$inline_2.domServices_) {" + " self$$inline_2.domServices_ = goog$component$DomServices.get(" + " self$$inline_2.appContext_);" + " }" + " JSCompiler_inline_result$$1=self$$inline_2.domServices_;" + " }" + " var myUrl = new JSCompiler_temp_const$$0(" + " JSCompiler_inline_result$$1.getDomHelper()." + " getWindow().location.href)" + "}"); } public void testIssue423() { assumeMinimumCapture = false; test( "(function($) {\n" + " $.fn.multicheck = function(options) {\n" + " initialize.call(this, options);\n" + " };\n" + "\n" + " function initialize(options) {\n" + " options.checkboxes = $(this).siblings(':checkbox');\n" + " preload_check_all.call(this);\n" + " }\n" + "\n" + " function preload_check_all() {\n" + " $(this).data('checkboxes');\n" + " }\n" + "})(jQuery)", "(function($){" + " $.fn.multicheck=function(options$$1){" + " {" + " options$$1.checkboxes=$(this).siblings(\":checkbox\");" + " {" + " $(this).data(\"checkboxes\")" + " }" + " }" + " }" + "})(jQuery)"); assumeMinimumCapture = true; test( "(function($) {\n" + " $.fn.multicheck = function(options) {\n" + " initialize.call(this, options);\n" + " };\n" + "\n" + " function initialize(options) {\n" + " options.checkboxes = $(this).siblings(':checkbox');\n" + " preload_check_all.call(this);\n" + " }\n" + "\n" + " function preload_check_all() {\n" + " $(this).data('checkboxes');\n" + " }\n" + "})(jQuery)", "{var $$$inline_0=jQuery;\n" + "$$$inline_0.fn.multicheck=function(options$$inline_4){\n" + " {options$$inline_4.checkboxes=" + "$$$inline_0(this).siblings(\":checkbox\");\n" + " {$$$inline_0(this).data(\"checkboxes\")}" + " }\n" + "}\n" + "}"); } public void testIssue728() { String f = "var f = function() { return false; };"; StringBuilder calls = new StringBuilder(); StringBuilder folded = new StringBuilder(); for (int i = 0; i < 30; i++) { calls.append("if (!f()) alert('x');"); folded.append("if (!false) alert('x');"); } test(f + calls, folded.toString()); } public void testAnonymous1() { assumeMinimumCapture = false; test("(function(){var a=10;(function(){var b=a;a++;alert(b)})()})();", "{var a$$inline_0=10;" + "{var b$$inline_1=a$$inline_0;" + "a$$inline_0++;alert(b$$inline_1)}}"); assumeMinimumCapture = true; test("(function(){var a=10;(function(){var b=a;a++;alert(b)})()})();", "{var a$$inline_2=10;" + "{var b$$inline_0=a$$inline_2;" + "a$$inline_2++;alert(b$$inline_0)}}"); } public void testAnonymous2() { testSame("(function(){eval();(function(){var b=a;a++;alert(b)})()})();"); } public void testAnonymous3() { // Introducing a new value into is tricky assumeMinimumCapture = false; testSame("(function(){var a=10;(function(){arguments;})()})();"); assumeMinimumCapture = true; test("(function(){var a=10;(function(){arguments;})()})();", "{var a$$inline_0=10;(function(){arguments;})();}"); test("(function(){(function(){arguments;})()})();", "{(function(){arguments;})()}"); } public void testLoopWithFunctionWithFunction() { assumeMinimumCapture = true; test("function _testLocalVariableInLoop_() {\n" + " var result = 0;\n" + " function foo() {\n" + " var arr = [1, 2, 3, 4, 5];\n" + " for (var i = 0, l = arr.length; i < l; i++) {\n" + " var j = arr[i];\n" + // don't inline this function, because the correct behavior depends // captured values. " (function() {\n" + " var k = j;\n" + " setTimeout(function() { result += k; }, 5 * i);\n" + " })();\n" + " }\n" + " }\n" + " foo();\n" + "}", "function _testLocalVariableInLoop_(){\n" + " var result=0;\n" + " {" + " var arr$$inline_0=[1,2,3,4,5];\n" + " var i$$inline_1=0;\n" + " var l$$inline_2=arr$$inline_0.length;\n" + " for(;i$$inline_1<l$$inline_2;i$$inline_1++){\n" + " var j$$inline_3=arr$$inline_0[i$$inline_1];\n" + " (function(){\n" + " var k$$inline_4=j$$inline_3;\n" + " setTimeout(function(){result+=k$$inline_4},5*i$$inline_1)\n" + " })()\n" + " }\n" + " }\n" + "}"); } public void testMethodWithFunctionWithFunction() { assumeMinimumCapture = true; test("function _testLocalVariable_() {\n" + " var result = 0;\n" + " function foo() {\n" + " var j = [i];\n" + " (function(j) {\n" + " setTimeout(function() { result += j; }, 5 * i);\n" + " })(j);\n" + " j = null;" + " }\n" + " foo();\n" + "}", "function _testLocalVariable_(){\n" + " var result=0;\n" + " {\n" + " var j$$inline_2=[i];\n" + " {\n" + " var j$$inline_0=j$$inline_2;\n" + // this temp is needed. " setTimeout(function(){result+=j$$inline_0},5*i);\n" + " }\n" + " j$$inline_2=null\n" + // because this value can be modified later. " }\n" + "}"); } // Inline a single reference function into deeper modules public void testCrossModuleInlining1() { test(createModuleChain( // m1 "function foo(){return f(1)+g(2)+h(3);}", // m2 "foo()" ), new String[] { // m1 "", // m2 "f(1)+g(2)+h(3);" } ); } // Inline a single reference function into shallow modules, only if it // is cheaper than the call itself. public void testCrossModuleInlining2() { testSame(createModuleChain( // m1 "foo()", // m2 "function foo(){return f(1)+g(2)+h(3);}" ) ); test(createModuleChain( // m1 "foo()", // m2 "function foo(){return f();}" ), new String[] { // m1 "f();", // m2 "" } ); } // Inline a multi-reference functions into shallow modules, only if it // is cheaper than the call itself. public void testCrossModuleInlining3() { testSame(createModuleChain( // m1 "foo()", // m2 "function foo(){return f(1)+g(2)+h(3);}", // m3 "foo()" ) ); test(createModuleChain( // m1 "foo()", // m2 "function foo(){return f();}", // m3 "foo()" ), new String[] { // m1 "f();", // m2 "", // m3 "f();" } ); } public void test6671158() { test( "function f() {return g()}" + "function Y(a){a.loader_()}" + "function _Z(){}" + "function _X() { new _Z(a,b, Y(singleton), f()) }", "function _Z(){}" + "function _X(){" + " var JSCompiler_temp_const$$2=_Z;" + " var JSCompiler_temp_const$$1=a;" + " var JSCompiler_temp_const$$0=b;" + " var JSCompiler_inline_result$$3;" + " {" + " singleton.loader_();" + " JSCompiler_inline_result$$3=void 0;" + " }" + " new JSCompiler_temp_const$$2(" + " JSCompiler_temp_const$$1," + " JSCompiler_temp_const$$0," + " JSCompiler_inline_result$$3," + " g())}"); } public void test8609285a() { test( "function f(x){ for(x in y){} } f()", "{var x$$inline_0=void 0;for(x$$inline_0 in y);}"); } public void test8609285b() { test( "function f(x){ for(var x in y){} } f()", "{var x$$inline_0=void 0;for(x$$inline_0 in y);}"); } }
public void testPrintWrapped() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; String expected; expected = "This is a" + hf.getNewLine() + "test."; hf.renderWrappedText(sb, 12, 0, text); assertEquals("single line text", expected, sb.toString()); sb.setLength(0); expected = "This is a" + hf.getNewLine() + " test."; hf.renderWrappedText(sb, 12, 4, text); assertEquals("single line padded text", expected, sb.toString()); text = " -p,--period <PERIOD> PERIOD is time duration of form " + "DATE[-DATE] where DATE has form YYYY[MM[DD]]"; sb.setLength(0); expected = " -p,--period <PERIOD> PERIOD is time duration of" + hf.getNewLine() + " form DATE[-DATE] where DATE" + hf.getNewLine() + " has form YYYY[MM[DD]]"; hf.renderWrappedText(sb, 53, 24, text); assertEquals("single line padded text 2", expected, sb.toString()); text = "aaaa aaaa aaaa" + hf.getNewLine() + "aaaaaa" + hf.getNewLine() + "aaaaa"; expected = text; sb.setLength(0); hf.renderWrappedText(sb, 16, 0, text); assertEquals("multi line text", expected, sb.toString()); expected = "aaaa aaaa aaaa" + hf.getNewLine() + " aaaaaa" + hf.getNewLine() + " aaaaa"; sb.setLength(0); hf.renderWrappedText(sb, 16, 4, text); assertEquals("multi-line padded text", expected, sb.toString()); }
org.apache.commons.cli.HelpFormatterTest::testPrintWrapped
src/test/org/apache/commons/cli/HelpFormatterTest.java
114
src/test/org/apache/commons/cli/HelpFormatterTest.java
testPrintWrapped
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test case for the HelpFormatter class * * @author Slawek Zachcial * @author John Keyes ( john at integralsource.com ) * @author brianegge **/ public class HelpFormatterTest extends TestCase { private static final String EOL = System.getProperty("line.separator"); public static void main( String[] args ) { String[] testName = { HelpFormatterTest.class.getName() }; junit.textui.TestRunner.main(testName); } public static TestSuite suite() { return new TestSuite(HelpFormatterTest.class); } public HelpFormatterTest( String s ) { super( s ); } public void testFindWrapPos() throws Exception { HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; //text width should be max 8; the wrap postition is 7 assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0)); //starting from 8 must give -1 - the wrap pos is after end assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8)); //if there is no a good position before width to make a wrapping look for the next one text = "aaaa aa"; assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0)); } public void testPrintWrapped() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; String expected; expected = "This is a" + hf.getNewLine() + "test."; hf.renderWrappedText(sb, 12, 0, text); assertEquals("single line text", expected, sb.toString()); sb.setLength(0); expected = "This is a" + hf.getNewLine() + " test."; hf.renderWrappedText(sb, 12, 4, text); assertEquals("single line padded text", expected, sb.toString()); text = " -p,--period <PERIOD> PERIOD is time duration of form " + "DATE[-DATE] where DATE has form YYYY[MM[DD]]"; sb.setLength(0); expected = " -p,--period <PERIOD> PERIOD is time duration of" + hf.getNewLine() + " form DATE[-DATE] where DATE" + hf.getNewLine() + " has form YYYY[MM[DD]]"; hf.renderWrappedText(sb, 53, 24, text); assertEquals("single line padded text 2", expected, sb.toString()); text = "aaaa aaaa aaaa" + hf.getNewLine() + "aaaaaa" + hf.getNewLine() + "aaaaa"; expected = text; sb.setLength(0); hf.renderWrappedText(sb, 16, 0, text); assertEquals("multi line text", expected, sb.toString()); expected = "aaaa aaaa aaaa" + hf.getNewLine() + " aaaaaa" + hf.getNewLine() + " aaaaa"; sb.setLength(0); hf.renderWrappedText(sb, 16, 4, text); assertEquals("multi-line padded text", expected, sb.toString()); } public void testPrintOptions() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); final int leftPad = 1; final int descPad = 3; final String lpad = hf.createPadding(leftPad); final String dpad = hf.createPadding(descPad); Options options = null; String expected = null; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa"; hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("simple non-wrapped option", expected, sb.toString()); int nextLineTabStop = leftPad+descPad+"-a".length(); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "aaaa aaaa"; sb.setLength(0); hf.renderOptions(sb, nextLineTabStop+17, options, leftPad, descPad); assertEquals("simple wrapped option", expected, sb.toString()); options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("long non-wrapped option", expected, sb.toString()); nextLineTabStop = leftPad+descPad+"-a,--aaa".length(); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("long wrapped option", expected, sb.toString()); options = new Options(). addOption("a", "aaa", false, "dddd dddd dddd dddd"). addOption("b", false, "feeee eeee eeee eeee"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.getNewLine() + lpad + "-b " + dpad + "feeee eeee" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "eeee eeee"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("multiple wrapped options", expected, sb.toString()); } public void testAutomaticUsage() throws Exception { HelpFormatter hf = new HelpFormatter(); Options options = null; String expected = "usage: app [-a]"; ByteArrayOutputStream out = new ByteArrayOutputStream( ); PrintWriter pw = new PrintWriter( out ); options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); hf.printUsage( pw, 60, "app", options ); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); expected = "usage: app [-a] [-b]"; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa") .addOption("b", false, "bbb" ); hf.printUsage( pw, 60, "app", options ); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); } // This test ensures the options are properly sorted // See https://issues.apache.org/jira/browse/CLI-131 public void testPrintUsage() { Option optionA = new Option("a", "first"); Option optionB = new Option("b", "second"); Option optionC = new Option("c", "third"); Options opts = new Options(); opts.addOption(optionA); opts.addOption(optionB); opts.addOption(optionC); HelpFormatter helpFormatter = new HelpFormatter(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(bytesOut); helpFormatter.printUsage(printWriter, 80, "app", opts); printWriter.close(); assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString()); } }
// You are a professional Java test case writer, please create a test case named `testPrintWrapped` for the issue `Cli-CLI-151`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-151 // // ## Issue-Title: // HelpFormatter wraps incorrectly on every line beyond the first // // ## Issue-Description: // // The method findWrapPos(...) in the HelpFormatter is a couple of bugs in the way that it deals with the "startPos" variable. This causes it to format every line beyond the first line by "startPos" to many characters, beyond the specified width. // // // To see this, create an option with a long description, and then use the help formatter to print it. The first line will be the correct length. The 2nd, 3rd, etc lines will all be too long. // // // I don't have a patch (sorry) - but here is a corrected version of the method. // // // I fixed it in two places - both were using "width + startPos" when they should have been using width. // // // // // ``` // protected int findWrapPos(String text, int width, int startPos) // { // int pos = -1; // // // the line ends before the max wrap pos or a new line char found // if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) // || ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width)) // { // return pos+1; // } // else if ((width) >= text.length()) // { // return -1; // } // // // // look for the last whitespace character before startPos+width // pos = width; // // char c; // // while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') // && (c != '\n') && (c != '\r')) // { // --pos; // } // // // if we found it - just return // if (pos > startPos) // { // return pos; // } // // // must look for the first whitespace chearacter after startPos // // + width // pos = startPos + width; // // while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') // && (c != '\n') && (c != '\r')) // { // ++pos; // } // // return (pos == text.length()) ? (-1) : pos; // } // // ``` // // // // // public void testPrintWrapped() throws Exception {
114
8
67
src/test/org/apache/commons/cli/HelpFormatterTest.java
src/test
```markdown ## Issue-ID: Cli-CLI-151 ## Issue-Title: HelpFormatter wraps incorrectly on every line beyond the first ## Issue-Description: The method findWrapPos(...) in the HelpFormatter is a couple of bugs in the way that it deals with the "startPos" variable. This causes it to format every line beyond the first line by "startPos" to many characters, beyond the specified width. To see this, create an option with a long description, and then use the help formatter to print it. The first line will be the correct length. The 2nd, 3rd, etc lines will all be too long. I don't have a patch (sorry) - but here is a corrected version of the method. I fixed it in two places - both were using "width + startPos" when they should have been using width. ``` protected int findWrapPos(String text, int width, int startPos) { int pos = -1; // the line ends before the max wrap pos or a new line char found if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) || ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width)) { return pos+1; } else if ((width) >= text.length()) { return -1; } // look for the last whitespace character before startPos+width pos = width; char c; while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { --pos; } // if we found it - just return if (pos > startPos) { return pos; } // must look for the first whitespace chearacter after startPos // + width pos = startPos + width; while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { ++pos; } return (pos == text.length()) ? (-1) : pos; } ``` ``` You are a professional Java test case writer, please create a test case named `testPrintWrapped` for the issue `Cli-CLI-151`, utilizing the provided issue report information and the following function signature. ```java public void testPrintWrapped() throws Exception { ```
67
[ "org.apache.commons.cli.HelpFormatter" ]
06a4b1a5880e47010b28e5cb1d3de6798c92c7a0d4113e697e16d87a8f5c04a0
public void testPrintWrapped() throws Exception
// You are a professional Java test case writer, please create a test case named `testPrintWrapped` for the issue `Cli-CLI-151`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-151 // // ## Issue-Title: // HelpFormatter wraps incorrectly on every line beyond the first // // ## Issue-Description: // // The method findWrapPos(...) in the HelpFormatter is a couple of bugs in the way that it deals with the "startPos" variable. This causes it to format every line beyond the first line by "startPos" to many characters, beyond the specified width. // // // To see this, create an option with a long description, and then use the help formatter to print it. The first line will be the correct length. The 2nd, 3rd, etc lines will all be too long. // // // I don't have a patch (sorry) - but here is a corrected version of the method. // // // I fixed it in two places - both were using "width + startPos" when they should have been using width. // // // // // ``` // protected int findWrapPos(String text, int width, int startPos) // { // int pos = -1; // // // the line ends before the max wrap pos or a new line char found // if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) // || ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width)) // { // return pos+1; // } // else if ((width) >= text.length()) // { // return -1; // } // // // // look for the last whitespace character before startPos+width // pos = width; // // char c; // // while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') // && (c != '\n') && (c != '\r')) // { // --pos; // } // // // if we found it - just return // if (pos > startPos) // { // return pos; // } // // // must look for the first whitespace chearacter after startPos // // + width // pos = startPos + width; // // while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') // && (c != '\n') && (c != '\r')) // { // ++pos; // } // // return (pos == text.length()) ? (-1) : pos; // } // // ``` // // // // //
Cli
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test case for the HelpFormatter class * * @author Slawek Zachcial * @author John Keyes ( john at integralsource.com ) * @author brianegge **/ public class HelpFormatterTest extends TestCase { private static final String EOL = System.getProperty("line.separator"); public static void main( String[] args ) { String[] testName = { HelpFormatterTest.class.getName() }; junit.textui.TestRunner.main(testName); } public static TestSuite suite() { return new TestSuite(HelpFormatterTest.class); } public HelpFormatterTest( String s ) { super( s ); } public void testFindWrapPos() throws Exception { HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; //text width should be max 8; the wrap postition is 7 assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0)); //starting from 8 must give -1 - the wrap pos is after end assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8)); //if there is no a good position before width to make a wrapping look for the next one text = "aaaa aa"; assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0)); } public void testPrintWrapped() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; String expected; expected = "This is a" + hf.getNewLine() + "test."; hf.renderWrappedText(sb, 12, 0, text); assertEquals("single line text", expected, sb.toString()); sb.setLength(0); expected = "This is a" + hf.getNewLine() + " test."; hf.renderWrappedText(sb, 12, 4, text); assertEquals("single line padded text", expected, sb.toString()); text = " -p,--period <PERIOD> PERIOD is time duration of form " + "DATE[-DATE] where DATE has form YYYY[MM[DD]]"; sb.setLength(0); expected = " -p,--period <PERIOD> PERIOD is time duration of" + hf.getNewLine() + " form DATE[-DATE] where DATE" + hf.getNewLine() + " has form YYYY[MM[DD]]"; hf.renderWrappedText(sb, 53, 24, text); assertEquals("single line padded text 2", expected, sb.toString()); text = "aaaa aaaa aaaa" + hf.getNewLine() + "aaaaaa" + hf.getNewLine() + "aaaaa"; expected = text; sb.setLength(0); hf.renderWrappedText(sb, 16, 0, text); assertEquals("multi line text", expected, sb.toString()); expected = "aaaa aaaa aaaa" + hf.getNewLine() + " aaaaaa" + hf.getNewLine() + " aaaaa"; sb.setLength(0); hf.renderWrappedText(sb, 16, 4, text); assertEquals("multi-line padded text", expected, sb.toString()); } public void testPrintOptions() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); final int leftPad = 1; final int descPad = 3; final String lpad = hf.createPadding(leftPad); final String dpad = hf.createPadding(descPad); Options options = null; String expected = null; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa"; hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("simple non-wrapped option", expected, sb.toString()); int nextLineTabStop = leftPad+descPad+"-a".length(); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "aaaa aaaa"; sb.setLength(0); hf.renderOptions(sb, nextLineTabStop+17, options, leftPad, descPad); assertEquals("simple wrapped option", expected, sb.toString()); options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("long non-wrapped option", expected, sb.toString()); nextLineTabStop = leftPad+descPad+"-a,--aaa".length(); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("long wrapped option", expected, sb.toString()); options = new Options(). addOption("a", "aaa", false, "dddd dddd dddd dddd"). addOption("b", false, "feeee eeee eeee eeee"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.getNewLine() + lpad + "-b " + dpad + "feeee eeee" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "eeee eeee"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("multiple wrapped options", expected, sb.toString()); } public void testAutomaticUsage() throws Exception { HelpFormatter hf = new HelpFormatter(); Options options = null; String expected = "usage: app [-a]"; ByteArrayOutputStream out = new ByteArrayOutputStream( ); PrintWriter pw = new PrintWriter( out ); options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); hf.printUsage( pw, 60, "app", options ); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); expected = "usage: app [-a] [-b]"; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa") .addOption("b", false, "bbb" ); hf.printUsage( pw, 60, "app", options ); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); } // This test ensures the options are properly sorted // See https://issues.apache.org/jira/browse/CLI-131 public void testPrintUsage() { Option optionA = new Option("a", "first"); Option optionB = new Option("b", "second"); Option optionC = new Option("c", "third"); Options opts = new Options(); opts.addOption(optionA); opts.addOption(optionB); opts.addOption(optionC); HelpFormatter helpFormatter = new HelpFormatter(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(bytesOut); helpFormatter.printUsage(printWriter, 80, "app", opts); printWriter.close(); assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString()); } }
public void testPropertyOptionFlags() throws Exception { Properties properties = new Properties(); properties.setProperty( "a", "true" ); properties.setProperty( "c", "yes" ); properties.setProperty( "e", "1" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("a") ); assertTrue( cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "false" ); properties.setProperty( "c", "no" ); properties.setProperty( "e", "0" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); // this option accepts as argument properties = new Properties(); properties.setProperty( "a", "TRUE" ); properties.setProperty( "c", "nO" ); properties.setProperty( "e", "TrUe" ); cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "just a string" ); properties.setProperty( "e", "" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); }
org.apache.commons.cli.ValueTest::testPropertyOptionFlags
src/test/org/apache/commons/cli/ValueTest.java
236
src/test/org/apache/commons/cli/ValueTest.java
testPropertyOptionFlags
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli; import java.util.Arrays; import java.util.Properties; import junit.framework.TestCase; public class ValueTest extends TestCase { private CommandLine _cl = null; private Options opts = new Options(); public void setUp() throws Exception { opts.addOption("a", false, "toggle -a"); opts.addOption("b", true, "set -b"); opts.addOption("c", "c", false, "toggle -c"); opts.addOption("d", "d", true, "set -d"); opts.addOption(OptionBuilder.hasOptionalArg().create('e')); opts.addOption(OptionBuilder.hasOptionalArg().withLongOpt("fish").create()); opts.addOption(OptionBuilder.hasOptionalArgs().withLongOpt("gravy").create()); opts.addOption(OptionBuilder.hasOptionalArgs(2).withLongOpt("hide").create()); opts.addOption(OptionBuilder.hasOptionalArgs(2).create('i')); opts.addOption(OptionBuilder.hasOptionalArgs().create('j')); opts.addOption(OptionBuilder.hasArgs().withValueSeparator(',').create('k')); String[] args = new String[] { "-a", "-b", "foo", "--c", "--d", "bar" }; Parser parser = new PosixParser(); _cl = parser.parse(opts,args); } public void testShortNoArg() { assertTrue( _cl.hasOption("a") ); assertNull( _cl.getOptionValue("a") ); } public void testShortWithArg() { assertTrue( _cl.hasOption("b") ); assertNotNull( _cl.getOptionValue("b") ); assertEquals( _cl.getOptionValue("b"), "foo"); } public void testLongNoArg() { assertTrue( _cl.hasOption("c") ); assertNull( _cl.getOptionValue("c") ); } public void testLongWithArg() { assertTrue( _cl.hasOption("d") ); assertNotNull( _cl.getOptionValue("d") ); assertEquals( _cl.getOptionValue("d"), "bar"); } public void testShortOptionalArgNoValue() throws Exception { String[] args = new String[] { "-e" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("e") ); assertNull( cmd.getOptionValue("e") ); } public void testShortOptionalArgValue() throws Exception { String[] args = new String[] { "-e", "everything" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("e") ); assertEquals( "everything", cmd.getOptionValue("e") ); } public void testLongOptionalNoValue() throws Exception { String[] args = new String[] { "--fish" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("fish") ); assertNull( cmd.getOptionValue("fish") ); } public void testLongOptionalArgValue() throws Exception { String[] args = new String[] { "--fish", "face" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("fish") ); assertEquals( "face", cmd.getOptionValue("fish") ); } public void testShortOptionalArgValues() throws Exception { String[] args = new String[] { "-j", "ink", "idea" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("j") ); assertEquals( "ink", cmd.getOptionValue("j") ); assertEquals( "ink", cmd.getOptionValues("j")[0] ); assertEquals( "idea", cmd.getOptionValues("j")[1] ); assertEquals( cmd.getArgs().length, 0 ); } public void testLongOptionalArgValues() throws Exception { String[] args = new String[] { "--gravy", "gold", "garden" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("gravy") ); assertEquals( "gold", cmd.getOptionValue("gravy") ); assertEquals( "gold", cmd.getOptionValues("gravy")[0] ); assertEquals( "garden", cmd.getOptionValues("gravy")[1] ); assertEquals( cmd.getArgs().length, 0 ); } public void testShortOptionalNArgValues() throws Exception { String[] args = new String[] { "-i", "ink", "idea", "isotope", "ice" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("i") ); assertEquals( "ink", cmd.getOptionValue("i") ); assertEquals( "ink", cmd.getOptionValues("i")[0] ); assertEquals( "idea", cmd.getOptionValues("i")[1] ); assertEquals( cmd.getArgs().length, 2 ); assertEquals( "isotope", cmd.getArgs()[0] ); assertEquals( "ice", cmd.getArgs()[1] ); } public void testLongOptionalNArgValues() throws Exception { String[] args = new String[] { "--hide", "house", "hair", "head" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("hide") ); assertEquals( "house", cmd.getOptionValue("hide") ); assertEquals( "house", cmd.getOptionValues("hide")[0] ); assertEquals( "hair", cmd.getOptionValues("hide")[1] ); assertEquals( cmd.getArgs().length, 1 ); assertEquals( "head", cmd.getArgs()[0] ); } public void testPropertyOptionSingularValue() throws Exception { Properties properties = new Properties(); properties.setProperty( "hide", "seek" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("hide") ); assertEquals( "seek", cmd.getOptionValue("hide") ); assertTrue( !cmd.hasOption("fake") ); } public void testPropertyOptionFlags() throws Exception { Properties properties = new Properties(); properties.setProperty( "a", "true" ); properties.setProperty( "c", "yes" ); properties.setProperty( "e", "1" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("a") ); assertTrue( cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "false" ); properties.setProperty( "c", "no" ); properties.setProperty( "e", "0" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); // this option accepts as argument properties = new Properties(); properties.setProperty( "a", "TRUE" ); properties.setProperty( "c", "nO" ); properties.setProperty( "e", "TrUe" ); cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "just a string" ); properties.setProperty( "e", "" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); } public void testPropertyOptionMultipleValues() throws Exception { Properties properties = new Properties(); properties.setProperty( "k", "one,two" ); Parser parser = new PosixParser(); String[] values = new String[] { "one", "two" }; CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("k") ); assertTrue( Arrays.equals( values, cmd.getOptionValues('k') ) ); } public void testPropertyOverrideValues() throws Exception { String[] args = new String[] { "-j", "found", "-i", "ink" }; Properties properties = new Properties(); properties.setProperty( "j", "seek" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, args, properties); assertTrue( cmd.hasOption("j") ); assertEquals( "found", cmd.getOptionValue("j") ); assertTrue( cmd.hasOption("i") ); assertEquals( "ink", cmd.getOptionValue("i") ); assertTrue( !cmd.hasOption("fake") ); } }
// You are a professional Java test case writer, please create a test case named `testPropertyOptionFlags` for the issue `Cli-CLI-201`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-201 // // ## Issue-Title: // Default options may be partially processed // // ## Issue-Description: // // The Properties instance passed to the Parser.parse() method to initialize the default options may be partially processed. This happens when the properties contains an option that doesn't accept arguments and has a default value that isn't evaluated to "true". When this case occurs the processing of the properties is stopped and the remaining options are never handled. // // // This is caused by the break statement in Parser.processProperties(Properties), a continue statement should have been used instead. // // // The related test in ValueTest is also wrong, there are two assertions that need to be changed: // // // // // ``` // Options opts = new Options(); // opts.addOption("a", false, "toggle -a"); // opts.addOption("c", "c", false, "toggle -c"); // opts.addOption(OptionBuilder.hasOptionalArg().create('e')); // // properties = new Properties(); // properties.setProperty( "a", "false" ); // properties.setProperty( "c", "no" ); // properties.setProperty( "e", "0" ); // // cmd = parser.parse(opts, null, properties); // assertTrue( !cmd.hasOption("a") ); // assertTrue( !cmd.hasOption("c") ); // assertTrue( !cmd.hasOption("e") ); // Wrong, this option accepts an argument and should receive the value "0" // // ``` // // // and the second one: // // // // // ``` // properties = new Properties(); // properties.setProperty( "a", "just a string" ); // properties.setProperty( "e", "" ); // // cmd = parser.parse(opts, null, properties); // assertTrue( !cmd.hasOption("a") ); // assertTrue( !cmd.hasOption("c") ); // assertTrue( !cmd.hasOption("e") ); // Wrong, this option accepts an argument and should receive an empty string as value // // ``` // // // // // public void testPropertyOptionFlags() throws Exception {
236
28
191
src/test/org/apache/commons/cli/ValueTest.java
src/test
```markdown ## Issue-ID: Cli-CLI-201 ## Issue-Title: Default options may be partially processed ## Issue-Description: The Properties instance passed to the Parser.parse() method to initialize the default options may be partially processed. This happens when the properties contains an option that doesn't accept arguments and has a default value that isn't evaluated to "true". When this case occurs the processing of the properties is stopped and the remaining options are never handled. This is caused by the break statement in Parser.processProperties(Properties), a continue statement should have been used instead. The related test in ValueTest is also wrong, there are two assertions that need to be changed: ``` Options opts = new Options(); opts.addOption("a", false, "toggle -a"); opts.addOption("c", "c", false, "toggle -c"); opts.addOption(OptionBuilder.hasOptionalArg().create('e')); properties = new Properties(); properties.setProperty( "a", "false" ); properties.setProperty( "c", "no" ); properties.setProperty( "e", "0" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( !cmd.hasOption("e") ); // Wrong, this option accepts an argument and should receive the value "0" ``` and the second one: ``` properties = new Properties(); properties.setProperty( "a", "just a string" ); properties.setProperty( "e", "" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( !cmd.hasOption("e") ); // Wrong, this option accepts an argument and should receive an empty string as value ``` ``` You are a professional Java test case writer, please create a test case named `testPropertyOptionFlags` for the issue `Cli-CLI-201`, utilizing the provided issue report information and the following function signature. ```java public void testPropertyOptionFlags() throws Exception { ```
191
[ "org.apache.commons.cli.Parser" ]
07be9f5a2dc338177219f9e05b441b6c77b4d7baec421c9c82e25c28a1683513
public void testPropertyOptionFlags() throws Exception
// You are a professional Java test case writer, please create a test case named `testPropertyOptionFlags` for the issue `Cli-CLI-201`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-201 // // ## Issue-Title: // Default options may be partially processed // // ## Issue-Description: // // The Properties instance passed to the Parser.parse() method to initialize the default options may be partially processed. This happens when the properties contains an option that doesn't accept arguments and has a default value that isn't evaluated to "true". When this case occurs the processing of the properties is stopped and the remaining options are never handled. // // // This is caused by the break statement in Parser.processProperties(Properties), a continue statement should have been used instead. // // // The related test in ValueTest is also wrong, there are two assertions that need to be changed: // // // // // ``` // Options opts = new Options(); // opts.addOption("a", false, "toggle -a"); // opts.addOption("c", "c", false, "toggle -c"); // opts.addOption(OptionBuilder.hasOptionalArg().create('e')); // // properties = new Properties(); // properties.setProperty( "a", "false" ); // properties.setProperty( "c", "no" ); // properties.setProperty( "e", "0" ); // // cmd = parser.parse(opts, null, properties); // assertTrue( !cmd.hasOption("a") ); // assertTrue( !cmd.hasOption("c") ); // assertTrue( !cmd.hasOption("e") ); // Wrong, this option accepts an argument and should receive the value "0" // // ``` // // // and the second one: // // // // // ``` // properties = new Properties(); // properties.setProperty( "a", "just a string" ); // properties.setProperty( "e", "" ); // // cmd = parser.parse(opts, null, properties); // assertTrue( !cmd.hasOption("a") ); // assertTrue( !cmd.hasOption("c") ); // assertTrue( !cmd.hasOption("e") ); // Wrong, this option accepts an argument and should receive an empty string as value // // ``` // // // // //
Cli
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli; import java.util.Arrays; import java.util.Properties; import junit.framework.TestCase; public class ValueTest extends TestCase { private CommandLine _cl = null; private Options opts = new Options(); public void setUp() throws Exception { opts.addOption("a", false, "toggle -a"); opts.addOption("b", true, "set -b"); opts.addOption("c", "c", false, "toggle -c"); opts.addOption("d", "d", true, "set -d"); opts.addOption(OptionBuilder.hasOptionalArg().create('e')); opts.addOption(OptionBuilder.hasOptionalArg().withLongOpt("fish").create()); opts.addOption(OptionBuilder.hasOptionalArgs().withLongOpt("gravy").create()); opts.addOption(OptionBuilder.hasOptionalArgs(2).withLongOpt("hide").create()); opts.addOption(OptionBuilder.hasOptionalArgs(2).create('i')); opts.addOption(OptionBuilder.hasOptionalArgs().create('j')); opts.addOption(OptionBuilder.hasArgs().withValueSeparator(',').create('k')); String[] args = new String[] { "-a", "-b", "foo", "--c", "--d", "bar" }; Parser parser = new PosixParser(); _cl = parser.parse(opts,args); } public void testShortNoArg() { assertTrue( _cl.hasOption("a") ); assertNull( _cl.getOptionValue("a") ); } public void testShortWithArg() { assertTrue( _cl.hasOption("b") ); assertNotNull( _cl.getOptionValue("b") ); assertEquals( _cl.getOptionValue("b"), "foo"); } public void testLongNoArg() { assertTrue( _cl.hasOption("c") ); assertNull( _cl.getOptionValue("c") ); } public void testLongWithArg() { assertTrue( _cl.hasOption("d") ); assertNotNull( _cl.getOptionValue("d") ); assertEquals( _cl.getOptionValue("d"), "bar"); } public void testShortOptionalArgNoValue() throws Exception { String[] args = new String[] { "-e" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("e") ); assertNull( cmd.getOptionValue("e") ); } public void testShortOptionalArgValue() throws Exception { String[] args = new String[] { "-e", "everything" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("e") ); assertEquals( "everything", cmd.getOptionValue("e") ); } public void testLongOptionalNoValue() throws Exception { String[] args = new String[] { "--fish" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("fish") ); assertNull( cmd.getOptionValue("fish") ); } public void testLongOptionalArgValue() throws Exception { String[] args = new String[] { "--fish", "face" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("fish") ); assertEquals( "face", cmd.getOptionValue("fish") ); } public void testShortOptionalArgValues() throws Exception { String[] args = new String[] { "-j", "ink", "idea" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("j") ); assertEquals( "ink", cmd.getOptionValue("j") ); assertEquals( "ink", cmd.getOptionValues("j")[0] ); assertEquals( "idea", cmd.getOptionValues("j")[1] ); assertEquals( cmd.getArgs().length, 0 ); } public void testLongOptionalArgValues() throws Exception { String[] args = new String[] { "--gravy", "gold", "garden" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("gravy") ); assertEquals( "gold", cmd.getOptionValue("gravy") ); assertEquals( "gold", cmd.getOptionValues("gravy")[0] ); assertEquals( "garden", cmd.getOptionValues("gravy")[1] ); assertEquals( cmd.getArgs().length, 0 ); } public void testShortOptionalNArgValues() throws Exception { String[] args = new String[] { "-i", "ink", "idea", "isotope", "ice" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("i") ); assertEquals( "ink", cmd.getOptionValue("i") ); assertEquals( "ink", cmd.getOptionValues("i")[0] ); assertEquals( "idea", cmd.getOptionValues("i")[1] ); assertEquals( cmd.getArgs().length, 2 ); assertEquals( "isotope", cmd.getArgs()[0] ); assertEquals( "ice", cmd.getArgs()[1] ); } public void testLongOptionalNArgValues() throws Exception { String[] args = new String[] { "--hide", "house", "hair", "head" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("hide") ); assertEquals( "house", cmd.getOptionValue("hide") ); assertEquals( "house", cmd.getOptionValues("hide")[0] ); assertEquals( "hair", cmd.getOptionValues("hide")[1] ); assertEquals( cmd.getArgs().length, 1 ); assertEquals( "head", cmd.getArgs()[0] ); } public void testPropertyOptionSingularValue() throws Exception { Properties properties = new Properties(); properties.setProperty( "hide", "seek" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("hide") ); assertEquals( "seek", cmd.getOptionValue("hide") ); assertTrue( !cmd.hasOption("fake") ); } public void testPropertyOptionFlags() throws Exception { Properties properties = new Properties(); properties.setProperty( "a", "true" ); properties.setProperty( "c", "yes" ); properties.setProperty( "e", "1" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("a") ); assertTrue( cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "false" ); properties.setProperty( "c", "no" ); properties.setProperty( "e", "0" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); // this option accepts as argument properties = new Properties(); properties.setProperty( "a", "TRUE" ); properties.setProperty( "c", "nO" ); properties.setProperty( "e", "TrUe" ); cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "just a string" ); properties.setProperty( "e", "" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); } public void testPropertyOptionMultipleValues() throws Exception { Properties properties = new Properties(); properties.setProperty( "k", "one,two" ); Parser parser = new PosixParser(); String[] values = new String[] { "one", "two" }; CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("k") ); assertTrue( Arrays.equals( values, cmd.getOptionValues('k') ) ); } public void testPropertyOverrideValues() throws Exception { String[] args = new String[] { "-j", "found", "-i", "ink" }; Properties properties = new Properties(); properties.setProperty( "j", "seek" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, args, properties); assertTrue( cmd.hasOption("j") ); assertEquals( "found", cmd.getOptionValue("j") ); assertTrue( cmd.hasOption("i") ); assertEquals( "ink", cmd.getOptionValue("i") ); assertTrue( !cmd.hasOption("fake") ); } }
public void testIssue1047() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " */\n" + "function C2() {}\n" + "\n" + "/**\n" + " * @constructor\n" + " */\n" + "function C3(c2) {\n" + " /**\n" + " * @type {C2} \n" + " * @private\n" + " */\n" + " this.c2_;\n" + "\n" + " var x = this.c2_.prop;\n" + "}", "Property prop never defined on C2"); }
com.google.javascript.jscomp.TypeCheckTest::testIssue1047
test/com/google/javascript/jscomp/TypeCheckTest.java
6,870
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue1047
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testGoodExtends18() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor\n" + " * @template T */\n" + "function C() {}\n" + "/** @constructor\n" + " * @extends {C.<string>} */\n" + "function D() {};\n" + "goog.inherits(D, C);\n" + "(new D())"); } public void testGoodExtends19() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */\n" + "function C() {}\n" + "" + "/** @interface\n" + " * @template T */\n" + "function D() {}\n" + "/** @param {T} t */\n" + "D.prototype.method;\n" + "" + "/** @constructor\n" + " * @template T\n" + " * @extends {C}\n" + " * @implements {D.<T>} */\n" + "function E() {};\n" + "goog.inherits(E, C);\n" + "/** @override */\n" + "E.prototype.method = function(t) {};\n" + "" + "var e = /** @type {E.<string>} */ (new E());\n" + "e.method(3);", "actual parameter 1 of E.prototype.method does not match formal " + "parameter\n" + "found : number\n" + "required: string"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testSetprop15() throws Exception { // Create static property on struct testTypes( "/** @interface */\n" + "function Peelable() {};\n" + "/** @return {undefined} */\n" + "Peelable.prototype.peel;\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Fruit() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Fruit}\n" + " * @implements {Peelable}\n" + " */\n" + "function Banana() { };\n" + "function f() {};\n" + "/** @override */\n" + "Banana.prototype.peel = f;"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar())['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testNamespaceType1() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @param {x.} y */ function f(y) {};", "Parse error. Namespaces not supported yet (x.)"); } public void testNamespaceType2() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @namespace */ x.y = {};" + "/** @param {x.y.} y */ function f(y) {}", "Parse error. Namespaces not supported yet (x.y.)"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } public void testIssue1023() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "(function () {" + " F.prototype = {" + " /** @param {string} x */" + " bar: function (x) { }" + " };" + "})();" + "(new F()).bar(true)", "actual parameter 1 of F.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testIssue1047() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " */\n" + "function C2() {}\n" + "\n" + "/**\n" + " * @constructor\n" + " */\n" + "function C3(c2) {\n" + " /**\n" + " * @type {C2} \n" + " * @private\n" + " */\n" + " this.c2_;\n" + "\n" + " var x = this.c2_.prop;\n" + "}", "Property prop never defined on C2"); } public void testIssue1072() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @return {number}\n" + " */\n" + "var f1 = function (x) {\n" + " return 3;\n" + "};\n" + "\n" + "/** Function */\n" + "var f2 = function (x) {\n" + " if (!x) throw new Error()\n" + " return /** @type {number} */ (f1('x'))\n" + "}\n" + "\n" + "/**\n" + " * @param {string} x\n" + " */\n" + "var f3 = function (x) {};\n" + "\n" + "f1(f3);", "actual parameter 1 of f1 does not match formal parameter\n" + "found : function (string): undefined\n" + "required: string"); } public void testEnums() throws Exception { testTypes( "var outer = function() {" + " /** @enum {number} */" + " var Level = {" + " NONE: 0," + " };" + " /** @type {!Level} */" + " var l = Level.NONE;" + "}"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType15() throws Exception { testTypes( "/**" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType16() throws Exception { testTypes( "/** @constructor */ function C() {this.foo = 1}\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType17() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType18() throws Exception { // Until template types can be restricted to exclude undefined, they // are always optional. testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({});"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};" + "" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {A}\n" + " */\n" + "var B = function() { this.bar = function(){}; };" + "" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype2() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " this.x = 123;\n" + "}\n" + "var objlit = /** @struct */ { y: 234 };\n" + "Foo.prototype = objlit;\n" + "var n = objlit.x;\n", "Property x never defined on Foo.prototype", false); } public void testIssue1024() throws Exception { testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = '__proto'\n" + "}\n" + "/** @param {Object} b\n" + " * @return {!Object}\n" + " */\n" + "function g(b) {\n" + " return b.prototype\n" + "}\n"); /* TODO(blickly): Make this warning go away. * This is old behavior, but it doesn't make sense to warn about since * both assignments are inferred. */ testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = {foo:3};\n" + "}\n" + "/** @param {Object} b\n" + " */\n" + "function g(b) {\n" + " b.prototype = function(){};\n" + "}\n", "assignment to property prototype of Object\n" + "found : {foo: number}\n" + "required: function (): undefined"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testIssue1047` for the issue `Closure-1047`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1047 // // ## Issue-Title: // Wrong type name reported on missing property error. // // ## Issue-Description: // /\*\* // \* @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 // // public void testIssue1047() throws Exception {
6,870
117
6,850
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-1047 ## Issue-Title: Wrong type name reported on missing property error. ## Issue-Description: /\*\* \* @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 ``` You are a professional Java test case writer, please create a test case named `testIssue1047` for the issue `Closure-1047`, utilizing the provided issue report information and the following function signature. ```java public void testIssue1047() throws Exception { ```
6,850
[ "com.google.javascript.jscomp.TypeValidator" ]
07cf137f8e93b1b3ea8d9d5deb05baafa7244be45fb719b13791f8e28a6b7d8e
public void testIssue1047() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue1047` for the issue `Closure-1047`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1047 // // ## Issue-Title: // Wrong type name reported on missing property error. // // ## Issue-Description: // /\*\* // \* @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 // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testGoodExtends18() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor\n" + " * @template T */\n" + "function C() {}\n" + "/** @constructor\n" + " * @extends {C.<string>} */\n" + "function D() {};\n" + "goog.inherits(D, C);\n" + "(new D())"); } public void testGoodExtends19() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */\n" + "function C() {}\n" + "" + "/** @interface\n" + " * @template T */\n" + "function D() {}\n" + "/** @param {T} t */\n" + "D.prototype.method;\n" + "" + "/** @constructor\n" + " * @template T\n" + " * @extends {C}\n" + " * @implements {D.<T>} */\n" + "function E() {};\n" + "goog.inherits(E, C);\n" + "/** @override */\n" + "E.prototype.method = function(t) {};\n" + "" + "var e = /** @type {E.<string>} */ (new E());\n" + "e.method(3);", "actual parameter 1 of E.prototype.method does not match formal " + "parameter\n" + "found : number\n" + "required: string"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testSetprop15() throws Exception { // Create static property on struct testTypes( "/** @interface */\n" + "function Peelable() {};\n" + "/** @return {undefined} */\n" + "Peelable.prototype.peel;\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Fruit() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Fruit}\n" + " * @implements {Peelable}\n" + " */\n" + "function Banana() { };\n" + "function f() {};\n" + "/** @override */\n" + "Banana.prototype.peel = f;"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar())['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testNamespaceType1() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @param {x.} y */ function f(y) {};", "Parse error. Namespaces not supported yet (x.)"); } public void testNamespaceType2() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @namespace */ x.y = {};" + "/** @param {x.y.} y */ function f(y) {}", "Parse error. Namespaces not supported yet (x.y.)"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } public void testIssue1023() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "(function () {" + " F.prototype = {" + " /** @param {string} x */" + " bar: function (x) { }" + " };" + "})();" + "(new F()).bar(true)", "actual parameter 1 of F.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testIssue1047() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " */\n" + "function C2() {}\n" + "\n" + "/**\n" + " * @constructor\n" + " */\n" + "function C3(c2) {\n" + " /**\n" + " * @type {C2} \n" + " * @private\n" + " */\n" + " this.c2_;\n" + "\n" + " var x = this.c2_.prop;\n" + "}", "Property prop never defined on C2"); } public void testIssue1072() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @return {number}\n" + " */\n" + "var f1 = function (x) {\n" + " return 3;\n" + "};\n" + "\n" + "/** Function */\n" + "var f2 = function (x) {\n" + " if (!x) throw new Error()\n" + " return /** @type {number} */ (f1('x'))\n" + "}\n" + "\n" + "/**\n" + " * @param {string} x\n" + " */\n" + "var f3 = function (x) {};\n" + "\n" + "f1(f3);", "actual parameter 1 of f1 does not match formal parameter\n" + "found : function (string): undefined\n" + "required: string"); } public void testEnums() throws Exception { testTypes( "var outer = function() {" + " /** @enum {number} */" + " var Level = {" + " NONE: 0," + " };" + " /** @type {!Level} */" + " var l = Level.NONE;" + "}"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType15() throws Exception { testTypes( "/**" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType16() throws Exception { testTypes( "/** @constructor */ function C() {this.foo = 1}\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType17() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType18() throws Exception { // Until template types can be restricted to exclude undefined, they // are always optional. testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({});"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};" + "" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {A}\n" + " */\n" + "var B = function() { this.bar = function(){}; };" + "" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype2() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " this.x = 123;\n" + "}\n" + "var objlit = /** @struct */ { y: 234 };\n" + "Foo.prototype = objlit;\n" + "var n = objlit.x;\n", "Property x never defined on Foo.prototype", false); } public void testIssue1024() throws Exception { testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = '__proto'\n" + "}\n" + "/** @param {Object} b\n" + " * @return {!Object}\n" + " */\n" + "function g(b) {\n" + " return b.prototype\n" + "}\n"); /* TODO(blickly): Make this warning go away. * This is old behavior, but it doesn't make sense to warn about since * both assignments are inferred. */ testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = {foo:3};\n" + "}\n" + "/** @param {Object} b\n" + " */\n" + "function g(b) {\n" + " b.prototype = function(){};\n" + "}\n", "assignment to property prototype of Object\n" + "found : {foo: number}\n" + "required: function (): undefined"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
@SuppressWarnings({ "unchecked", "rawtypes" }) public void testCustomEnumValueAndKeyViaModifier() throws IOException { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config, final JavaType type, BeanDescription beanDesc, final JsonDeserializer<?> deserializer) { return new JsonDeserializer<Enum>() { @Override public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); final String str = p.getValueAsString().toLowerCase(); return KeyEnum.valueOf(rawClass, str); } }; } @Override public KeyDeserializer modifyKeyDeserializer(DeserializationConfig config, final JavaType type, KeyDeserializer deserializer) { if (!type.isEnumType()) { return deserializer; } return new KeyDeserializer() { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); return Enum.valueOf(rawClass, key.toLowerCase()); } }; } }); ObjectMapper mapper = new ObjectMapper() .registerModule(module); // First, enum value as is KeyEnum key = mapper.readValue(quote(KeyEnum.replacements.name().toUpperCase()), KeyEnum.class); assertSame(KeyEnum.replacements, key); // and then as key EnumMap<KeyEnum,String> map = mapper.readValue( aposToQuotes("{'REPlaceMENTS':'foobar'}"), new TypeReference<EnumMap<KeyEnum,String>>() { }); assertEquals(1, map.size()); assertSame(KeyEnum.replacements, map.keySet().iterator().next()); }
com.fasterxml.jackson.databind.module.TestCustomEnumKeyDeserializer::testCustomEnumValueAndKeyViaModifier
src/test/java/com/fasterxml/jackson/databind/module/TestCustomEnumKeyDeserializer.java
279
src/test/java/com/fasterxml/jackson/databind/module/TestCustomEnumKeyDeserializer.java
testCustomEnumValueAndKeyViaModifier
package com.fasterxml.jackson.databind.module; import java.io.File; import java.io.IOException; import java.util.*; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.exc.InvalidFormatException; import com.fasterxml.jackson.databind.node.ObjectNode; @SuppressWarnings("serial") public class TestCustomEnumKeyDeserializer extends BaseMapTest { @JsonSerialize(using = TestEnumSerializer.class, keyUsing = TestEnumKeySerializer.class) @JsonDeserialize(using = TestEnumDeserializer.class, keyUsing = TestEnumKeyDeserializer.class) public enum TestEnumMixin { } enum KeyEnum { replacements, rootDirectory, licenseString } enum TestEnum { RED("red"), GREEN("green"); private final String code; TestEnum(String code) { this.code = code; } public static TestEnum lookup(String lower) { for (TestEnum item : values()) { if (item.code().equals(lower)) { return item; } } throw new IllegalArgumentException("Invalid code " + lower); } public String code() { return code; } } static class TestEnumSerializer extends JsonSerializer<TestEnum> { @Override public void serialize(TestEnum languageCode, JsonGenerator g, SerializerProvider serializerProvider) throws IOException { g.writeString(languageCode.code()); } @Override public Class<TestEnum> handledType() { return TestEnum.class; } } static class TestEnumKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { try { return TestEnum.lookup(key); } catch (IllegalArgumentException e) { return ctxt.handleWeirdKey(TestEnum.class, key, "Unknown code"); } } } static class TestEnumDeserializer extends StdDeserializer<TestEnum> { public TestEnumDeserializer() { super(TestEnum.class); } @Override public TestEnum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { String code = p.getText(); try { return TestEnum.lookup(code); } catch (IllegalArgumentException e) { throw InvalidFormatException.from(p, "Undefined ISO-639 language code", code, TestEnum.class); } } } static class TestEnumKeySerializer extends JsonSerializer<TestEnum> { @Override public void serialize(TestEnum test, JsonGenerator g, SerializerProvider serializerProvider) throws IOException { g.writeFieldName(test.code()); } @Override public Class<TestEnum> handledType() { return TestEnum.class; } } static class Bean { private File rootDirectory; private String licenseString; private Map<TestEnum, Map<String, String>> replacements; public File getRootDirectory() { return rootDirectory; } public void setRootDirectory(File rootDirectory) { this.rootDirectory = rootDirectory; } public String getLicenseString() { return licenseString; } public void setLicenseString(String licenseString) { this.licenseString = licenseString; } public Map<TestEnum, Map<String, String>> getReplacements() { return replacements; } public void setReplacements(Map<TestEnum, Map<String, String>> replacements) { this.replacements = replacements; } } static class TestEnumModule extends SimpleModule { public TestEnumModule() { super(Version.unknownVersion()); } @Override public void setupModule(SetupContext context) { context.setMixInAnnotations(TestEnum.class, TestEnumMixin.class); SimpleSerializers keySerializers = new SimpleSerializers(); keySerializers.addSerializer(new TestEnumKeySerializer()); context.addKeySerializers(keySerializers); } } // for [databind#1441] enum SuperTypeEnum { FOO; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "@type", defaultImpl = SuperType.class) static class SuperType { public Map<SuperTypeEnum, String> someMap; } /* /********************************************************** /* Test methods /********************************************************** */ // Test passing with the fix @Test public void testWithEnumKeys() throws Exception { ObjectMapper plainObjectMapper = new ObjectMapper(); JsonNode tree = plainObjectMapper.readTree(aposToQuotes("{'red' : [ 'a', 'b']}")); ObjectMapper fancyObjectMapper = new ObjectMapper().registerModule(new TestEnumModule()); // this line is might throw with Jackson 2.6.2. Map<TestEnum, Set<String>> map = fancyObjectMapper.convertValue(tree, new TypeReference<Map<TestEnum, Set<String>>>() { } ); assertNotNull(map); } // and another still failing // NOTE: temporarily named as non-test to ignore it; JsonIgnore doesn't work for some reason // public void testWithTree749() throws Exception public void withTree749() throws Exception { ObjectMapper mapper = new ObjectMapper().registerModule(new TestEnumModule()); Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>(); Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>(); Map<String, String> reps = new LinkedHashMap<String, String>(); reps.put("1", "one"); replacements.put(TestEnum.GREEN, reps); inputMap.put(KeyEnum.replacements, replacements); JsonNode tree = mapper.valueToTree(inputMap); ObjectNode ob = (ObjectNode) tree; JsonNode inner = ob.get("replacements"); String firstFieldName = inner.fieldNames().next(); assertEquals("green", firstFieldName); } // [databind#1441] public void testCustomEnumKeySerializerWithPolymorphic() throws IOException { SimpleModule simpleModule = new SimpleModule(); simpleModule.addDeserializer(SuperTypeEnum.class, new JsonDeserializer<SuperTypeEnum>() { @Override public SuperTypeEnum deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException { return SuperTypeEnum.valueOf(p.getText()); } }); ObjectMapper mapper = new ObjectMapper() .registerModule(simpleModule); SuperType superType = mapper.readValue("{\"someMap\": {\"FOO\": \"bar\"}}", SuperType.class); assertEquals("Deserialized someMap.FOO should equal bar", "bar", superType.someMap.get(SuperTypeEnum.FOO)); } // [databind#1445] @SuppressWarnings({ "unchecked", "rawtypes" }) public void testCustomEnumValueAndKeyViaModifier() throws IOException { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config, final JavaType type, BeanDescription beanDesc, final JsonDeserializer<?> deserializer) { return new JsonDeserializer<Enum>() { @Override public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); final String str = p.getValueAsString().toLowerCase(); return KeyEnum.valueOf(rawClass, str); } }; } @Override public KeyDeserializer modifyKeyDeserializer(DeserializationConfig config, final JavaType type, KeyDeserializer deserializer) { if (!type.isEnumType()) { return deserializer; } return new KeyDeserializer() { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); return Enum.valueOf(rawClass, key.toLowerCase()); } }; } }); ObjectMapper mapper = new ObjectMapper() .registerModule(module); // First, enum value as is KeyEnum key = mapper.readValue(quote(KeyEnum.replacements.name().toUpperCase()), KeyEnum.class); assertSame(KeyEnum.replacements, key); // and then as key EnumMap<KeyEnum,String> map = mapper.readValue( aposToQuotes("{'REPlaceMENTS':'foobar'}"), new TypeReference<EnumMap<KeyEnum,String>>() { }); assertEquals(1, map.size()); assertSame(KeyEnum.replacements, map.keySet().iterator().next()); } }
// You are a professional Java test case writer, please create a test case named `testCustomEnumValueAndKeyViaModifier` for the issue `JacksonDatabind-1445`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1445 // // ## Issue-Title: // Map key deserializerModifiers ignored // // ## Issue-Description: // We have a module that extends simple model to allow us to accept enum names in lower case in a fairly generic manner // // Inside that we add the `modifyKeyDeserializer` // // // The incoming class (using immutables) is mapped to a guava immutable map. // // Walking through the code: // // // // > // > com.fasterxml.jackson.datatype.guava.deser.ImmutableMapDeserializer.createContextual // > // > calls DeserializationContext.findKeyDeserializer // > // > calls DeserializerCache.findKeyDeserializer // > // > calls BasicDeserializerFactory.createKeyDeserializer // > // > // > // // // which has the code: // // // // ``` // // the only non-standard thing is this: // if (deser == null) { // if (type.isEnumType()) { // return \_createEnumKeyDeserializer(ctxt, type); // } // deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type); // } // ``` // // Since we are an enum type, it returns the value in the `_createEnumKeyDeserializer`, which is the standard enum deserializer. // // Below that block is the check for the hasDeserializerModifiers, but since we have returned already, it is never called, so we can't override the behaviour. // // // Module fragment: // // // // ``` // setDeserializerModifier(new BeanDeserializerModifier() { // @Override // @SuppressWarnings("unchecked") // public JsonDeserializer<Enum> modifyEnumDeserializer( // DeserializationConfig config, // final JavaType type, // BeanDescription beanDesc, // final JsonDeserializer<?> deserializer) { // return new JsonDeserializer<Enum>() { // @Override // public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { // Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); // return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase()); // } // }; // } // // @Override // public KeyDeserializer modifyKeyDeserializer( // DeserializationConfig config, // @SuppressWarnings({ "unchecked", "rawtypes" }) public void testCustomEnumValueAndKeyViaModifier() throws IOException {
279
// [databind#1445]
67
228
src/test/java/com/fasterxml/jackson/databind/module/TestCustomEnumKeyDeserializer.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1445 ## Issue-Title: Map key deserializerModifiers ignored ## Issue-Description: We have a module that extends simple model to allow us to accept enum names in lower case in a fairly generic manner Inside that we add the `modifyKeyDeserializer` The incoming class (using immutables) is mapped to a guava immutable map. Walking through the code: > > com.fasterxml.jackson.datatype.guava.deser.ImmutableMapDeserializer.createContextual > > calls DeserializationContext.findKeyDeserializer > > calls DeserializerCache.findKeyDeserializer > > calls BasicDeserializerFactory.createKeyDeserializer > > > which has the code: ``` // the only non-standard thing is this: if (deser == null) { if (type.isEnumType()) { return \_createEnumKeyDeserializer(ctxt, type); } deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type); } ``` Since we are an enum type, it returns the value in the `_createEnumKeyDeserializer`, which is the standard enum deserializer. Below that block is the check for the hasDeserializerModifiers, but since we have returned already, it is never called, so we can't override the behaviour. Module fragment: ``` setDeserializerModifier(new BeanDeserializerModifier() { @Override @SuppressWarnings("unchecked") public JsonDeserializer<Enum> modifyEnumDeserializer( DeserializationConfig config, final JavaType type, BeanDescription beanDesc, final JsonDeserializer<?> deserializer) { return new JsonDeserializer<Enum>() { @Override public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase()); } }; } @Override public KeyDeserializer modifyKeyDeserializer( DeserializationConfig config, ``` You are a professional Java test case writer, please create a test case named `testCustomEnumValueAndKeyViaModifier` for the issue `JacksonDatabind-1445`, utilizing the provided issue report information and the following function signature. ```java @SuppressWarnings({ "unchecked", "rawtypes" }) public void testCustomEnumValueAndKeyViaModifier() throws IOException { ```
228
[ "com.fasterxml.jackson.databind.deser.BasicDeserializerFactory" ]
07eae1ed4d266e930fc9bee30abaffb2bf09fcdb47d1a7a371337c99c601b4a0
@SuppressWarnings({ "unchecked", "rawtypes" }) public void testCustomEnumValueAndKeyViaModifier() throws IOException
// You are a professional Java test case writer, please create a test case named `testCustomEnumValueAndKeyViaModifier` for the issue `JacksonDatabind-1445`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1445 // // ## Issue-Title: // Map key deserializerModifiers ignored // // ## Issue-Description: // We have a module that extends simple model to allow us to accept enum names in lower case in a fairly generic manner // // Inside that we add the `modifyKeyDeserializer` // // // The incoming class (using immutables) is mapped to a guava immutable map. // // Walking through the code: // // // // > // > com.fasterxml.jackson.datatype.guava.deser.ImmutableMapDeserializer.createContextual // > // > calls DeserializationContext.findKeyDeserializer // > // > calls DeserializerCache.findKeyDeserializer // > // > calls BasicDeserializerFactory.createKeyDeserializer // > // > // > // // // which has the code: // // // // ``` // // the only non-standard thing is this: // if (deser == null) { // if (type.isEnumType()) { // return \_createEnumKeyDeserializer(ctxt, type); // } // deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type); // } // ``` // // Since we are an enum type, it returns the value in the `_createEnumKeyDeserializer`, which is the standard enum deserializer. // // Below that block is the check for the hasDeserializerModifiers, but since we have returned already, it is never called, so we can't override the behaviour. // // // Module fragment: // // // // ``` // setDeserializerModifier(new BeanDeserializerModifier() { // @Override // @SuppressWarnings("unchecked") // public JsonDeserializer<Enum> modifyEnumDeserializer( // DeserializationConfig config, // final JavaType type, // BeanDescription beanDesc, // final JsonDeserializer<?> deserializer) { // return new JsonDeserializer<Enum>() { // @Override // public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { // Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); // return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase()); // } // }; // } // // @Override // public KeyDeserializer modifyKeyDeserializer( // DeserializationConfig config, //
JacksonDatabind
package com.fasterxml.jackson.databind.module; import java.io.File; import java.io.IOException; import java.util.*; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.exc.InvalidFormatException; import com.fasterxml.jackson.databind.node.ObjectNode; @SuppressWarnings("serial") public class TestCustomEnumKeyDeserializer extends BaseMapTest { @JsonSerialize(using = TestEnumSerializer.class, keyUsing = TestEnumKeySerializer.class) @JsonDeserialize(using = TestEnumDeserializer.class, keyUsing = TestEnumKeyDeserializer.class) public enum TestEnumMixin { } enum KeyEnum { replacements, rootDirectory, licenseString } enum TestEnum { RED("red"), GREEN("green"); private final String code; TestEnum(String code) { this.code = code; } public static TestEnum lookup(String lower) { for (TestEnum item : values()) { if (item.code().equals(lower)) { return item; } } throw new IllegalArgumentException("Invalid code " + lower); } public String code() { return code; } } static class TestEnumSerializer extends JsonSerializer<TestEnum> { @Override public void serialize(TestEnum languageCode, JsonGenerator g, SerializerProvider serializerProvider) throws IOException { g.writeString(languageCode.code()); } @Override public Class<TestEnum> handledType() { return TestEnum.class; } } static class TestEnumKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { try { return TestEnum.lookup(key); } catch (IllegalArgumentException e) { return ctxt.handleWeirdKey(TestEnum.class, key, "Unknown code"); } } } static class TestEnumDeserializer extends StdDeserializer<TestEnum> { public TestEnumDeserializer() { super(TestEnum.class); } @Override public TestEnum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { String code = p.getText(); try { return TestEnum.lookup(code); } catch (IllegalArgumentException e) { throw InvalidFormatException.from(p, "Undefined ISO-639 language code", code, TestEnum.class); } } } static class TestEnumKeySerializer extends JsonSerializer<TestEnum> { @Override public void serialize(TestEnum test, JsonGenerator g, SerializerProvider serializerProvider) throws IOException { g.writeFieldName(test.code()); } @Override public Class<TestEnum> handledType() { return TestEnum.class; } } static class Bean { private File rootDirectory; private String licenseString; private Map<TestEnum, Map<String, String>> replacements; public File getRootDirectory() { return rootDirectory; } public void setRootDirectory(File rootDirectory) { this.rootDirectory = rootDirectory; } public String getLicenseString() { return licenseString; } public void setLicenseString(String licenseString) { this.licenseString = licenseString; } public Map<TestEnum, Map<String, String>> getReplacements() { return replacements; } public void setReplacements(Map<TestEnum, Map<String, String>> replacements) { this.replacements = replacements; } } static class TestEnumModule extends SimpleModule { public TestEnumModule() { super(Version.unknownVersion()); } @Override public void setupModule(SetupContext context) { context.setMixInAnnotations(TestEnum.class, TestEnumMixin.class); SimpleSerializers keySerializers = new SimpleSerializers(); keySerializers.addSerializer(new TestEnumKeySerializer()); context.addKeySerializers(keySerializers); } } // for [databind#1441] enum SuperTypeEnum { FOO; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "@type", defaultImpl = SuperType.class) static class SuperType { public Map<SuperTypeEnum, String> someMap; } /* /********************************************************** /* Test methods /********************************************************** */ // Test passing with the fix @Test public void testWithEnumKeys() throws Exception { ObjectMapper plainObjectMapper = new ObjectMapper(); JsonNode tree = plainObjectMapper.readTree(aposToQuotes("{'red' : [ 'a', 'b']}")); ObjectMapper fancyObjectMapper = new ObjectMapper().registerModule(new TestEnumModule()); // this line is might throw with Jackson 2.6.2. Map<TestEnum, Set<String>> map = fancyObjectMapper.convertValue(tree, new TypeReference<Map<TestEnum, Set<String>>>() { } ); assertNotNull(map); } // and another still failing // NOTE: temporarily named as non-test to ignore it; JsonIgnore doesn't work for some reason // public void testWithTree749() throws Exception public void withTree749() throws Exception { ObjectMapper mapper = new ObjectMapper().registerModule(new TestEnumModule()); Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>(); Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>(); Map<String, String> reps = new LinkedHashMap<String, String>(); reps.put("1", "one"); replacements.put(TestEnum.GREEN, reps); inputMap.put(KeyEnum.replacements, replacements); JsonNode tree = mapper.valueToTree(inputMap); ObjectNode ob = (ObjectNode) tree; JsonNode inner = ob.get("replacements"); String firstFieldName = inner.fieldNames().next(); assertEquals("green", firstFieldName); } // [databind#1441] public void testCustomEnumKeySerializerWithPolymorphic() throws IOException { SimpleModule simpleModule = new SimpleModule(); simpleModule.addDeserializer(SuperTypeEnum.class, new JsonDeserializer<SuperTypeEnum>() { @Override public SuperTypeEnum deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException { return SuperTypeEnum.valueOf(p.getText()); } }); ObjectMapper mapper = new ObjectMapper() .registerModule(simpleModule); SuperType superType = mapper.readValue("{\"someMap\": {\"FOO\": \"bar\"}}", SuperType.class); assertEquals("Deserialized someMap.FOO should equal bar", "bar", superType.someMap.get(SuperTypeEnum.FOO)); } // [databind#1445] @SuppressWarnings({ "unchecked", "rawtypes" }) public void testCustomEnumValueAndKeyViaModifier() throws IOException { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config, final JavaType type, BeanDescription beanDesc, final JsonDeserializer<?> deserializer) { return new JsonDeserializer<Enum>() { @Override public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); final String str = p.getValueAsString().toLowerCase(); return KeyEnum.valueOf(rawClass, str); } }; } @Override public KeyDeserializer modifyKeyDeserializer(DeserializationConfig config, final JavaType type, KeyDeserializer deserializer) { if (!type.isEnumType()) { return deserializer; } return new KeyDeserializer() { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass(); return Enum.valueOf(rawClass, key.toLowerCase()); } }; } }); ObjectMapper mapper = new ObjectMapper() .registerModule(module); // First, enum value as is KeyEnum key = mapper.readValue(quote(KeyEnum.replacements.name().toUpperCase()), KeyEnum.class); assertSame(KeyEnum.replacements, key); // and then as key EnumMap<KeyEnum,String> map = mapper.readValue( aposToQuotes("{'REPlaceMENTS':'foobar'}"), new TypeReference<EnumMap<KeyEnum,String>>() { }); assertEquals(1, map.size()); assertSame(KeyEnum.replacements, map.keySet().iterator().next()); } }
public void testDisappearingMixins515() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS) .disable(MapperFeature.AUTO_DETECT_FIELDS) .disable(MapperFeature.AUTO_DETECT_GETTERS) .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) .disable(MapperFeature.INFER_PROPERTY_MUTATORS); SimpleModule module = new SimpleModule("Test"); module.setMixInAnnotation(Person.class, PersonMixin.class); mapper.registerModule(module); assertEquals("{\"city\":\"Seattle\"}", mapper.writeValueAsString(new PersonImpl())); }
com.fasterxml.jackson.databind.introspect.TestMixinMerging::testDisappearingMixins515
src/test/java/com/fasterxml/jackson/databind/introspect/TestMixinMerging.java
48
src/test/java/com/fasterxml/jackson/databind/introspect/TestMixinMerging.java
testDisappearingMixins515
package com.fasterxml.jackson.databind.introspect; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.module.SimpleModule; public class TestMixinMerging extends BaseMapTest { public interface Contact { String getCity(); } static class ContactImpl implements Contact { public String getCity() { return "Seattle"; } } static class ContactMixin implements Contact { @JsonProperty public String getCity() { return null; } } public interface Person extends Contact {} static class PersonImpl extends ContactImpl implements Person {} static class PersonMixin extends ContactMixin implements Person {} /* /********************************************************** /* Unit tests /********************************************************** */ // for [Issue#515] public void testDisappearingMixins515() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS) .disable(MapperFeature.AUTO_DETECT_FIELDS) .disable(MapperFeature.AUTO_DETECT_GETTERS) .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) .disable(MapperFeature.INFER_PROPERTY_MUTATORS); SimpleModule module = new SimpleModule("Test"); module.setMixInAnnotation(Person.class, PersonMixin.class); mapper.registerModule(module); assertEquals("{\"city\":\"Seattle\"}", mapper.writeValueAsString(new PersonImpl())); } }
// You are a professional Java test case writer, please create a test case named `testDisappearingMixins515` for the issue `JacksonDatabind-515`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-515 // // ## Issue-Title: // Mixin annotations lost when using a mixin class hierarchy with non-mixin interfaces // // ## Issue-Description: // In summary, mixin annotations are lost when Jackson scans a parent mixin class with Json annotations followed by an interface implemented by the parent mixin class that does not have the same Json annotations. // // Jackson version: 2.4.0 // // // Detail: // // I have the following class structure // // // // ``` // public interface Contact { // String getCity(); // } // // public class ContactImpl implements Contact { // public String getCity() { ... } // } // // public class ContactMixin implements Contact { // @JsonProperty // public String getCity() { return null; } // } // // public interface Person extends Contact {} // // public class PersonImpl extends ContactImpl implements Person {} // // public class PersonMixin extends ContactMixin implements Person {} // ``` // // and I configure a module as // // // // ``` // // There are other getters/properties in the Impl class that do not need to be serialized and so // // I am using the Mixin to match the interface and explicitly annotate all the inherited methods // module.disable(MapperFeature.ALLOW\_FINAL\_FIELDS\_AS\_MUTATORS) // .disable(MapperFeature.AUTO\_DETECT\_FIELDS) // .disable(MapperFeature.AUTO\_DETECT\_GETTERS) // .disable(MapperFeature.AUTO\_DETECT\_IS\_GETTERS) // .disable(MapperFeature.INFER\_PROPERTY\_MUTATORS); // module.setMixInAnnotation(Person.class, PersonMixin.class); // ``` // // When a `PersonImpl` instance is serialized, `city` is not included. // // // I debugged the code and this is what happens: // // In `AnnotatedClass.resolveMemberMethods()` the supertypes of `PersonImpl` are `[Person.class, Contact.class, ContactImpl.class]` in that order. // // // It starts with `Person` for which it finds `PersonMixin` and proceeds to `AnnotatedClass._addMethodMixIns()`. Here the `parents` list has `[PersonMixin, ContactMixin, Contact]`. When it processes `ContactMixin` it adds `getCity()` with the `JsonProperty` annotation. Then it processes `Contact`, doesn't find `getCity()` in `methods` map and so creates a new `AnnotatedMethod` for `getCity()` with the one from the interface which has no annotation which replaces the one from `ContactMixin` // // // The workaround for this issue is to explicitly add any parent mixins to the module i.e. // // // // ``` // module.setMixInAnnotation(Contact.class, ContactMixin.class); // ``` // // // public void testDisappearingMixins515() throws Exception {
48
// for [Issue#515] /* /********************************************************** /* Unit tests /********************************************************** */
5
35
src/test/java/com/fasterxml/jackson/databind/introspect/TestMixinMerging.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-515 ## Issue-Title: Mixin annotations lost when using a mixin class hierarchy with non-mixin interfaces ## Issue-Description: In summary, mixin annotations are lost when Jackson scans a parent mixin class with Json annotations followed by an interface implemented by the parent mixin class that does not have the same Json annotations. Jackson version: 2.4.0 Detail: I have the following class structure ``` public interface Contact { String getCity(); } public class ContactImpl implements Contact { public String getCity() { ... } } public class ContactMixin implements Contact { @JsonProperty public String getCity() { return null; } } public interface Person extends Contact {} public class PersonImpl extends ContactImpl implements Person {} public class PersonMixin extends ContactMixin implements Person {} ``` and I configure a module as ``` // There are other getters/properties in the Impl class that do not need to be serialized and so // I am using the Mixin to match the interface and explicitly annotate all the inherited methods module.disable(MapperFeature.ALLOW\_FINAL\_FIELDS\_AS\_MUTATORS) .disable(MapperFeature.AUTO\_DETECT\_FIELDS) .disable(MapperFeature.AUTO\_DETECT\_GETTERS) .disable(MapperFeature.AUTO\_DETECT\_IS\_GETTERS) .disable(MapperFeature.INFER\_PROPERTY\_MUTATORS); module.setMixInAnnotation(Person.class, PersonMixin.class); ``` When a `PersonImpl` instance is serialized, `city` is not included. I debugged the code and this is what happens: In `AnnotatedClass.resolveMemberMethods()` the supertypes of `PersonImpl` are `[Person.class, Contact.class, ContactImpl.class]` in that order. It starts with `Person` for which it finds `PersonMixin` and proceeds to `AnnotatedClass._addMethodMixIns()`. Here the `parents` list has `[PersonMixin, ContactMixin, Contact]`. When it processes `ContactMixin` it adds `getCity()` with the `JsonProperty` annotation. Then it processes `Contact`, doesn't find `getCity()` in `methods` map and so creates a new `AnnotatedMethod` for `getCity()` with the one from the interface which has no annotation which replaces the one from `ContactMixin` The workaround for this issue is to explicitly add any parent mixins to the module i.e. ``` module.setMixInAnnotation(Contact.class, ContactMixin.class); ``` ``` You are a professional Java test case writer, please create a test case named `testDisappearingMixins515` for the issue `JacksonDatabind-515`, utilizing the provided issue report information and the following function signature. ```java public void testDisappearingMixins515() throws Exception { ```
35
[ "com.fasterxml.jackson.databind.introspect.AnnotatedClass" ]
087f36d21997ef4790c74a98f969082973773cace36a3204ae644d604f73103c
public void testDisappearingMixins515() throws Exception
// You are a professional Java test case writer, please create a test case named `testDisappearingMixins515` for the issue `JacksonDatabind-515`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-515 // // ## Issue-Title: // Mixin annotations lost when using a mixin class hierarchy with non-mixin interfaces // // ## Issue-Description: // In summary, mixin annotations are lost when Jackson scans a parent mixin class with Json annotations followed by an interface implemented by the parent mixin class that does not have the same Json annotations. // // Jackson version: 2.4.0 // // // Detail: // // I have the following class structure // // // // ``` // public interface Contact { // String getCity(); // } // // public class ContactImpl implements Contact { // public String getCity() { ... } // } // // public class ContactMixin implements Contact { // @JsonProperty // public String getCity() { return null; } // } // // public interface Person extends Contact {} // // public class PersonImpl extends ContactImpl implements Person {} // // public class PersonMixin extends ContactMixin implements Person {} // ``` // // and I configure a module as // // // // ``` // // There are other getters/properties in the Impl class that do not need to be serialized and so // // I am using the Mixin to match the interface and explicitly annotate all the inherited methods // module.disable(MapperFeature.ALLOW\_FINAL\_FIELDS\_AS\_MUTATORS) // .disable(MapperFeature.AUTO\_DETECT\_FIELDS) // .disable(MapperFeature.AUTO\_DETECT\_GETTERS) // .disable(MapperFeature.AUTO\_DETECT\_IS\_GETTERS) // .disable(MapperFeature.INFER\_PROPERTY\_MUTATORS); // module.setMixInAnnotation(Person.class, PersonMixin.class); // ``` // // When a `PersonImpl` instance is serialized, `city` is not included. // // // I debugged the code and this is what happens: // // In `AnnotatedClass.resolveMemberMethods()` the supertypes of `PersonImpl` are `[Person.class, Contact.class, ContactImpl.class]` in that order. // // // It starts with `Person` for which it finds `PersonMixin` and proceeds to `AnnotatedClass._addMethodMixIns()`. Here the `parents` list has `[PersonMixin, ContactMixin, Contact]`. When it processes `ContactMixin` it adds `getCity()` with the `JsonProperty` annotation. Then it processes `Contact`, doesn't find `getCity()` in `methods` map and so creates a new `AnnotatedMethod` for `getCity()` with the one from the interface which has no annotation which replaces the one from `ContactMixin` // // // The workaround for this issue is to explicitly add any parent mixins to the module i.e. // // // // ``` // module.setMixInAnnotation(Contact.class, ContactMixin.class); // ``` // // //
JacksonDatabind
package com.fasterxml.jackson.databind.introspect; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.module.SimpleModule; public class TestMixinMerging extends BaseMapTest { public interface Contact { String getCity(); } static class ContactImpl implements Contact { public String getCity() { return "Seattle"; } } static class ContactMixin implements Contact { @JsonProperty public String getCity() { return null; } } public interface Person extends Contact {} static class PersonImpl extends ContactImpl implements Person {} static class PersonMixin extends ContactMixin implements Person {} /* /********************************************************** /* Unit tests /********************************************************** */ // for [Issue#515] public void testDisappearingMixins515() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS) .disable(MapperFeature.AUTO_DETECT_FIELDS) .disable(MapperFeature.AUTO_DETECT_GETTERS) .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) .disable(MapperFeature.INFER_PROPERTY_MUTATORS); SimpleModule module = new SimpleModule("Test"); module.setMixInAnnotation(Person.class, PersonMixin.class); mapper.registerModule(module); assertEquals("{\"city\":\"Seattle\"}", mapper.writeValueAsString(new PersonImpl())); } }
public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { // this is the utf8 representation of the character: // COUNTING ROD UNIT DIGIT THREE // in unicode // codepoint: U+1D362 byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }; String escaped = StringEscapeUtils.escapeHtml( new String(data, "UTF8") ); String unescaped = StringEscapeUtils.unescapeHtml( escaped ); assertEquals( "High unicode was not escaped correctly", "&#119650;", escaped); }
org.apache.commons.lang.StringEscapeUtilsTest::testEscapeHtmlHighUnicode
src/test/org/apache/commons/lang/StringEscapeUtilsTest.java
430
src/test/org/apache/commons/lang/StringEscapeUtilsTest.java
testEscapeHtmlHighUnicode
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Unit tests for {@link StringEscapeUtils}. * * @author <a href="mailto:alex@purpletech.com">Alexander Day Chaffee</a> * @version $Id$ */ public class StringEscapeUtilsTest extends TestCase { private final static String FOO = "foo"; public StringEscapeUtilsTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(StringEscapeUtilsTest.class); suite.setName("StringEscapeUtilsTest Tests"); return suite; } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new StringEscapeUtils()); Constructor[] cons = StringEscapeUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(StringEscapeUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(StringEscapeUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testEscapeJava() throws IOException { assertEquals(null, StringEscapeUtils.escapeJava(null)); try { StringEscapeUtils.escapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJava(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEscapeJava("empty string", "", ""); assertEscapeJava(FOO, FOO); assertEscapeJava("tab", "\\t", "\t"); assertEscapeJava("backslash", "\\\\", "\\"); assertEscapeJava("single quote should not be escaped", "'", "'"); assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r"); assertEscapeJava("\\u1234", "\u1234"); assertEscapeJava("\\u0234", "\u0234"); assertEscapeJava("\\u00EF", "\u00ef"); assertEscapeJava("\\u0001", "\u0001"); assertEscapeJava("Should use capitalized unicode hex", "\\uABCD", "\uabcd"); assertEscapeJava("He didn't say, \\\"stop!\\\"", "He didn't say, \"stop!\""); assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0"); assertEscapeJava("\\uABCD\\u1234\\u012C", "\uABCD\u1234\u012C"); } /** * https://issues.apache.org/jira/browse/LANG-421 */ public void testEscapeJavaWithSlash() { final String input = "String with a slash (/) in it"; final String expected = input; final String actual = StringEscapeUtils.escapeJava(input); /** * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape * in a Java string. */ assertEquals(expected, actual); } private void assertEscapeJava(String escaped, String original) throws IOException { assertEscapeJava(null, escaped, original); } private void assertEscapeJava(String message, String expected, String original) throws IOException { String converted = StringEscapeUtils.escapeJava(original); message = "escapeJava(String) failed" + (message == null ? "" : (": " + message)); assertEquals(message, expected, converted); StringWriter writer = new StringWriter(); StringEscapeUtils.escapeJava(writer, original); assertEquals(expected, writer.toString()); } public void testUnescapeJava() throws IOException { assertEquals(null, StringEscapeUtils.unescapeJava(null)); try { StringEscapeUtils.unescapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava("\\u02-3"); fail(); } catch (RuntimeException ex) { } assertUnescapeJava("", ""); assertUnescapeJava("test", "test"); assertUnescapeJava("\ntest\b", "\\ntest\\b"); assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b"); assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r"); assertUnescapeJava("\\", "\\"); //foo assertUnescapeJava("lowercase unicode", "\uABCDx", "\\uabcdx"); assertUnescapeJava("uppercase unicode", "\uABCDx", "\\uABCDx"); assertUnescapeJava("unicode as final character", "\uABCD", "\\uabcd"); } private void assertUnescapeJava(String unescaped, String original) throws IOException { assertUnescapeJava(null, unescaped, original); } private void assertUnescapeJava(String message, String unescaped, String original) throws IOException { String expected = unescaped; String actual = StringEscapeUtils.unescapeJava(original); assertEquals("unescape(String) failed" + (message == null ? "" : (": " + message)) + ": expected '" + StringEscapeUtils.escapeJava(expected) + // we escape this so we can see it in the error message "' actual '" + StringEscapeUtils.escapeJava(actual) + "'", expected, actual); StringWriter writer = new StringWriter(); StringEscapeUtils.unescapeJava(writer, original); assertEquals(unescaped, writer.toString()); } public void testEscapeJavaScript() { assertEquals(null, StringEscapeUtils.escapeJavaScript(null)); try { StringEscapeUtils.escapeJavaScript(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJavaScript(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeJavaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';", StringEscapeUtils.escapeJavaScript("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';")); } // HTML and XML //-------------------------------------------------------------- String[][] htmlEscapes = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread &amp; butter", "bread & butter"}, {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, {"final character only", "greater than &gt;", "greater than >"}, {"first character only", "&lt; less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Fran&ccedil;ais,&#26085;&#26412;&#35486; (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii doesn't number-escape", "~\u007F", "\u007E\u007F"}, {"8-bit ascii does number-escape", "&#128;&#159;", "\u0080\u009F"}, }; public void testEscapeHtml() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][1]; String original = htmlEscapes[i][2]; assertEquals(message, expected, StringEscapeUtils.escapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.escapeHtml(sw, original); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } } public void testUnescapeHtml() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][2]; String original = htmlEscapes[i][1]; assertEquals(message, expected, StringEscapeUtils.unescapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.unescapeHtml(sw, original); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } // \u00E7 is a cedilla (c with wiggle under) // note that the test string must be 7-bit-clean (unicode escaped) or else it will compile incorrectly // on some locales assertEquals("funny chars pass through OK", "Fran\u00E7ais", StringEscapeUtils.unescapeHtml("Fran\u00E7ais")); assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml("Hello&;World")); assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml("Hello&#;World")); assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml("Hello&# ;World")); assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml("Hello&##;World")); } public void testUnescapeHexCharsHtml() { // Simple easy to grok test assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("&#x80;&#x9F;")); assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("&#X80;&#X9F;")); // Test all Character values: for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { Character c1 = new Character(i); Character c2 = new Character((char)(i+1)); String expected = c1.toString() + c2.toString(); String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";"; String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";"; assertEquals("hex number unescape index " + (int)i, expected, StringEscapeUtils.unescapeHtml(escapedC1 + escapedC2)); } } public void testUnescapeUnknownEntity() throws Exception { assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml("&zzzz;")); } public void testEscapeHtmlVersions() throws Exception { assertEquals("&Beta;", StringEscapeUtils.escapeHtml("\u0392")); assertEquals("\u0392", StringEscapeUtils.unescapeHtml("&Beta;")); //todo: refine API for escaping/unescaping specific HTML versions } public void testEscapeXml() throws Exception { assertEquals("&lt;abc&gt;", StringEscapeUtils.escapeXml("<abc>")); assertEquals("<abc>", StringEscapeUtils.unescapeXml("&lt;abc&gt;")); assertEquals("XML should use numbers, not names for HTML entities", "&#161;", StringEscapeUtils.escapeXml("\u00A1")); assertEquals("XML should use numbers, not names for HTML entities", "\u00A0", StringEscapeUtils.unescapeXml("&#160;")); assertEquals("ain't", StringEscapeUtils.unescapeXml("ain&apos;t")); assertEquals("ain&apos;t", StringEscapeUtils.escapeXml("ain't")); assertEquals("", StringEscapeUtils.escapeXml("")); assertEquals(null, StringEscapeUtils.escapeXml(null)); assertEquals(null, StringEscapeUtils.unescapeXml(null)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.escapeXml(sw, "<abc>"); } catch (IOException e) { } assertEquals("XML was escaped incorrectly", "&lt;abc&gt;", sw.toString() ); sw = new StringWriter(); try { StringEscapeUtils.unescapeXml(sw, "&lt;abc&gt;"); } catch (IOException e) { } assertEquals("XML was unescaped incorrectly", "<abc>", sw.toString() ); } // SQL // see http://www.jguru.com/faq/view.jsp?EID=8881 //-------------------- public void testEscapeSql() throws Exception { assertEquals("don''t stop", StringEscapeUtils.escapeSql("don't stop")); assertEquals("", StringEscapeUtils.escapeSql("")); assertEquals(null, StringEscapeUtils.escapeSql(null)); } // Tests issue #38569 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 public void testStandaloneAmphersand() { assertEquals("<P&O>", StringEscapeUtils.unescapeHtml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeHtml("test & &lt;")); assertEquals("<P&O>", StringEscapeUtils.unescapeXml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeXml("test & &lt;")); } public void testLang313() { assertEquals("& &", StringEscapeUtils.unescapeHtml("& &amp;")); } public void testEscapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar")); assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar")); assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar")); assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar")); assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar")); assertEquals("", StringEscapeUtils.escapeCsv("")); assertEquals(null, StringEscapeUtils.escapeCsv(null)); } public void testEscapeCsvWriter() throws Exception { checkCsvEscapeWriter("foo.bar", "foo.bar"); checkCsvEscapeWriter("\"foo,bar\"", "foo,bar"); checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar"); checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar"); checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar"); checkCsvEscapeWriter("", null); checkCsvEscapeWriter("", ""); } private void checkCsvEscapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.escapeCsv(writer, value); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } public void testUnescapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar")); assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\"")); assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\"")); assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\"")); assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\"")); assertEquals("", StringEscapeUtils.unescapeCsv("")); assertEquals(null, StringEscapeUtils.unescapeCsv(null)); assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\"")); } public void testUnescapeCsvWriter() throws Exception { checkCsvUnescapeWriter("foo.bar", "foo.bar"); checkCsvUnescapeWriter("foo,bar", "\"foo,bar\""); checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\""); checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\""); checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\""); checkCsvUnescapeWriter("", null); checkCsvUnescapeWriter("", ""); checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\""); } private void checkCsvUnescapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.unescapeCsv(writer, value); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } // https://issues.apache.org/jira/browse/LANG-480 public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { // this is the utf8 representation of the character: // COUNTING ROD UNIT DIGIT THREE // in unicode // codepoint: U+1D362 byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }; String escaped = StringEscapeUtils.escapeHtml( new String(data, "UTF8") ); String unescaped = StringEscapeUtils.unescapeHtml( escaped ); assertEquals( "High unicode was not escaped correctly", "&#119650;", escaped); } }
// You are a professional Java test case writer, please create a test case named `testEscapeHtmlHighUnicode` for the issue `Lang-LANG-480`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-480 // // ## Issue-Title: // StringEscapeUtils.escapeHtml incorrectly converts unicode characters above U+00FFFF into 2 characters // // ## Issue-Description: // // Characters that are represented as a 2 characters internaly by java are incorrectly converted by the function. The following test displays the problem quite nicely: // // // import org.apache.commons.lang.\*; // // // public class J2 { // // public static void main(String[] args) throws Exception { // // // this is the utf8 representation of the character: // // // COUNTING ROD UNIT DIGIT THREE // // // in unicode // // // codepoint: U+1D362 // // byte[] data = new byte[] // // // { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 } // ; // // // //output is: &#55348;&#57186; // // // should be: &#119650; // // System.out.println("'" + StringEscapeUtils.escapeHtml(new String(data, "UTF8")) + "'"); // // } // // } // // // Should be very quick to fix, feel free to drop me an email if you want a patch. // // // // // public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException {
430
// https://issues.apache.org/jira/browse/LANG-480
42
419
src/test/org/apache/commons/lang/StringEscapeUtilsTest.java
src/test
```markdown ## Issue-ID: Lang-LANG-480 ## Issue-Title: StringEscapeUtils.escapeHtml incorrectly converts unicode characters above U+00FFFF into 2 characters ## Issue-Description: Characters that are represented as a 2 characters internaly by java are incorrectly converted by the function. The following test displays the problem quite nicely: import org.apache.commons.lang.\*; public class J2 { public static void main(String[] args) throws Exception { // this is the utf8 representation of the character: // COUNTING ROD UNIT DIGIT THREE // in unicode // codepoint: U+1D362 byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 } ; //output is: &#55348;&#57186; // should be: &#119650; System.out.println("'" + StringEscapeUtils.escapeHtml(new String(data, "UTF8")) + "'"); } } Should be very quick to fix, feel free to drop me an email if you want a patch. ``` You are a professional Java test case writer, please create a test case named `testEscapeHtmlHighUnicode` for the issue `Lang-LANG-480`, utilizing the provided issue report information and the following function signature. ```java public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { ```
419
[ "org.apache.commons.lang.Entities" ]
09e21fc9f93ec3b58ce73a20100c02baa5b8011972117677c0d29019423b3d43
public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException
// You are a professional Java test case writer, please create a test case named `testEscapeHtmlHighUnicode` for the issue `Lang-LANG-480`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-480 // // ## Issue-Title: // StringEscapeUtils.escapeHtml incorrectly converts unicode characters above U+00FFFF into 2 characters // // ## Issue-Description: // // Characters that are represented as a 2 characters internaly by java are incorrectly converted by the function. The following test displays the problem quite nicely: // // // import org.apache.commons.lang.\*; // // // public class J2 { // // public static void main(String[] args) throws Exception { // // // this is the utf8 representation of the character: // // // COUNTING ROD UNIT DIGIT THREE // // // in unicode // // // codepoint: U+1D362 // // byte[] data = new byte[] // // // { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 } // ; // // // //output is: &#55348;&#57186; // // // should be: &#119650; // // System.out.println("'" + StringEscapeUtils.escapeHtml(new String(data, "UTF8")) + "'"); // // } // // } // // // Should be very quick to fix, feel free to drop me an email if you want a patch. // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Unit tests for {@link StringEscapeUtils}. * * @author <a href="mailto:alex@purpletech.com">Alexander Day Chaffee</a> * @version $Id$ */ public class StringEscapeUtilsTest extends TestCase { private final static String FOO = "foo"; public StringEscapeUtilsTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(StringEscapeUtilsTest.class); suite.setName("StringEscapeUtilsTest Tests"); return suite; } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new StringEscapeUtils()); Constructor[] cons = StringEscapeUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(StringEscapeUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(StringEscapeUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testEscapeJava() throws IOException { assertEquals(null, StringEscapeUtils.escapeJava(null)); try { StringEscapeUtils.escapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJava(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEscapeJava("empty string", "", ""); assertEscapeJava(FOO, FOO); assertEscapeJava("tab", "\\t", "\t"); assertEscapeJava("backslash", "\\\\", "\\"); assertEscapeJava("single quote should not be escaped", "'", "'"); assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r"); assertEscapeJava("\\u1234", "\u1234"); assertEscapeJava("\\u0234", "\u0234"); assertEscapeJava("\\u00EF", "\u00ef"); assertEscapeJava("\\u0001", "\u0001"); assertEscapeJava("Should use capitalized unicode hex", "\\uABCD", "\uabcd"); assertEscapeJava("He didn't say, \\\"stop!\\\"", "He didn't say, \"stop!\""); assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0"); assertEscapeJava("\\uABCD\\u1234\\u012C", "\uABCD\u1234\u012C"); } /** * https://issues.apache.org/jira/browse/LANG-421 */ public void testEscapeJavaWithSlash() { final String input = "String with a slash (/) in it"; final String expected = input; final String actual = StringEscapeUtils.escapeJava(input); /** * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape * in a Java string. */ assertEquals(expected, actual); } private void assertEscapeJava(String escaped, String original) throws IOException { assertEscapeJava(null, escaped, original); } private void assertEscapeJava(String message, String expected, String original) throws IOException { String converted = StringEscapeUtils.escapeJava(original); message = "escapeJava(String) failed" + (message == null ? "" : (": " + message)); assertEquals(message, expected, converted); StringWriter writer = new StringWriter(); StringEscapeUtils.escapeJava(writer, original); assertEquals(expected, writer.toString()); } public void testUnescapeJava() throws IOException { assertEquals(null, StringEscapeUtils.unescapeJava(null)); try { StringEscapeUtils.unescapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava("\\u02-3"); fail(); } catch (RuntimeException ex) { } assertUnescapeJava("", ""); assertUnescapeJava("test", "test"); assertUnescapeJava("\ntest\b", "\\ntest\\b"); assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b"); assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r"); assertUnescapeJava("\\", "\\"); //foo assertUnescapeJava("lowercase unicode", "\uABCDx", "\\uabcdx"); assertUnescapeJava("uppercase unicode", "\uABCDx", "\\uABCDx"); assertUnescapeJava("unicode as final character", "\uABCD", "\\uabcd"); } private void assertUnescapeJava(String unescaped, String original) throws IOException { assertUnescapeJava(null, unescaped, original); } private void assertUnescapeJava(String message, String unescaped, String original) throws IOException { String expected = unescaped; String actual = StringEscapeUtils.unescapeJava(original); assertEquals("unescape(String) failed" + (message == null ? "" : (": " + message)) + ": expected '" + StringEscapeUtils.escapeJava(expected) + // we escape this so we can see it in the error message "' actual '" + StringEscapeUtils.escapeJava(actual) + "'", expected, actual); StringWriter writer = new StringWriter(); StringEscapeUtils.unescapeJava(writer, original); assertEquals(unescaped, writer.toString()); } public void testEscapeJavaScript() { assertEquals(null, StringEscapeUtils.escapeJavaScript(null)); try { StringEscapeUtils.escapeJavaScript(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJavaScript(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeJavaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';", StringEscapeUtils.escapeJavaScript("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';")); } // HTML and XML //-------------------------------------------------------------- String[][] htmlEscapes = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread &amp; butter", "bread & butter"}, {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, {"final character only", "greater than &gt;", "greater than >"}, {"first character only", "&lt; less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Fran&ccedil;ais,&#26085;&#26412;&#35486; (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii doesn't number-escape", "~\u007F", "\u007E\u007F"}, {"8-bit ascii does number-escape", "&#128;&#159;", "\u0080\u009F"}, }; public void testEscapeHtml() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][1]; String original = htmlEscapes[i][2]; assertEquals(message, expected, StringEscapeUtils.escapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.escapeHtml(sw, original); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } } public void testUnescapeHtml() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][2]; String original = htmlEscapes[i][1]; assertEquals(message, expected, StringEscapeUtils.unescapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.unescapeHtml(sw, original); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } // \u00E7 is a cedilla (c with wiggle under) // note that the test string must be 7-bit-clean (unicode escaped) or else it will compile incorrectly // on some locales assertEquals("funny chars pass through OK", "Fran\u00E7ais", StringEscapeUtils.unescapeHtml("Fran\u00E7ais")); assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml("Hello&;World")); assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml("Hello&#;World")); assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml("Hello&# ;World")); assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml("Hello&##;World")); } public void testUnescapeHexCharsHtml() { // Simple easy to grok test assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("&#x80;&#x9F;")); assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("&#X80;&#X9F;")); // Test all Character values: for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { Character c1 = new Character(i); Character c2 = new Character((char)(i+1)); String expected = c1.toString() + c2.toString(); String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";"; String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";"; assertEquals("hex number unescape index " + (int)i, expected, StringEscapeUtils.unescapeHtml(escapedC1 + escapedC2)); } } public void testUnescapeUnknownEntity() throws Exception { assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml("&zzzz;")); } public void testEscapeHtmlVersions() throws Exception { assertEquals("&Beta;", StringEscapeUtils.escapeHtml("\u0392")); assertEquals("\u0392", StringEscapeUtils.unescapeHtml("&Beta;")); //todo: refine API for escaping/unescaping specific HTML versions } public void testEscapeXml() throws Exception { assertEquals("&lt;abc&gt;", StringEscapeUtils.escapeXml("<abc>")); assertEquals("<abc>", StringEscapeUtils.unescapeXml("&lt;abc&gt;")); assertEquals("XML should use numbers, not names for HTML entities", "&#161;", StringEscapeUtils.escapeXml("\u00A1")); assertEquals("XML should use numbers, not names for HTML entities", "\u00A0", StringEscapeUtils.unescapeXml("&#160;")); assertEquals("ain't", StringEscapeUtils.unescapeXml("ain&apos;t")); assertEquals("ain&apos;t", StringEscapeUtils.escapeXml("ain't")); assertEquals("", StringEscapeUtils.escapeXml("")); assertEquals(null, StringEscapeUtils.escapeXml(null)); assertEquals(null, StringEscapeUtils.unescapeXml(null)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.escapeXml(sw, "<abc>"); } catch (IOException e) { } assertEquals("XML was escaped incorrectly", "&lt;abc&gt;", sw.toString() ); sw = new StringWriter(); try { StringEscapeUtils.unescapeXml(sw, "&lt;abc&gt;"); } catch (IOException e) { } assertEquals("XML was unescaped incorrectly", "<abc>", sw.toString() ); } // SQL // see http://www.jguru.com/faq/view.jsp?EID=8881 //-------------------- public void testEscapeSql() throws Exception { assertEquals("don''t stop", StringEscapeUtils.escapeSql("don't stop")); assertEquals("", StringEscapeUtils.escapeSql("")); assertEquals(null, StringEscapeUtils.escapeSql(null)); } // Tests issue #38569 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 public void testStandaloneAmphersand() { assertEquals("<P&O>", StringEscapeUtils.unescapeHtml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeHtml("test & &lt;")); assertEquals("<P&O>", StringEscapeUtils.unescapeXml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeXml("test & &lt;")); } public void testLang313() { assertEquals("& &", StringEscapeUtils.unescapeHtml("& &amp;")); } public void testEscapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar")); assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar")); assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar")); assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar")); assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar")); assertEquals("", StringEscapeUtils.escapeCsv("")); assertEquals(null, StringEscapeUtils.escapeCsv(null)); } public void testEscapeCsvWriter() throws Exception { checkCsvEscapeWriter("foo.bar", "foo.bar"); checkCsvEscapeWriter("\"foo,bar\"", "foo,bar"); checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar"); checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar"); checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar"); checkCsvEscapeWriter("", null); checkCsvEscapeWriter("", ""); } private void checkCsvEscapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.escapeCsv(writer, value); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } public void testUnescapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar")); assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\"")); assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\"")); assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\"")); assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\"")); assertEquals("", StringEscapeUtils.unescapeCsv("")); assertEquals(null, StringEscapeUtils.unescapeCsv(null)); assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\"")); } public void testUnescapeCsvWriter() throws Exception { checkCsvUnescapeWriter("foo.bar", "foo.bar"); checkCsvUnescapeWriter("foo,bar", "\"foo,bar\""); checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\""); checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\""); checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\""); checkCsvUnescapeWriter("", null); checkCsvUnescapeWriter("", ""); checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\""); } private void checkCsvUnescapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.unescapeCsv(writer, value); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } // https://issues.apache.org/jira/browse/LANG-480 public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { // this is the utf8 representation of the character: // COUNTING ROD UNIT DIGIT THREE // in unicode // codepoint: U+1D362 byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }; String escaped = StringEscapeUtils.escapeHtml( new String(data, "UTF8") ); String unescaped = StringEscapeUtils.unescapeHtml( escaped ); assertEquals( "High unicode was not escaped correctly", "&#119650;", escaped); } }
@Test(expected = IllegalArgumentException.class) public void testGetStringInconsistentRecord() { header.put("fourth", Integer.valueOf(4)); recordWithHeader.get("fourth"); }
org.apache.commons.csv.CSVRecordTest::testGetStringInconsistentRecord
src/test/java/org/apache/commons/csv/CSVRecordTest.java
69
src/test/java/org/apache/commons/csv/CSVRecordTest.java
testGetStringInconsistentRecord
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; public class CSVRecordTest { private String[] values; private CSVRecord record, recordWithHeader; private Map<String, Integer> header; @Before public void setUp() throws Exception { values = new String[] { "first", "second", "third" }; record = new CSVRecord(values, null, null, 0); header = new HashMap<String, Integer>(); header.put("first", Integer.valueOf(0)); header.put("second", Integer.valueOf(1)); header.put("third", Integer.valueOf(2)); recordWithHeader = new CSVRecord(values, header, null, 0); } @Test public void testGetInt() { assertEquals(values[0], record.get(0)); assertEquals(values[1], record.get(1)); assertEquals(values[2], record.get(2)); } @Test public void testGetString() { assertEquals(values[0], recordWithHeader.get("first")); assertEquals(values[1], recordWithHeader.get("second")); assertEquals(values[2], recordWithHeader.get("third")); } @Test(expected = IllegalStateException.class) public void testGetStringNoHeader() { record.get("first"); } @Test(expected = IllegalArgumentException.class) public void testGetStringInconsistentRecord() { header.put("fourth", Integer.valueOf(4)); recordWithHeader.get("fourth"); } @Test public void testIsConsistent() { assertTrue(record.isConsistent()); assertTrue(recordWithHeader.isConsistent()); header.put("fourth", Integer.valueOf(4)); assertFalse(recordWithHeader.isConsistent()); } @Test public void testIsMapped() { assertFalse(record.isMapped("first")); assertTrue(recordWithHeader.isMapped("first")); assertFalse(recordWithHeader.isMapped("fourth")); } @Test public void testIsSet() { assertFalse(record.isSet("first")); assertTrue(recordWithHeader.isSet("first")); assertFalse(recordWithHeader.isSet("fourth")); } @Test public void testIterator() { int i = 0; for (Iterator<String> itr = record.iterator(); itr.hasNext();) { String value = itr.next(); assertEquals(values[i], value); i++; } } }
// You are a professional Java test case writer, please create a test case named `testGetStringInconsistentRecord` for the issue `Csv-CSV-96`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-96 // // ## Issue-Title: // CSVRecord does not verify that the length of the header mapping matches the number of values // // ## Issue-Description: // // CSVRecord does not verify that the size of the header mapping matches the number of values. The following test will produce a ArrayOutOfBoundsException: // // // // // ``` // @Test // public void testInvalidHeaderTooLong() throws Exception { // final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").build()); // final CSVRecord record = parser.iterator().next(); // record.get("C"); // } // // ``` // // // // // @Test(expected = IllegalArgumentException.class) public void testGetStringInconsistentRecord() {
69
2
65
src/test/java/org/apache/commons/csv/CSVRecordTest.java
src/test/java
```markdown ## Issue-ID: Csv-CSV-96 ## Issue-Title: CSVRecord does not verify that the length of the header mapping matches the number of values ## Issue-Description: CSVRecord does not verify that the size of the header mapping matches the number of values. The following test will produce a ArrayOutOfBoundsException: ``` @Test public void testInvalidHeaderTooLong() throws Exception { final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").build()); final CSVRecord record = parser.iterator().next(); record.get("C"); } ``` ``` You are a professional Java test case writer, please create a test case named `testGetStringInconsistentRecord` for the issue `Csv-CSV-96`, utilizing the provided issue report information and the following function signature. ```java @Test(expected = IllegalArgumentException.class) public void testGetStringInconsistentRecord() { ```
65
[ "org.apache.commons.csv.CSVRecord" ]
0a2f6014ca50ba51e4edfca75d3e15e95f8108af79f28766048809a9bf6fd911
@Test(expected = IllegalArgumentException.class) public void testGetStringInconsistentRecord()
// You are a professional Java test case writer, please create a test case named `testGetStringInconsistentRecord` for the issue `Csv-CSV-96`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-96 // // ## Issue-Title: // CSVRecord does not verify that the length of the header mapping matches the number of values // // ## Issue-Description: // // CSVRecord does not verify that the size of the header mapping matches the number of values. The following test will produce a ArrayOutOfBoundsException: // // // // // ``` // @Test // public void testInvalidHeaderTooLong() throws Exception { // final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").build()); // final CSVRecord record = parser.iterator().next(); // record.get("C"); // } // // ``` // // // // //
Csv
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; public class CSVRecordTest { private String[] values; private CSVRecord record, recordWithHeader; private Map<String, Integer> header; @Before public void setUp() throws Exception { values = new String[] { "first", "second", "third" }; record = new CSVRecord(values, null, null, 0); header = new HashMap<String, Integer>(); header.put("first", Integer.valueOf(0)); header.put("second", Integer.valueOf(1)); header.put("third", Integer.valueOf(2)); recordWithHeader = new CSVRecord(values, header, null, 0); } @Test public void testGetInt() { assertEquals(values[0], record.get(0)); assertEquals(values[1], record.get(1)); assertEquals(values[2], record.get(2)); } @Test public void testGetString() { assertEquals(values[0], recordWithHeader.get("first")); assertEquals(values[1], recordWithHeader.get("second")); assertEquals(values[2], recordWithHeader.get("third")); } @Test(expected = IllegalStateException.class) public void testGetStringNoHeader() { record.get("first"); } @Test(expected = IllegalArgumentException.class) public void testGetStringInconsistentRecord() { header.put("fourth", Integer.valueOf(4)); recordWithHeader.get("fourth"); } @Test public void testIsConsistent() { assertTrue(record.isConsistent()); assertTrue(recordWithHeader.isConsistent()); header.put("fourth", Integer.valueOf(4)); assertFalse(recordWithHeader.isConsistent()); } @Test public void testIsMapped() { assertFalse(record.isMapped("first")); assertTrue(recordWithHeader.isMapped("first")); assertFalse(recordWithHeader.isMapped("fourth")); } @Test public void testIsSet() { assertFalse(record.isSet("first")); assertTrue(recordWithHeader.isSet("first")); assertFalse(recordWithHeader.isSet("fourth")); } @Test public void testIterator() { int i = 0; for (Iterator<String> itr = record.iterator(); itr.hasNext();) { String value = itr.next(); assertEquals(values[i], value); i++; } } }
public void testSymbolTableExpansionBytes() throws Exception { _testSymbolTableExpansion(true); }
com.fasterxml.jackson.core.sym.SymbolsViaParserTest::testSymbolTableExpansionBytes
src/test/java/com/fasterxml/jackson/core/sym/SymbolsViaParserTest.java
32
src/test/java/com/fasterxml/jackson/core/sym/SymbolsViaParserTest.java
testSymbolTableExpansionBytes
package com.fasterxml.jackson.core.sym; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.HashSet; import com.fasterxml.jackson.core.*; /** * Tests that use symbol table functionality through parser. */ public class SymbolsViaParserTest extends com.fasterxml.jackson.core.BaseTest { // for [jackson-core#213] public void test17CharSymbols() throws Exception { _test17Chars(false); } // for [jackson-core#213] public void test17ByteSymbols() throws Exception { _test17Chars(true); } // for [jackson-core#216] public void testSymbolTableExpansionChars() throws Exception { _testSymbolTableExpansion(false); } // for [jackson-core#216] public void testSymbolTableExpansionBytes() throws Exception { _testSymbolTableExpansion(true); } /* /********************************************************** /* Secondary test methods /********************************************************** */ private void _test17Chars(boolean useBytes) throws IOException { String doc = _createDoc17(); JsonFactory f = new JsonFactory(); JsonParser p = useBytes ? f.createParser(doc.getBytes("UTF-8")) : f.createParser(doc); HashSet<String> syms = new HashSet<String>(); assertToken(JsonToken.START_OBJECT, p.nextToken()); for (int i = 0; i < 50; ++i) { assertToken(JsonToken.FIELD_NAME, p.nextToken()); syms.add(p.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); } assertToken(JsonToken.END_OBJECT, p.nextToken()); assertEquals(50, syms.size()); p.close(); } private String _createDoc17() { StringBuilder sb = new StringBuilder(1000); sb.append("{\n"); for (int i = 1; i <= 50; ++i) { if (i > 1) { sb.append(",\n"); } sb.append("\"lengthmatters") .append(1000 + i) .append("\": true"); } sb.append("\n}"); return sb.toString(); } public void _testSymbolTableExpansion(boolean useBytes) throws Exception { JsonFactory jsonFactory = new JsonFactory(); // Important: must create separate documents to gradually build up symbol table for (int i = 0; i < 200; i++) { String field = Integer.toString(i); final String doc = "{ \"" + field + "\" : \"test\" }"; JsonParser parser = useBytes ? jsonFactory.createParser(doc.getBytes("UTF-8")) : jsonFactory.createParser(doc); assertToken(JsonToken.START_OBJECT, parser.nextToken()); assertToken(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals(field, parser.getCurrentName()); assertToken(JsonToken.VALUE_STRING, parser.nextToken()); assertToken(JsonToken.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); parser.close(); } } }
// You are a professional Java test case writer, please create a test case named `testSymbolTableExpansionBytes` for the issue `JacksonCore-216`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-216 // // ## Issue-Title: // ArrayIndexOutOfBoundsException: 128 when repeatedly serializing to a byte array // // ## Issue-Description: // // ``` // java.lang.ArrayIndexOutOfBoundsException: 128 // at com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer.addName(ByteQuadsCanonicalizer.java:853) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.addName(UTF8StreamJsonParser.java:2340) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.findName(UTF8StreamJsonParser.java:2224) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseLongName(UTF8StreamJsonParser.java:1831) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseMediumName2(UTF8StreamJsonParser.java:1786) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseMediumName(UTF8StreamJsonParser.java:1743) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._parseName(UTF8StreamJsonParser.java:1678) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextFieldName(UTF8StreamJsonParser.java:1007) // at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:471) // at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:341) // at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26) // at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702) // at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2824) // at com.kryptnostic.services.v1.SmokeTests.spamAddIndexPair(SmokeTests.java:605) // at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) // at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) // at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) // at java.lang.reflect.Method.invoke(Method.java:497) // at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) // at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) // at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) // at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) // at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) // at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) // at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) // at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) // at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) // at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63 public void testSymbolTableExpansionBytes() throws Exception {
32
// for [jackson-core#216]
11
30
src/test/java/com/fasterxml/jackson/core/sym/SymbolsViaParserTest.java
src/test/java
```markdown ## Issue-ID: JacksonCore-216 ## Issue-Title: ArrayIndexOutOfBoundsException: 128 when repeatedly serializing to a byte array ## Issue-Description: ``` java.lang.ArrayIndexOutOfBoundsException: 128 at com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer.addName(ByteQuadsCanonicalizer.java:853) at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.addName(UTF8StreamJsonParser.java:2340) at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.findName(UTF8StreamJsonParser.java:2224) at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseLongName(UTF8StreamJsonParser.java:1831) at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseMediumName2(UTF8StreamJsonParser.java:1786) at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseMediumName(UTF8StreamJsonParser.java:1743) at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._parseName(UTF8StreamJsonParser.java:1678) at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextFieldName(UTF8StreamJsonParser.java:1007) at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:471) at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:341) at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2824) at com.kryptnostic.services.v1.SmokeTests.spamAddIndexPair(SmokeTests.java:605) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63 ``` You are a professional Java test case writer, please create a test case named `testSymbolTableExpansionBytes` for the issue `JacksonCore-216`, utilizing the provided issue report information and the following function signature. ```java public void testSymbolTableExpansionBytes() throws Exception { ```
30
[ "com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer" ]
0a65e0609f40f9f4ca3a294cb7a25a7f8be29dea86533bc5633d37a768f6352f
public void testSymbolTableExpansionBytes() throws Exception
// You are a professional Java test case writer, please create a test case named `testSymbolTableExpansionBytes` for the issue `JacksonCore-216`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-216 // // ## Issue-Title: // ArrayIndexOutOfBoundsException: 128 when repeatedly serializing to a byte array // // ## Issue-Description: // // ``` // java.lang.ArrayIndexOutOfBoundsException: 128 // at com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer.addName(ByteQuadsCanonicalizer.java:853) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.addName(UTF8StreamJsonParser.java:2340) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.findName(UTF8StreamJsonParser.java:2224) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseLongName(UTF8StreamJsonParser.java:1831) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseMediumName2(UTF8StreamJsonParser.java:1786) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.parseMediumName(UTF8StreamJsonParser.java:1743) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._parseName(UTF8StreamJsonParser.java:1678) // at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextFieldName(UTF8StreamJsonParser.java:1007) // at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:471) // at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:341) // at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26) // at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702) // at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2824) // at com.kryptnostic.services.v1.SmokeTests.spamAddIndexPair(SmokeTests.java:605) // at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) // at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) // at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) // at java.lang.reflect.Method.invoke(Method.java:497) // at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) // at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) // at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) // at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) // at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) // at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) // at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) // at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) // at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) // at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63
JacksonCore
package com.fasterxml.jackson.core.sym; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.HashSet; import com.fasterxml.jackson.core.*; /** * Tests that use symbol table functionality through parser. */ public class SymbolsViaParserTest extends com.fasterxml.jackson.core.BaseTest { // for [jackson-core#213] public void test17CharSymbols() throws Exception { _test17Chars(false); } // for [jackson-core#213] public void test17ByteSymbols() throws Exception { _test17Chars(true); } // for [jackson-core#216] public void testSymbolTableExpansionChars() throws Exception { _testSymbolTableExpansion(false); } // for [jackson-core#216] public void testSymbolTableExpansionBytes() throws Exception { _testSymbolTableExpansion(true); } /* /********************************************************** /* Secondary test methods /********************************************************** */ private void _test17Chars(boolean useBytes) throws IOException { String doc = _createDoc17(); JsonFactory f = new JsonFactory(); JsonParser p = useBytes ? f.createParser(doc.getBytes("UTF-8")) : f.createParser(doc); HashSet<String> syms = new HashSet<String>(); assertToken(JsonToken.START_OBJECT, p.nextToken()); for (int i = 0; i < 50; ++i) { assertToken(JsonToken.FIELD_NAME, p.nextToken()); syms.add(p.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); } assertToken(JsonToken.END_OBJECT, p.nextToken()); assertEquals(50, syms.size()); p.close(); } private String _createDoc17() { StringBuilder sb = new StringBuilder(1000); sb.append("{\n"); for (int i = 1; i <= 50; ++i) { if (i > 1) { sb.append(",\n"); } sb.append("\"lengthmatters") .append(1000 + i) .append("\": true"); } sb.append("\n}"); return sb.toString(); } public void _testSymbolTableExpansion(boolean useBytes) throws Exception { JsonFactory jsonFactory = new JsonFactory(); // Important: must create separate documents to gradually build up symbol table for (int i = 0; i < 200; i++) { String field = Integer.toString(i); final String doc = "{ \"" + field + "\" : \"test\" }"; JsonParser parser = useBytes ? jsonFactory.createParser(doc.getBytes("UTF-8")) : jsonFactory.createParser(doc); assertToken(JsonToken.START_OBJECT, parser.nextToken()); assertToken(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals(field, parser.getCurrentName()); assertToken(JsonToken.VALUE_STRING, parser.nextToken()); assertToken(JsonToken.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); parser.close(); } } }
public void testIssue925() { test( "if (x[--y] === 1) {\n" + " x[y] = 0;\n" + "} else {\n" + " x[y] = 1;\n" + "}", "(x[--y] === 1) ? x[y] = 0 : x[y] = 1;"); test( "if (x[--y]) {\n" + " a = 0;\n" + "} else {\n" + " a = 1;\n" + "}", "a = (x[--y]) ? 0 : 1;"); test("if (x++) { x += 2 } else { x += 3 }", "x++ ? x += 2 : x += 3"); test("if (x++) { x = x + 2 } else { x = x + 3 }", "x = x++ ? x + 2 : x + 3"); }
com.google.javascript.jscomp.PeepholeSubstituteAlternateSyntaxTest::testIssue925
test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java
987
test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java
testIssue925
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Tests for {@link PeepholeSubstituteAlternateSyntax} in isolation. * Tests for the interaction of multiple peephole passes are in * PeepholeIntegrationTest. */ public class PeepholeSubstituteAlternateSyntaxTest extends CompilerTestCase { // Externs for built-in constructors // Needed for testFoldLiteralObjectConstructors(), // testFoldLiteralArrayConstructors() and testFoldRegExp...() private static final String FOLD_CONSTANTS_TEST_EXTERNS = "var Object = function f(){};\n" + "var RegExp = function f(a){};\n" + "var Array = function f(a){};\n"; private boolean late = true; // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeSubstituteAlternateSyntaxTest(boolean compareAsTree) { super(FOLD_CONSTANTS_TEST_EXTERNS, compareAsTree); } public PeepholeSubstituteAlternateSyntaxTest() { super(FOLD_CONSTANTS_TEST_EXTERNS); } @Override public void setUp() throws Exception { late = true; super.setUp(); enableLineNumberCheck(true); disableNormalize(); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeSubstituteAlternateSyntax(late)) .setRetraverseOnChange(false); return peepholePass; } @Override protected int getNumRepetitions() { return 1; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } void assertResultString(String js, String expected) { assertResultString(js, expected, false); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. void assertResultString(String js, String expected, boolean normalize) { PeepholeSubstituteAlternateSyntaxTest scTest = new PeepholeSubstituteAlternateSyntaxTest(false); if (normalize) { scTest.enableNormalize(); } else { scTest.disableNormalize(); } scTest.test(js, expected); } /** Check that removing blocks with 1 child works */ public void testFoldOneChildBlocks() { late = false; fold("function f(){if(x)a();x=3}", "function f(){x&&a();x=3}"); fold("function f(){if(x){a()}x=3}", "function f(){x&&a();x=3}"); fold("function f(){if(x){return 3}}", "function f(){if(x)return 3}"); fold("function f(){if(x){a()}}", "function f(){x&&a()}"); fold("function f(){if(x){throw 1}}", "function f(){if(x)throw 1;}"); // Try it out with functions fold("function f(){if(x){foo()}}", "function f(){x&&foo()}"); fold("function f(){if(x){foo()}else{bar()}}", "function f(){x?foo():bar()}"); // Try it out with properties and methods fold("function f(){if(x){a.b=1}}", "function f(){if(x)a.b=1}"); fold("function f(){if(x){a.b*=1}}", "function f(){x&&(a.b*=1)}"); fold("function f(){if(x){a.b+=1}}", "function f(){x&&(a.b+=1)}"); fold("function f(){if(x){++a.b}}", "function f(){x&&++a.b}"); fold("function f(){if(x){a.foo()}}", "function f(){x&&a.foo()}"); // Try it out with throw/catch/finally [which should not change] fold("function f(){try{foo()}catch(e){bar(e)}finally{baz()}}", "function f(){try{foo()}catch(e){bar(e)}finally{baz()}}"); // Try it out with switch statements fold("function f(){switch(x){case 1:break}}", "function f(){switch(x){case 1:break}}"); // Do while loops stay in a block if that's where they started fold("function f(){if(e1){do foo();while(e2)}else foo2()}", "function f(){if(e1){do foo();while(e2)}else foo2()}"); // Test an obscure case with do and while fold("if(x){do{foo()}while(y)}else bar()", "if(x){do foo();while(y)}else bar()"); // Play with nested IFs fold("function f(){if(x){if(y)foo()}}", "function f(){x&&y&&foo()}"); fold("function f(){if(x){if(y)foo();else bar()}}", "function f(){x&&(y?foo():bar())}"); fold("function f(){if(x){if(y)foo()}else bar()}", "function f(){x?y&&foo():bar()}"); fold("function f(){if(x){if(y)foo();else bar()}else{baz()}}", "function f(){x?y?foo():bar():baz()}"); fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}", "if(e1)while(e2)e3&&foo();else bar()"); fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}", "if(e1)with(e2)e3&&foo();else bar()"); fold("if(a||b){if(c||d){var x;}}", "if(a||b)if(c||d)var x"); fold("if(x){ if(y){var x;}else{var z;} }", "if(x)if(y)var x;else var z"); // NOTE - technically we can remove the blocks since both the parent // and child have elses. But we don't since it causes ambiguities in // some cases where not all descendent ifs having elses fold("if(x){ if(y){var x;}else{var z;} }else{var w}", "if(x)if(y)var x;else var z;else var w"); fold("if (x) {var x;}else { if (y) { var y;} }", "if(x)var x;else if(y)var y"); // Here's some of the ambiguous cases fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}", "if(a)if(b){f1();f2()}else c&&f3();else d&&f4()"); fold("function f(){foo()}", "function f(){foo()}"); fold("switch(x){case y: foo()}", "switch(x){case y:foo()}"); fold("try{foo()}catch(ex){bar()}finally{baz()}", "try{foo()}catch(ex){bar()}finally{baz()}"); } /** Try to minimize returns */ public void testFoldReturns() { fold("function f(){if(x)return 1;else return 2}", "function f(){return x?1:2}"); fold("function f(){if(x)return 1;return 2}", "function f(){return x?1:2}"); fold("function f(){if(x)return;return 2}", "function f(){return x?void 0:2}"); fold("function f(){if(x)return 1+x;else return 2-x}", "function f(){return x?1+x:2-x}"); fold("function f(){if(x)return 1+x;return 2-x}", "function f(){return x?1+x:2-x}"); fold("function f(){if(x)return y += 1;else return y += 2}", "function f(){return x?(y+=1):(y+=2)}"); fold("function f(){if(x)return;else return 2-x}", "function f(){if(x);else return 2-x}"); fold("function f(){if(x)return;return 2-x}", "function f(){return x?void 0:2-x}"); fold("function f(){if(x)return x;else return}", "function f(){if(x)return x;{}}"); fold("function f(){if(x)return x;return}", "function f(){if(x)return x}"); foldSame("function f(){for(var x in y) { return x.y; } return k}"); } public void testCombineIfs1() { fold("function f() {if (x) return 1; if (y) return 1}", "function f() {if (x||y) return 1;}"); fold("function f() {if (x) return 1; if (y) foo(); else return 1}", "function f() {if ((!x)&&y) foo(); else return 1;}"); } public void testCombineIfs2() { // combinable but not yet done foldSame("function f() {if (x) throw 1; if (y) throw 1}"); // Can't combine, side-effect fold("function f(){ if (x) g(); if (y) g() }", "function f(){ x&&g(); y&&g() }"); // Can't combine, side-effect fold("function f(){ if (x) y = 0; if (y) y = 0; }", "function f(){ x&&(y = 0); y&&(y = 0); }"); } public void testCombineIfs3() { foldSame("function f() {if (x) return 1; if (y) {g();f()}}"); } /** Try to minimize assignments */ public void testFoldAssignments() { fold("function f(){if(x)y=3;else y=4;}", "function f(){y=x?3:4}"); fold("function f(){if(x)y=1+a;else y=2+a;}", "function f(){y=x?1+a:2+a}"); // and operation assignments fold("function f(){if(x)y+=1;else y+=2;}", "function f(){y+=x?1:2}"); fold("function f(){if(x)y-=1;else y-=2;}", "function f(){y-=x?1:2}"); fold("function f(){if(x)y%=1;else y%=2;}", "function f(){y%=x?1:2}"); fold("function f(){if(x)y|=1;else y|=2;}", "function f(){y|=x?1:2}"); // sanity check, don't fold if the 2 ops don't match foldSame("function f(){x ? y-=1 : y+=2}"); // sanity check, don't fold if the 2 LHS don't match foldSame("function f(){x ? y-=1 : z-=1}"); // sanity check, don't fold if there are potential effects foldSame("function f(){x ? y().a=3 : y().a=4}"); } public void testRemoveDuplicateStatements() { fold("if (a) { x = 1; x++ } else { x = 2; x++ }", "x=(a) ? 1 : 2; x++"); fold("if (a) { x = 1; x++; y += 1; z = pi; }" + " else { x = 2; x++; y += 1; z = pi; }", "x=(a) ? 1 : 2; x++; y += 1; z = pi;"); fold("function z() {" + "if (a) { foo(); return !0 } else { goo(); return !0 }" + "}", "function z() {(a) ? foo() : goo(); return !0}"); fold("function z() {if (a) { foo(); x = true; return true " + "} else { goo(); x = true; return true }}", "function z() {(a) ? foo() : goo(); x = !0; return !0}"); fold("function z() {" + " if (a) { bar(); foo(); return true }" + " else { bar(); goo(); return true }" + "}", "function z() {" + " if (a) { bar(); foo(); }" + " else { bar(); goo(); }" + " return !0;" + "}"); } public void testNotCond() { fold("function f(){if(!x)foo()}", "function f(){x||foo()}"); fold("function f(){if(!x)b=1}", "function f(){x||(b=1)}"); fold("if(!x)z=1;else if(y)z=2", "if(x){y&&(z=2);}else{z=1;}"); fold("if(x)y&&(z=2);else z=1;", "x ? y&&(z=2) : z=1"); foldSame("function f(){if(!(x=1))a.b=1}"); } public void testAndParenthesesCount() { fold("function f(){if(x||y)a.foo()}", "function f(){(x||y)&&a.foo()}"); fold("function f(){if(x.a)x.a=0}", "function f(){x.a&&(x.a=0)}"); foldSame("function f(){if(x()||y()){x()||y()}}"); } public void testFoldLogicalOpStringCompare() { // side-effects // There is two way to parse two &&'s and both are correct. assertResultString("if(foo() && false) z()", "foo()&&0&&z()"); } public void testFoldNot() { fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}"); fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}"); fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}"); fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}"); // Because !(x<NaN) != x>=NaN don't fold < and > cases. foldSame("while(!(x>y)){a=b;}"); foldSame("while(!(x>=y)){a=b;}"); foldSame("while(!(x<y)){a=b;}"); foldSame("while(!(x<=y)){a=b;}"); foldSame("while(!(x<=NaN)){a=b;}"); // NOT forces a boolean context fold("x = !(y() && true)", "x = !y()"); // This will be further optimized by PeepholeFoldConstants. fold("x = !true", "x = !1"); } public void testFoldRegExpConstructor() { enableNormalize(); // Cannot fold all the way to a literal because there are too few arguments. fold("x = new RegExp", "x = RegExp()"); // Empty regexp should not fold to // since that is a line comment in JS fold("x = new RegExp(\"\")", "x = RegExp(\"\")"); fold("x = new RegExp(\"\", \"i\")", "x = RegExp(\"\",\"i\")"); // Bogus flags should not fold testSame("x = RegExp(\"foobar\", \"bogus\")", PeepholeSubstituteAlternateSyntax.INVALID_REGULAR_EXPRESSION_FLAGS); // Can Fold fold("x = new RegExp(\"foobar\")", "x = /foobar/"); fold("x = RegExp(\"foobar\")", "x = /foobar/"); fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i"); // Make sure that escaping works fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i"); fold("x = new RegExp(\"/\", \"\")", "x = /\\//"); fold("x = new RegExp(\"[/]\", \"\")", "x = /[/]/"); fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//"); fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//"); fold("x = new RegExp(\"\\n\")", "x = /\\n/"); fold("x = new RegExp('\\\\\\r')", "x = /\\r/"); // Don't fold really long regexp literals, because Opera 9.2's // regexp parser will explode. String longRegexp = ""; for (int i = 0; i < 200; i++) longRegexp += "x"; foldSame("x = RegExp(\"" + longRegexp + "\")"); // Shouldn't fold RegExp unnormalized because // we can't be sure that RegExp hasn't been redefined disableNormalize(); foldSame("x = new RegExp(\"foobar\")"); } public void testVersionSpecificRegExpQuirks() { enableNormalize(); // Don't fold if the flags contain 'g' enableEcmaScript5(false); fold("x = new RegExp(\"foobar\", \"g\")", "x = RegExp(\"foobar\",\"g\")"); fold("x = new RegExp(\"foobar\", \"ig\")", "x = RegExp(\"foobar\",\"ig\")"); // ... unless in ECMAScript 5 mode per section 7.8.5 of ECMAScript 5. enableEcmaScript5(true); fold("x = new RegExp(\"foobar\", \"ig\")", "x = /foobar/ig"); // Don't fold things that crash older versions of Safari and that don't work // as regex literals on other old versions of Safari enableEcmaScript5(false); fold("x = new RegExp(\"\\u2028\")", "x = RegExp(\"\\u2028\")"); fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/"); // Sunset Safari exclusions for ECMAScript 5 and later. enableEcmaScript5(true); fold("x = new RegExp(\"\\u2028\\u2029\")", "x = /\\u2028\\u2029/"); fold("x = new RegExp(\"\\\\u2028\")", "x = /\\u2028/"); fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/"); } public void testFoldRegExpConstructorStringCompare() { // Might have something to do with the internal representation of \n and how // it is used in node comparison. assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i", true); } public void testContainsUnicodeEscape() throws Exception { assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("")); assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo")); assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape( "\u2028")); assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape( "\\u2028")); assertTrue( PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo\\u2028")); assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape( "foo\\\\u2028")); assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape( "foo\\\\u2028bar\\u2028")); } public void testFoldLiteralObjectConstructors() { enableNormalize(); // Can fold when normalized fold("x = new Object", "x = ({})"); fold("x = new Object()", "x = ({})"); fold("x = Object()", "x = ({})"); disableNormalize(); // Cannot fold above when not normalized foldSame("x = new Object"); foldSame("x = new Object()"); foldSame("x = Object()"); enableNormalize(); // Cannot fold, the constructor being used is actually a local function foldSame("x = " + "(function f(){function Object(){this.x=4};return new Object();})();"); } public void testFoldLiteralArrayConstructors() { enableNormalize(); // No arguments - can fold when normalized fold("x = new Array", "x = []"); fold("x = new Array()", "x = []"); fold("x = Array()", "x = []"); // One argument - can be fold when normalized fold("x = new Array(0)", "x = []"); fold("x = Array(0)", "x = []"); fold("x = new Array(\"a\")", "x = [\"a\"]"); fold("x = Array(\"a\")", "x = [\"a\"]"); // One argument - cannot be fold when normalized fold("x = new Array(7)", "x = Array(7)"); fold("x = Array(7)", "x = Array(7)"); fold("x = new Array(y)", "x = Array(y)"); fold("x = Array(y)", "x = Array(y)"); fold("x = new Array(foo())", "x = Array(foo())"); fold("x = Array(foo())", "x = Array(foo())"); // More than one argument - can be fold when normalized fold("x = new Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]"); fold("x = Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]"); fold("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')", "x = ['a', 1, 2, 'bc', 3, {}, 'abc']"); fold("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')", "x = ['a', 1, 2, 'bc', 3, {}, 'abc']"); fold("x = new Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]"); fold("x = Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]"); fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))", "x = [{}, [\"abc\", {}, [[]]]]"); fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))", "x = [{}, [\"abc\", {}, [[]]]]"); disableNormalize(); // Cannot fold above when not normalized foldSame("x = new Array"); foldSame("x = new Array()"); foldSame("x = Array()"); foldSame("x = new Array(0)"); foldSame("x = Array(0)"); foldSame("x = new Array(\"a\")"); foldSame("x = Array(\"a\")"); foldSame("x = new Array(7)"); foldSame("x = Array(7)"); foldSame("x = new Array(foo())"); foldSame("x = Array(foo())"); foldSame("x = new Array(1, 2, 3, 4)"); foldSame("x = Array(1, 2, 3, 4)"); foldSame("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')"); foldSame("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')"); foldSame("x = new Array(Array(1, '2', 3, '4'))"); foldSame("x = Array(Array(1, '2', 3, '4'))"); foldSame("x = new Array(" + "Object(), Array(\"abc\", Object(), Array(Array())))"); foldSame("x = new Array(" + "Object(), Array(\"abc\", Object(), Array(Array())))"); } public void testMinimizeExprCondition() { fold("(x ? true : false) && y()", "x&&y()"); fold("(x ? false : true) && y()", "(!x)&&y()"); fold("(x ? true : y) && y()", "(x || y)&&y()"); fold("(x ? y : false) && y()", "(x && y)&&y()"); fold("(x && true) && y()", "x && y()"); fold("(x && false) && y()", "0&&y()"); fold("(x || true) && y()", "1&&y()"); fold("(x || false) && y()", "x&&y()"); } public void testMinimizeWhileCondition() { // This test uses constant folding logic, so is only here for completeness. fold("while(!!true) foo()", "while(1) foo()"); // These test tryMinimizeCondition fold("while(!!x) foo()", "while(x) foo()"); fold("while(!(!x&&!y)) foo()", "while(x||y) foo()"); fold("while(x||!!y) foo()", "while(x||y) foo()"); fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()"); fold("while(!(!x&&y)) foo()", "while(x||!y) foo()"); fold("while(!(x||!y)) foo()", "while(!x&&y) foo()"); fold("while(!(x||y)) foo()", "while(!x&&!y) foo()"); fold("while(!(!x||y-z)) foo()", "while(x&&!(y-z)) foo()"); fold("while(!(!(x/y)||z+w)) foo()", "while(x/y&&!(z+w)) foo()"); foldSame("while(!(x+y||z)) foo()"); foldSame("while(!(x&&y*z)) foo()"); fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()"); fold("while(x&&!0) foo()", "while(x) foo()"); fold("while(x||!1) foo()", "while(x) foo()"); fold("while(!((x,y)&&z)) foo()", "while(!(x,y)||!z) foo()"); } public void testMinimizeForCondition() { // This test uses constant folding logic, so is only here for completeness. // These could be simplified to "for(;;) ..." fold("for(;!!true;) foo()", "for(;1;) foo()"); // Don't bother with FOR inits as there are normalized out. fold("for(!!true;;) foo()", "for(!0;;) foo()"); // These test tryMinimizeCondition fold("for(;!!x;) foo()", "for(;x;) foo()"); // sanity check foldSame("for(a in b) foo()"); foldSame("for(a in {}) foo()"); foldSame("for(a in []) foo()"); fold("for(a in !!true) foo()", "for(a in !0) foo()"); } public void testMinimizeCondition_example1() { // Based on a real failing code sample. fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}"); } public void testFoldLoopBreakLate() { late = true; fold("for(;;) if (a) break", "for(;!a;);"); foldSame("for(;;) if (a) { f(); break }"); fold("for(;;) if (a) break; else f()", "for(;!a;) { { f(); } }"); fold("for(;a;) if (b) break", "for(;a && !b;);"); fold("for(;a;) { if (b) break; if (c) break; }", "for(;(a && !b);) if (c) break;"); fold("for(;(a && !b);) if (c) break;", "for(;(a && !b) && !c;);"); // 'while' is normalized to 'for' enableNormalize(true); fold("while(true) if (a) break", "for(;1&&!a;);"); } public void testFoldLoopBreakEarly() { late = false; foldSame("for(;;) if (a) break"); foldSame("for(;;) if (a) { f(); break }"); foldSame("for(;;) if (a) break; else f()"); foldSame("for(;a;) if (b) break"); foldSame("for(;a;) { if (b) break; if (c) break; }"); foldSame("while(1) if (a) break"); enableNormalize(true); foldSame("while(1) if (a) break"); } public void testFoldConditionalVarDeclaration() { fold("if(x) var y=1;else y=2", "var y=x?1:2"); fold("if(x) y=1;else var y=2", "var y=x?1:2"); foldSame("if(x) var y = 1; z = 2"); foldSame("if(x||y) y = 1; var z = 2"); foldSame("if(x) { var y = 1; print(y)} else y = 2 "); foldSame("if(x) var y = 1; else {y = 2; print(y)}"); } public void testFoldReturnResult() { fold("function f(){return false;}", "function f(){return !1}"); foldSame("function f(){return null;}"); fold("function f(){return void 0;}", "function f(){return}"); fold("function f(){return;}", "function f(){}"); foldSame("function f(){return void foo();}"); fold("function f(){return undefined;}", "function f(){return}"); fold("function f(){if(a()){return undefined;}}", "function f(){if(a()){return}}"); } public void testFoldStandardConstructors() { foldSame("new Foo('a')"); foldSame("var x = new goog.Foo(1)"); foldSame("var x = new String(1)"); foldSame("var x = new Number(1)"); foldSame("var x = new Boolean(1)"); enableNormalize(); fold("var x = new Object('a')", "var x = Object('a')"); fold("var x = new RegExp('')", "var x = RegExp('')"); fold("var x = new Error('20')", "var x = Error(\"20\")"); fold("var x = new Array(20)", "var x = Array(20)"); } public void testSubsituteReturn() { fold("function f() { while(x) { return }}", "function f() { while(x) { break }}"); foldSame("function f() { while(x) { return 5 } }"); foldSame("function f() { a: { return 5 } }"); fold("function f() { while(x) { return 5} return 5}", "function f() { while(x) { break } return 5}"); fold("function f() { while(x) { return x} return x}", "function f() { while(x) { break } return x}"); fold("function f() { while(x) { if (y) { return }}}", "function f() { while(x) { if (y) { break }}}"); fold("function f() { while(x) { if (y) { return }} return}", "function f() { while(x) { if (y) { break }}}"); fold("function f() { while(x) { if (y) { return 5 }} return 5}", "function f() { while(x) { if (y) { break }} return 5}"); // It doesn't matter if x is changed between them. We are still returning // x at whatever x value current holds. The whole x = 1 is skipped. fold("function f() { while(x) { if (y) { return x } x = 1} return x}", "function f() { while(x) { if (y) { break } x = 1} return x}"); // RemoveUnreachableCode would take care of the useless breaks. fold("function f() { while(x) { if (y) { return x } return x} return x}", "function f() { while(x) { if (y) {} break }return x}"); // A break here only breaks out of the inner loop. foldSame("function f() { while(x) { while (y) { return } } }"); foldSame("function f() { while(1) { return 7} return 5}"); foldSame("function f() {" + " try { while(x) {return f()}} catch (e) { } return f()}"); foldSame("function f() {" + " try { while(x) {return f()}} finally {alert(1)} return f()}"); // Both returns has the same handler fold("function f() {" + " try { while(x) { return f() } return f() } catch (e) { } }", "function f() {" + " try { while(x) { break } return f() } catch (e) { } }"); // We can't fold this because it'll change the order of when foo is called. foldSame("function f() {" + " try { while(x) { return foo() } } finally { alert(1) } " + " return foo()}"); // This is fine, we have no side effect in the return value. fold("function f() {" + " try { while(x) { return 1 } } finally { alert(1) } return 1}", "function f() {" + " try { while(x) { break } } finally { alert(1) } return 1}" ); foldSame("function f() { try{ return a } finally { a = 2 } return a; }"); fold( "function f() { switch(a){ case 1: return a; default: g();} return a;}", "function f() { switch(a){ case 1: break; default: g();} return a; }"); } public void testSubsituteBreakForThrow() { foldSame("function f() { while(x) { throw Error }}"); fold("function f() { while(x) { throw Error } throw Error }", "function f() { while(x) { break } throw Error}"); foldSame("function f() { while(x) { throw Error(1) } throw Error(2)}"); foldSame("function f() { while(x) { throw Error(1) } return Error(2)}"); foldSame("function f() { while(x) { throw 5 } }"); foldSame("function f() { a: { throw 5 } }"); fold("function f() { while(x) { throw 5} throw 5}", "function f() { while(x) { break } throw 5}"); fold("function f() { while(x) { throw x} throw x}", "function f() { while(x) { break } throw x}"); foldSame("function f() { while(x) { if (y) { throw Error }}}"); fold("function f() { while(x) { if (y) { throw Error }} throw Error}", "function f() { while(x) { if (y) { break }} throw Error}"); fold("function f() { while(x) { if (y) { throw 5 }} throw 5}", "function f() { while(x) { if (y) { break }} throw 5}"); // It doesn't matter if x is changed between them. We are still throwing // x at whatever x value current holds. The whole x = 1 is skipped. fold("function f() { while(x) { if (y) { throw x } x = 1} throw x}", "function f() { while(x) { if (y) { break } x = 1} throw x}"); // RemoveUnreachableCode would take care of the useless breaks. fold("function f() { while(x) { if (y) { throw x } throw x} throw x}", "function f() { while(x) { if (y) {} break }throw x}"); // A break here only breaks out of the inner loop. foldSame("function f() { while(x) { while (y) { throw Error } } }"); foldSame("function f() { while(1) { throw 7} throw 5}"); foldSame("function f() {" + " try { while(x) {throw f()}} catch (e) { } throw f()}"); foldSame("function f() {" + " try { while(x) {throw f()}} finally {alert(1)} throw f()}"); // Both throws has the same handler fold("function f() {" + " try { while(x) { throw f() } throw f() } catch (e) { } }", "function f() {" + " try { while(x) { break } throw f() } catch (e) { } }"); // We can't fold this because it'll change the order of when foo is called. foldSame("function f() {" + " try { while(x) { throw foo() } } finally { alert(1) } " + " throw foo()}"); // This is fine, we have no side effect in the throw value. fold("function f() {" + " try { while(x) { throw 1 } } finally { alert(1) } throw 1}", "function f() {" + " try { while(x) { break } } finally { alert(1) } throw 1}" ); foldSame("function f() { try{ throw a } finally { a = 2 } throw a; }"); fold( "function f() { switch(a){ case 1: throw a; default: g();} throw a;}", "function f() { switch(a){ case 1: break; default: g();} throw a; }"); } public void testRemoveDuplicateReturn() { fold("function f() { return; }", "function f(){}"); foldSame("function f() { return a; }"); fold("function f() { if (x) { return a } return a; }", "function f() { if (x) {} return a; }"); foldSame( "function f() { try { if (x) { return a } } catch(e) {} return a; }"); foldSame( "function f() { try { if (x) {} } catch(e) {} return 1; }"); // finally clauses may have side effects foldSame( "function f() { try { if (x) { return a } } finally { a++ } return a; }"); // but they don't matter if the result doesn't have side effects and can't // be affect by side-effects. fold("function f() { try { if (x) { return 1 } } finally {} return 1; }", "function f() { try { if (x) {} } finally {} return 1; }"); fold("function f() { switch(a){ case 1: return a; } return a; }", "function f() { switch(a){ case 1: } return a; }"); fold("function f() { switch(a){ " + " case 1: return a; case 2: return a; } return a; }", "function f() { switch(a){ " + " case 1: break; case 2: } return a; }"); } public void testRemoveDuplicateThrow() { foldSame("function f() { throw a; }"); fold("function f() { if (x) { throw a } throw a; }", "function f() { if (x) {} throw a; }"); foldSame( "function f() { try { if (x) {throw a} } catch(e) {} throw a; }"); foldSame( "function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }"); foldSame( "function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }"); foldSame( "function f() { try { if (x) {throw 1} } catch(e) {throw 1}}"); fold( "function f() { try { if (x) {throw 1} } catch(e) {throw 1} throw 1; }", "function f() { try { if (x) {throw 1} } catch(e) {} throw 1; }"); // finally clauses may have side effects foldSame( "function f() { try { if (x) { throw a } } finally { a++ } throw a; }"); // but they don't matter if the result doesn't have side effects and can't // be affect by side-effects. fold("function f() { try { if (x) { throw 1 } } finally {} throw 1; }", "function f() { try { if (x) {} } finally {} throw 1; }"); fold("function f() { switch(a){ case 1: throw a; } throw a; }", "function f() { switch(a){ case 1: } throw a; }"); fold("function f() { switch(a){ " + "case 1: throw a; case 2: throw a; } throw a; }", "function f() { switch(a){ case 1: break; case 2: } throw a; }"); } public void testNestedIfCombine() { fold("if(x)if(y){while(1){}}", "if(x&&y){while(1){}}"); fold("if(x||z)if(y){while(1){}}", "if((x||z)&&y){while(1){}}"); fold("if(x)if(y||z){while(1){}}", "if((x)&&(y||z)){while(1){}}"); foldSame("if(x||z)if(y||z){while(1){}}"); fold("if(x)if(y){if(z){while(1){}}}", "if(x&&y&&z){while(1){}}"); } public void testFoldTrueFalse() { fold("x = true", "x = !0"); fold("x = false", "x = !1"); } public void testIssue291() { fold("if (true) { f.onchange(); }", "if (1) f.onchange();"); foldSame("if (f) { f.onchange(); }"); foldSame("if (f) { f.bar(); } else { f.onchange(); }"); fold("if (f) { f.bonchange(); }", "f && f.bonchange();"); foldSame("if (f) { f['x'](); }"); } public void testUndefined() { foldSame("var x = undefined"); foldSame("function f(f) {var undefined=2;var x = undefined;}"); this.enableNormalize(); fold("var x = undefined", "var x=void 0"); foldSame( "var undefined = 1;" + "function f() {var undefined=2;var x = undefined;}"); foldSame("function f(undefined) {}"); foldSame("try {} catch(undefined) {}"); foldSame("for (undefined in {}) {}"); foldSame("undefined++;"); fold("undefined += undefined;", "undefined += void 0;"); } public void testSplitCommaExpressions() { late = false; // Don't try to split in expressions. foldSame("while (foo(), !0) boo()"); foldSame("var a = (foo(), !0);"); foldSame("a = (foo(), !0);"); // Don't try to split COMMA under LABELs. foldSame("a:a(),b()"); fold("(x=2), foo()", "x=2; foo()"); fold("foo(), boo();", "foo(); boo()"); fold("(a(), b()), (c(), d());", "a(); b(); (c(), d());"); fold("a(); b(); (c(), d());", "a(); b(); c(); d();"); fold("foo(), true", "foo();true"); fold("foo();true", "foo();1"); fold("function x(){foo(), !0}", "function x(){foo(); !0}"); fold("function x(){foo(); !0}", "function x(){foo(); 1}"); } public void testComma1() { late = false; fold("1, 2", "1; 2"); fold("1; 2", "1; 1"); late = true; foldSame("1, 2"); } public void testComma2() { late = false; test("1, a()", "1; a()"); late = true; foldSame("1, a()"); } public void testComma3() { late = false; test("1, a(), b()", "1; a(); b()"); late = true; foldSame("1, a(), b()"); } public void testComma4() { late = false; test("a(), b()", "a();b()"); late = true; foldSame("a(), b()"); } public void testComma5() { late = false; test("a(), b(), 1", "a();b();1"); late = true; foldSame("a(), b(), 1"); } public void testObjectLiteral() { test("({})", "1"); test("({a:1})", "1"); testSame("({a:foo()})"); testSame("({'a':foo()})"); } public void testArrayLiteral() { test("([])", "1"); test("([1])", "1"); test("([a])", "1"); testSame("([foo()])"); } public void testStringArraySplitting() { testSame("var x=['1','2','3','4']"); testSame("var x=['1','2','3','4','5']"); test("var x=['1','2','3','4','5','6']", "var x='123456'.split('')"); test("var x=['1','2','3','4','5','00']", "var x='1 2 3 4 5 00'.split(' ')"); test("var x=['1','2','3','4','5','6','7']", "var x='1234567'.split('')"); test("var x=['1','2','3','4','5','6','00']", "var x='1 2 3 4 5 6 00'.split(' ')"); test("var x=[' ,',',',',',',',',',',']", "var x=' ,;,;,;,;,;,'.split(';')"); test("var x=[',,',' ',',',',',',',',']", "var x=',,; ;,;,;,;,'.split(';')"); test("var x=['a,',' ',',',',',',',',']", "var x='a,; ;,;,;,;,'.split(';')"); // all possible delimiters used, leave it alone testSame("var x=[',', ' ', ';', '{', '}']"); } public void testRemoveElseCause() { test("function f() {" + " if(x) return 1;" + " else if(x) return 2;" + " else if(x) return 3 }", "function f() {" + " if(x) return 1;" + "{ if(x) return 2;" + "{ if(x) return 3 } } }"); } public void testRemoveElseCause1() { test("function f() { if (x) throw 1; else f() }", "function f() { if (x) throw 1; { f() } }"); } public void testRemoveElseCause2() { test("function f() { if (x) return 1; else f() }", "function f() { if (x) return 1; { f() } }"); test("function f() { if (x) return; else f() }", "function f() { if (x) {} else { f() } }"); // This case is handled by minimize exit points. testSame("function f() { if (x) return; f() }"); } public void testRemoveElseCause3() { testSame("function f() { a:{if (x) break a; else f() } }"); testSame("function f() { if (x) { a:{ break a } } else f() }"); testSame("function f() { if (x) a:{ break a } else f() }"); } public void testRemoveElseCause4() { testSame("function f() { if (x) { if (y) { return 1; } } else f() }"); } public void testIssue925() { test( "if (x[--y] === 1) {\n" + " x[y] = 0;\n" + "} else {\n" + " x[y] = 1;\n" + "}", "(x[--y] === 1) ? x[y] = 0 : x[y] = 1;"); test( "if (x[--y]) {\n" + " a = 0;\n" + "} else {\n" + " a = 1;\n" + "}", "a = (x[--y]) ? 0 : 1;"); test("if (x++) { x += 2 } else { x += 3 }", "x++ ? x += 2 : x += 3"); test("if (x++) { x = x + 2 } else { x = x + 3 }", "x = x++ ? x + 2 : x + 3"); } public void testBindToCall1() { test("(goog.bind(f))()", "f()"); test("(goog.bind(f,a))()", "f.call(a)"); test("(goog.bind(f,a,b))()", "f.call(a,b)"); test("(goog.bind(f))(a)", "f(a)"); test("(goog.bind(f,a))(b)", "f.call(a,b)"); test("(goog.bind(f,a,b))(c)", "f.call(a,b,c)"); test("(goog.partial(f))()", "f()"); test("(goog.partial(f,a))()", "f(a)"); test("(goog.partial(f,a,b))()", "f(a,b)"); test("(goog.partial(f))(a)", "f(a)"); test("(goog.partial(f,a))(b)", "f(a,b)"); test("(goog.partial(f,a,b))(c)", "f(a,b,c)"); test("((function(){}).bind())()", "((function(){}))()"); test("((function(){}).bind(a))()", "((function(){})).call(a)"); test("((function(){}).bind(a,b))()", "((function(){})).call(a,b)"); test("((function(){}).bind())(a)", "((function(){}))(a)"); test("((function(){}).bind(a))(b)", "((function(){})).call(a,b)"); test("((function(){}).bind(a,b))(c)", "((function(){})).call(a,b,c)"); // Without using type information we don't know "f" is a function. testSame("(f.bind())()"); testSame("(f.bind(a))()"); testSame("(f.bind())(a)"); testSame("(f.bind(a))(b)"); // Don't rewrite if the bind isn't the immediate call target testSame("(goog.bind(f)).call(g)"); } public void testBindToCall2() { test("(goog$bind(f))()", "f()"); test("(goog$bind(f,a))()", "f.call(a)"); test("(goog$bind(f,a,b))()", "f.call(a,b)"); test("(goog$bind(f))(a)", "f(a)"); test("(goog$bind(f,a))(b)", "f.call(a,b)"); test("(goog$bind(f,a,b))(c)", "f.call(a,b,c)"); test("(goog$partial(f))()", "f()"); test("(goog$partial(f,a))()", "f(a)"); test("(goog$partial(f,a,b))()", "f(a,b)"); test("(goog$partial(f))(a)", "f(a)"); test("(goog$partial(f,a))(b)", "f(a,b)"); test("(goog$partial(f,a,b))(c)", "f(a,b,c)"); // Don't rewrite if the bind isn't the immediate call target testSame("(goog$bind(f)).call(g)"); } public void testBindToCall3() { // TODO(johnlenz): The code generator wraps free calls with (0,...) to // prevent leaking "this", but the parser doesn't unfold it, making a // AST comparison fail. For now do a string comparison to validate the // correct code is in fact generated. // The FREE call wrapping should be moved out of the code generator // and into a denormalizing pass. new StringCompareTestCase().testBindToCall3(); } public void testSimpleFunctionCall() { test("var a = String(23)", "var a = '' + 23"); test("var a = String('hello')", "var a = '' + 'hello'"); testSame("var a = String('hello', bar());"); testSame("var a = String({valueOf: function() { return 1; }});"); } private static class StringCompareTestCase extends CompilerTestCase { StringCompareTestCase() { super("", false); } @Override protected CompilerPass getProcessor(Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeSubstituteAlternateSyntax(false)); return peepholePass; } public void testBindToCall3() { test("(goog.bind(f.m))()", "(0,f.m)()"); test("(goog.bind(f.m,a))()", "f.m.call(a)"); test("(goog.bind(f.m))(a)", "(0,f.m)(a)"); test("(goog.bind(f.m,a))(b)", "f.m.call(a,b)"); test("(goog.partial(f.m))()", "(0,f.m)()"); test("(goog.partial(f.m,a))()", "(0,f.m)(a)"); test("(goog.partial(f.m))(a)", "(0,f.m)(a)"); test("(goog.partial(f.m,a))(b)", "(0,f.m)(a,b)"); // Without using type information we don't know "f" is a function. testSame("f.m.bind()()"); testSame("f.m.bind(a)()"); testSame("f.m.bind()(a)"); testSame("f.m.bind(a)(b)"); // Don't rewrite if the bind isn't the immediate call target testSame("goog.bind(f.m).call(g)"); } } }
// You are a professional Java test case writer, please create a test case named `testIssue925` for the issue `Closure-925`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-925 // // ## Issue-Title: // if statement // // ## Issue-Description: // **What steps will reproduce the problem?** // INPUT: // if( es[--esi][ es[esi+1] ] === 1) // { // es[esi] = 0; // } // else // { // es[esi] = 1; // } // OUTPUT: // // es[esi] = 1 === es[--esi][es[esi + 1]] ? 0 : 1; // // BUT MUST BE // es[--esi] = 1 === es[esi][es[esi + 1]] ? 0 : 1; // // Im using latest version on windows // // public void testIssue925() {
987
132
965
test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java
test
```markdown ## Issue-ID: Closure-925 ## Issue-Title: if statement ## Issue-Description: **What steps will reproduce the problem?** INPUT: if( es[--esi][ es[esi+1] ] === 1) { es[esi] = 0; } else { es[esi] = 1; } OUTPUT: es[esi] = 1 === es[--esi][es[esi + 1]] ? 0 : 1; BUT MUST BE es[--esi] = 1 === es[esi][es[esi + 1]] ? 0 : 1; Im using latest version on windows ``` You are a professional Java test case writer, please create a test case named `testIssue925` for the issue `Closure-925`, utilizing the provided issue report information and the following function signature. ```java public void testIssue925() { ```
965
[ "com.google.javascript.jscomp.PeepholeSubstituteAlternateSyntax" ]
0a901c2d99ba7e71ce4fe08c81a6650b2301e27afd561ada89f37c1462772bc8
public void testIssue925()
// You are a professional Java test case writer, please create a test case named `testIssue925` for the issue `Closure-925`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-925 // // ## Issue-Title: // if statement // // ## Issue-Description: // **What steps will reproduce the problem?** // INPUT: // if( es[--esi][ es[esi+1] ] === 1) // { // es[esi] = 0; // } // else // { // es[esi] = 1; // } // OUTPUT: // // es[esi] = 1 === es[--esi][es[esi + 1]] ? 0 : 1; // // BUT MUST BE // es[--esi] = 1 === es[esi][es[esi + 1]] ? 0 : 1; // // Im using latest version on windows // //
Closure
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Tests for {@link PeepholeSubstituteAlternateSyntax} in isolation. * Tests for the interaction of multiple peephole passes are in * PeepholeIntegrationTest. */ public class PeepholeSubstituteAlternateSyntaxTest extends CompilerTestCase { // Externs for built-in constructors // Needed for testFoldLiteralObjectConstructors(), // testFoldLiteralArrayConstructors() and testFoldRegExp...() private static final String FOLD_CONSTANTS_TEST_EXTERNS = "var Object = function f(){};\n" + "var RegExp = function f(a){};\n" + "var Array = function f(a){};\n"; private boolean late = true; // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeSubstituteAlternateSyntaxTest(boolean compareAsTree) { super(FOLD_CONSTANTS_TEST_EXTERNS, compareAsTree); } public PeepholeSubstituteAlternateSyntaxTest() { super(FOLD_CONSTANTS_TEST_EXTERNS); } @Override public void setUp() throws Exception { late = true; super.setUp(); enableLineNumberCheck(true); disableNormalize(); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeSubstituteAlternateSyntax(late)) .setRetraverseOnChange(false); return peepholePass; } @Override protected int getNumRepetitions() { return 1; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } void assertResultString(String js, String expected) { assertResultString(js, expected, false); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. void assertResultString(String js, String expected, boolean normalize) { PeepholeSubstituteAlternateSyntaxTest scTest = new PeepholeSubstituteAlternateSyntaxTest(false); if (normalize) { scTest.enableNormalize(); } else { scTest.disableNormalize(); } scTest.test(js, expected); } /** Check that removing blocks with 1 child works */ public void testFoldOneChildBlocks() { late = false; fold("function f(){if(x)a();x=3}", "function f(){x&&a();x=3}"); fold("function f(){if(x){a()}x=3}", "function f(){x&&a();x=3}"); fold("function f(){if(x){return 3}}", "function f(){if(x)return 3}"); fold("function f(){if(x){a()}}", "function f(){x&&a()}"); fold("function f(){if(x){throw 1}}", "function f(){if(x)throw 1;}"); // Try it out with functions fold("function f(){if(x){foo()}}", "function f(){x&&foo()}"); fold("function f(){if(x){foo()}else{bar()}}", "function f(){x?foo():bar()}"); // Try it out with properties and methods fold("function f(){if(x){a.b=1}}", "function f(){if(x)a.b=1}"); fold("function f(){if(x){a.b*=1}}", "function f(){x&&(a.b*=1)}"); fold("function f(){if(x){a.b+=1}}", "function f(){x&&(a.b+=1)}"); fold("function f(){if(x){++a.b}}", "function f(){x&&++a.b}"); fold("function f(){if(x){a.foo()}}", "function f(){x&&a.foo()}"); // Try it out with throw/catch/finally [which should not change] fold("function f(){try{foo()}catch(e){bar(e)}finally{baz()}}", "function f(){try{foo()}catch(e){bar(e)}finally{baz()}}"); // Try it out with switch statements fold("function f(){switch(x){case 1:break}}", "function f(){switch(x){case 1:break}}"); // Do while loops stay in a block if that's where they started fold("function f(){if(e1){do foo();while(e2)}else foo2()}", "function f(){if(e1){do foo();while(e2)}else foo2()}"); // Test an obscure case with do and while fold("if(x){do{foo()}while(y)}else bar()", "if(x){do foo();while(y)}else bar()"); // Play with nested IFs fold("function f(){if(x){if(y)foo()}}", "function f(){x&&y&&foo()}"); fold("function f(){if(x){if(y)foo();else bar()}}", "function f(){x&&(y?foo():bar())}"); fold("function f(){if(x){if(y)foo()}else bar()}", "function f(){x?y&&foo():bar()}"); fold("function f(){if(x){if(y)foo();else bar()}else{baz()}}", "function f(){x?y?foo():bar():baz()}"); fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}", "if(e1)while(e2)e3&&foo();else bar()"); fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}", "if(e1)with(e2)e3&&foo();else bar()"); fold("if(a||b){if(c||d){var x;}}", "if(a||b)if(c||d)var x"); fold("if(x){ if(y){var x;}else{var z;} }", "if(x)if(y)var x;else var z"); // NOTE - technically we can remove the blocks since both the parent // and child have elses. But we don't since it causes ambiguities in // some cases where not all descendent ifs having elses fold("if(x){ if(y){var x;}else{var z;} }else{var w}", "if(x)if(y)var x;else var z;else var w"); fold("if (x) {var x;}else { if (y) { var y;} }", "if(x)var x;else if(y)var y"); // Here's some of the ambiguous cases fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}", "if(a)if(b){f1();f2()}else c&&f3();else d&&f4()"); fold("function f(){foo()}", "function f(){foo()}"); fold("switch(x){case y: foo()}", "switch(x){case y:foo()}"); fold("try{foo()}catch(ex){bar()}finally{baz()}", "try{foo()}catch(ex){bar()}finally{baz()}"); } /** Try to minimize returns */ public void testFoldReturns() { fold("function f(){if(x)return 1;else return 2}", "function f(){return x?1:2}"); fold("function f(){if(x)return 1;return 2}", "function f(){return x?1:2}"); fold("function f(){if(x)return;return 2}", "function f(){return x?void 0:2}"); fold("function f(){if(x)return 1+x;else return 2-x}", "function f(){return x?1+x:2-x}"); fold("function f(){if(x)return 1+x;return 2-x}", "function f(){return x?1+x:2-x}"); fold("function f(){if(x)return y += 1;else return y += 2}", "function f(){return x?(y+=1):(y+=2)}"); fold("function f(){if(x)return;else return 2-x}", "function f(){if(x);else return 2-x}"); fold("function f(){if(x)return;return 2-x}", "function f(){return x?void 0:2-x}"); fold("function f(){if(x)return x;else return}", "function f(){if(x)return x;{}}"); fold("function f(){if(x)return x;return}", "function f(){if(x)return x}"); foldSame("function f(){for(var x in y) { return x.y; } return k}"); } public void testCombineIfs1() { fold("function f() {if (x) return 1; if (y) return 1}", "function f() {if (x||y) return 1;}"); fold("function f() {if (x) return 1; if (y) foo(); else return 1}", "function f() {if ((!x)&&y) foo(); else return 1;}"); } public void testCombineIfs2() { // combinable but not yet done foldSame("function f() {if (x) throw 1; if (y) throw 1}"); // Can't combine, side-effect fold("function f(){ if (x) g(); if (y) g() }", "function f(){ x&&g(); y&&g() }"); // Can't combine, side-effect fold("function f(){ if (x) y = 0; if (y) y = 0; }", "function f(){ x&&(y = 0); y&&(y = 0); }"); } public void testCombineIfs3() { foldSame("function f() {if (x) return 1; if (y) {g();f()}}"); } /** Try to minimize assignments */ public void testFoldAssignments() { fold("function f(){if(x)y=3;else y=4;}", "function f(){y=x?3:4}"); fold("function f(){if(x)y=1+a;else y=2+a;}", "function f(){y=x?1+a:2+a}"); // and operation assignments fold("function f(){if(x)y+=1;else y+=2;}", "function f(){y+=x?1:2}"); fold("function f(){if(x)y-=1;else y-=2;}", "function f(){y-=x?1:2}"); fold("function f(){if(x)y%=1;else y%=2;}", "function f(){y%=x?1:2}"); fold("function f(){if(x)y|=1;else y|=2;}", "function f(){y|=x?1:2}"); // sanity check, don't fold if the 2 ops don't match foldSame("function f(){x ? y-=1 : y+=2}"); // sanity check, don't fold if the 2 LHS don't match foldSame("function f(){x ? y-=1 : z-=1}"); // sanity check, don't fold if there are potential effects foldSame("function f(){x ? y().a=3 : y().a=4}"); } public void testRemoveDuplicateStatements() { fold("if (a) { x = 1; x++ } else { x = 2; x++ }", "x=(a) ? 1 : 2; x++"); fold("if (a) { x = 1; x++; y += 1; z = pi; }" + " else { x = 2; x++; y += 1; z = pi; }", "x=(a) ? 1 : 2; x++; y += 1; z = pi;"); fold("function z() {" + "if (a) { foo(); return !0 } else { goo(); return !0 }" + "}", "function z() {(a) ? foo() : goo(); return !0}"); fold("function z() {if (a) { foo(); x = true; return true " + "} else { goo(); x = true; return true }}", "function z() {(a) ? foo() : goo(); x = !0; return !0}"); fold("function z() {" + " if (a) { bar(); foo(); return true }" + " else { bar(); goo(); return true }" + "}", "function z() {" + " if (a) { bar(); foo(); }" + " else { bar(); goo(); }" + " return !0;" + "}"); } public void testNotCond() { fold("function f(){if(!x)foo()}", "function f(){x||foo()}"); fold("function f(){if(!x)b=1}", "function f(){x||(b=1)}"); fold("if(!x)z=1;else if(y)z=2", "if(x){y&&(z=2);}else{z=1;}"); fold("if(x)y&&(z=2);else z=1;", "x ? y&&(z=2) : z=1"); foldSame("function f(){if(!(x=1))a.b=1}"); } public void testAndParenthesesCount() { fold("function f(){if(x||y)a.foo()}", "function f(){(x||y)&&a.foo()}"); fold("function f(){if(x.a)x.a=0}", "function f(){x.a&&(x.a=0)}"); foldSame("function f(){if(x()||y()){x()||y()}}"); } public void testFoldLogicalOpStringCompare() { // side-effects // There is two way to parse two &&'s and both are correct. assertResultString("if(foo() && false) z()", "foo()&&0&&z()"); } public void testFoldNot() { fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}"); fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}"); fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}"); fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}"); // Because !(x<NaN) != x>=NaN don't fold < and > cases. foldSame("while(!(x>y)){a=b;}"); foldSame("while(!(x>=y)){a=b;}"); foldSame("while(!(x<y)){a=b;}"); foldSame("while(!(x<=y)){a=b;}"); foldSame("while(!(x<=NaN)){a=b;}"); // NOT forces a boolean context fold("x = !(y() && true)", "x = !y()"); // This will be further optimized by PeepholeFoldConstants. fold("x = !true", "x = !1"); } public void testFoldRegExpConstructor() { enableNormalize(); // Cannot fold all the way to a literal because there are too few arguments. fold("x = new RegExp", "x = RegExp()"); // Empty regexp should not fold to // since that is a line comment in JS fold("x = new RegExp(\"\")", "x = RegExp(\"\")"); fold("x = new RegExp(\"\", \"i\")", "x = RegExp(\"\",\"i\")"); // Bogus flags should not fold testSame("x = RegExp(\"foobar\", \"bogus\")", PeepholeSubstituteAlternateSyntax.INVALID_REGULAR_EXPRESSION_FLAGS); // Can Fold fold("x = new RegExp(\"foobar\")", "x = /foobar/"); fold("x = RegExp(\"foobar\")", "x = /foobar/"); fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i"); // Make sure that escaping works fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i"); fold("x = new RegExp(\"/\", \"\")", "x = /\\//"); fold("x = new RegExp(\"[/]\", \"\")", "x = /[/]/"); fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//"); fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//"); fold("x = new RegExp(\"\\n\")", "x = /\\n/"); fold("x = new RegExp('\\\\\\r')", "x = /\\r/"); // Don't fold really long regexp literals, because Opera 9.2's // regexp parser will explode. String longRegexp = ""; for (int i = 0; i < 200; i++) longRegexp += "x"; foldSame("x = RegExp(\"" + longRegexp + "\")"); // Shouldn't fold RegExp unnormalized because // we can't be sure that RegExp hasn't been redefined disableNormalize(); foldSame("x = new RegExp(\"foobar\")"); } public void testVersionSpecificRegExpQuirks() { enableNormalize(); // Don't fold if the flags contain 'g' enableEcmaScript5(false); fold("x = new RegExp(\"foobar\", \"g\")", "x = RegExp(\"foobar\",\"g\")"); fold("x = new RegExp(\"foobar\", \"ig\")", "x = RegExp(\"foobar\",\"ig\")"); // ... unless in ECMAScript 5 mode per section 7.8.5 of ECMAScript 5. enableEcmaScript5(true); fold("x = new RegExp(\"foobar\", \"ig\")", "x = /foobar/ig"); // Don't fold things that crash older versions of Safari and that don't work // as regex literals on other old versions of Safari enableEcmaScript5(false); fold("x = new RegExp(\"\\u2028\")", "x = RegExp(\"\\u2028\")"); fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/"); // Sunset Safari exclusions for ECMAScript 5 and later. enableEcmaScript5(true); fold("x = new RegExp(\"\\u2028\\u2029\")", "x = /\\u2028\\u2029/"); fold("x = new RegExp(\"\\\\u2028\")", "x = /\\u2028/"); fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/"); } public void testFoldRegExpConstructorStringCompare() { // Might have something to do with the internal representation of \n and how // it is used in node comparison. assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i", true); } public void testContainsUnicodeEscape() throws Exception { assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("")); assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo")); assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape( "\u2028")); assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape( "\\u2028")); assertTrue( PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo\\u2028")); assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape( "foo\\\\u2028")); assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape( "foo\\\\u2028bar\\u2028")); } public void testFoldLiteralObjectConstructors() { enableNormalize(); // Can fold when normalized fold("x = new Object", "x = ({})"); fold("x = new Object()", "x = ({})"); fold("x = Object()", "x = ({})"); disableNormalize(); // Cannot fold above when not normalized foldSame("x = new Object"); foldSame("x = new Object()"); foldSame("x = Object()"); enableNormalize(); // Cannot fold, the constructor being used is actually a local function foldSame("x = " + "(function f(){function Object(){this.x=4};return new Object();})();"); } public void testFoldLiteralArrayConstructors() { enableNormalize(); // No arguments - can fold when normalized fold("x = new Array", "x = []"); fold("x = new Array()", "x = []"); fold("x = Array()", "x = []"); // One argument - can be fold when normalized fold("x = new Array(0)", "x = []"); fold("x = Array(0)", "x = []"); fold("x = new Array(\"a\")", "x = [\"a\"]"); fold("x = Array(\"a\")", "x = [\"a\"]"); // One argument - cannot be fold when normalized fold("x = new Array(7)", "x = Array(7)"); fold("x = Array(7)", "x = Array(7)"); fold("x = new Array(y)", "x = Array(y)"); fold("x = Array(y)", "x = Array(y)"); fold("x = new Array(foo())", "x = Array(foo())"); fold("x = Array(foo())", "x = Array(foo())"); // More than one argument - can be fold when normalized fold("x = new Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]"); fold("x = Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]"); fold("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')", "x = ['a', 1, 2, 'bc', 3, {}, 'abc']"); fold("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')", "x = ['a', 1, 2, 'bc', 3, {}, 'abc']"); fold("x = new Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]"); fold("x = Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]"); fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))", "x = [{}, [\"abc\", {}, [[]]]]"); fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))", "x = [{}, [\"abc\", {}, [[]]]]"); disableNormalize(); // Cannot fold above when not normalized foldSame("x = new Array"); foldSame("x = new Array()"); foldSame("x = Array()"); foldSame("x = new Array(0)"); foldSame("x = Array(0)"); foldSame("x = new Array(\"a\")"); foldSame("x = Array(\"a\")"); foldSame("x = new Array(7)"); foldSame("x = Array(7)"); foldSame("x = new Array(foo())"); foldSame("x = Array(foo())"); foldSame("x = new Array(1, 2, 3, 4)"); foldSame("x = Array(1, 2, 3, 4)"); foldSame("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')"); foldSame("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')"); foldSame("x = new Array(Array(1, '2', 3, '4'))"); foldSame("x = Array(Array(1, '2', 3, '4'))"); foldSame("x = new Array(" + "Object(), Array(\"abc\", Object(), Array(Array())))"); foldSame("x = new Array(" + "Object(), Array(\"abc\", Object(), Array(Array())))"); } public void testMinimizeExprCondition() { fold("(x ? true : false) && y()", "x&&y()"); fold("(x ? false : true) && y()", "(!x)&&y()"); fold("(x ? true : y) && y()", "(x || y)&&y()"); fold("(x ? y : false) && y()", "(x && y)&&y()"); fold("(x && true) && y()", "x && y()"); fold("(x && false) && y()", "0&&y()"); fold("(x || true) && y()", "1&&y()"); fold("(x || false) && y()", "x&&y()"); } public void testMinimizeWhileCondition() { // This test uses constant folding logic, so is only here for completeness. fold("while(!!true) foo()", "while(1) foo()"); // These test tryMinimizeCondition fold("while(!!x) foo()", "while(x) foo()"); fold("while(!(!x&&!y)) foo()", "while(x||y) foo()"); fold("while(x||!!y) foo()", "while(x||y) foo()"); fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()"); fold("while(!(!x&&y)) foo()", "while(x||!y) foo()"); fold("while(!(x||!y)) foo()", "while(!x&&y) foo()"); fold("while(!(x||y)) foo()", "while(!x&&!y) foo()"); fold("while(!(!x||y-z)) foo()", "while(x&&!(y-z)) foo()"); fold("while(!(!(x/y)||z+w)) foo()", "while(x/y&&!(z+w)) foo()"); foldSame("while(!(x+y||z)) foo()"); foldSame("while(!(x&&y*z)) foo()"); fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()"); fold("while(x&&!0) foo()", "while(x) foo()"); fold("while(x||!1) foo()", "while(x) foo()"); fold("while(!((x,y)&&z)) foo()", "while(!(x,y)||!z) foo()"); } public void testMinimizeForCondition() { // This test uses constant folding logic, so is only here for completeness. // These could be simplified to "for(;;) ..." fold("for(;!!true;) foo()", "for(;1;) foo()"); // Don't bother with FOR inits as there are normalized out. fold("for(!!true;;) foo()", "for(!0;;) foo()"); // These test tryMinimizeCondition fold("for(;!!x;) foo()", "for(;x;) foo()"); // sanity check foldSame("for(a in b) foo()"); foldSame("for(a in {}) foo()"); foldSame("for(a in []) foo()"); fold("for(a in !!true) foo()", "for(a in !0) foo()"); } public void testMinimizeCondition_example1() { // Based on a real failing code sample. fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}"); } public void testFoldLoopBreakLate() { late = true; fold("for(;;) if (a) break", "for(;!a;);"); foldSame("for(;;) if (a) { f(); break }"); fold("for(;;) if (a) break; else f()", "for(;!a;) { { f(); } }"); fold("for(;a;) if (b) break", "for(;a && !b;);"); fold("for(;a;) { if (b) break; if (c) break; }", "for(;(a && !b);) if (c) break;"); fold("for(;(a && !b);) if (c) break;", "for(;(a && !b) && !c;);"); // 'while' is normalized to 'for' enableNormalize(true); fold("while(true) if (a) break", "for(;1&&!a;);"); } public void testFoldLoopBreakEarly() { late = false; foldSame("for(;;) if (a) break"); foldSame("for(;;) if (a) { f(); break }"); foldSame("for(;;) if (a) break; else f()"); foldSame("for(;a;) if (b) break"); foldSame("for(;a;) { if (b) break; if (c) break; }"); foldSame("while(1) if (a) break"); enableNormalize(true); foldSame("while(1) if (a) break"); } public void testFoldConditionalVarDeclaration() { fold("if(x) var y=1;else y=2", "var y=x?1:2"); fold("if(x) y=1;else var y=2", "var y=x?1:2"); foldSame("if(x) var y = 1; z = 2"); foldSame("if(x||y) y = 1; var z = 2"); foldSame("if(x) { var y = 1; print(y)} else y = 2 "); foldSame("if(x) var y = 1; else {y = 2; print(y)}"); } public void testFoldReturnResult() { fold("function f(){return false;}", "function f(){return !1}"); foldSame("function f(){return null;}"); fold("function f(){return void 0;}", "function f(){return}"); fold("function f(){return;}", "function f(){}"); foldSame("function f(){return void foo();}"); fold("function f(){return undefined;}", "function f(){return}"); fold("function f(){if(a()){return undefined;}}", "function f(){if(a()){return}}"); } public void testFoldStandardConstructors() { foldSame("new Foo('a')"); foldSame("var x = new goog.Foo(1)"); foldSame("var x = new String(1)"); foldSame("var x = new Number(1)"); foldSame("var x = new Boolean(1)"); enableNormalize(); fold("var x = new Object('a')", "var x = Object('a')"); fold("var x = new RegExp('')", "var x = RegExp('')"); fold("var x = new Error('20')", "var x = Error(\"20\")"); fold("var x = new Array(20)", "var x = Array(20)"); } public void testSubsituteReturn() { fold("function f() { while(x) { return }}", "function f() { while(x) { break }}"); foldSame("function f() { while(x) { return 5 } }"); foldSame("function f() { a: { return 5 } }"); fold("function f() { while(x) { return 5} return 5}", "function f() { while(x) { break } return 5}"); fold("function f() { while(x) { return x} return x}", "function f() { while(x) { break } return x}"); fold("function f() { while(x) { if (y) { return }}}", "function f() { while(x) { if (y) { break }}}"); fold("function f() { while(x) { if (y) { return }} return}", "function f() { while(x) { if (y) { break }}}"); fold("function f() { while(x) { if (y) { return 5 }} return 5}", "function f() { while(x) { if (y) { break }} return 5}"); // It doesn't matter if x is changed between them. We are still returning // x at whatever x value current holds. The whole x = 1 is skipped. fold("function f() { while(x) { if (y) { return x } x = 1} return x}", "function f() { while(x) { if (y) { break } x = 1} return x}"); // RemoveUnreachableCode would take care of the useless breaks. fold("function f() { while(x) { if (y) { return x } return x} return x}", "function f() { while(x) { if (y) {} break }return x}"); // A break here only breaks out of the inner loop. foldSame("function f() { while(x) { while (y) { return } } }"); foldSame("function f() { while(1) { return 7} return 5}"); foldSame("function f() {" + " try { while(x) {return f()}} catch (e) { } return f()}"); foldSame("function f() {" + " try { while(x) {return f()}} finally {alert(1)} return f()}"); // Both returns has the same handler fold("function f() {" + " try { while(x) { return f() } return f() } catch (e) { } }", "function f() {" + " try { while(x) { break } return f() } catch (e) { } }"); // We can't fold this because it'll change the order of when foo is called. foldSame("function f() {" + " try { while(x) { return foo() } } finally { alert(1) } " + " return foo()}"); // This is fine, we have no side effect in the return value. fold("function f() {" + " try { while(x) { return 1 } } finally { alert(1) } return 1}", "function f() {" + " try { while(x) { break } } finally { alert(1) } return 1}" ); foldSame("function f() { try{ return a } finally { a = 2 } return a; }"); fold( "function f() { switch(a){ case 1: return a; default: g();} return a;}", "function f() { switch(a){ case 1: break; default: g();} return a; }"); } public void testSubsituteBreakForThrow() { foldSame("function f() { while(x) { throw Error }}"); fold("function f() { while(x) { throw Error } throw Error }", "function f() { while(x) { break } throw Error}"); foldSame("function f() { while(x) { throw Error(1) } throw Error(2)}"); foldSame("function f() { while(x) { throw Error(1) } return Error(2)}"); foldSame("function f() { while(x) { throw 5 } }"); foldSame("function f() { a: { throw 5 } }"); fold("function f() { while(x) { throw 5} throw 5}", "function f() { while(x) { break } throw 5}"); fold("function f() { while(x) { throw x} throw x}", "function f() { while(x) { break } throw x}"); foldSame("function f() { while(x) { if (y) { throw Error }}}"); fold("function f() { while(x) { if (y) { throw Error }} throw Error}", "function f() { while(x) { if (y) { break }} throw Error}"); fold("function f() { while(x) { if (y) { throw 5 }} throw 5}", "function f() { while(x) { if (y) { break }} throw 5}"); // It doesn't matter if x is changed between them. We are still throwing // x at whatever x value current holds. The whole x = 1 is skipped. fold("function f() { while(x) { if (y) { throw x } x = 1} throw x}", "function f() { while(x) { if (y) { break } x = 1} throw x}"); // RemoveUnreachableCode would take care of the useless breaks. fold("function f() { while(x) { if (y) { throw x } throw x} throw x}", "function f() { while(x) { if (y) {} break }throw x}"); // A break here only breaks out of the inner loop. foldSame("function f() { while(x) { while (y) { throw Error } } }"); foldSame("function f() { while(1) { throw 7} throw 5}"); foldSame("function f() {" + " try { while(x) {throw f()}} catch (e) { } throw f()}"); foldSame("function f() {" + " try { while(x) {throw f()}} finally {alert(1)} throw f()}"); // Both throws has the same handler fold("function f() {" + " try { while(x) { throw f() } throw f() } catch (e) { } }", "function f() {" + " try { while(x) { break } throw f() } catch (e) { } }"); // We can't fold this because it'll change the order of when foo is called. foldSame("function f() {" + " try { while(x) { throw foo() } } finally { alert(1) } " + " throw foo()}"); // This is fine, we have no side effect in the throw value. fold("function f() {" + " try { while(x) { throw 1 } } finally { alert(1) } throw 1}", "function f() {" + " try { while(x) { break } } finally { alert(1) } throw 1}" ); foldSame("function f() { try{ throw a } finally { a = 2 } throw a; }"); fold( "function f() { switch(a){ case 1: throw a; default: g();} throw a;}", "function f() { switch(a){ case 1: break; default: g();} throw a; }"); } public void testRemoveDuplicateReturn() { fold("function f() { return; }", "function f(){}"); foldSame("function f() { return a; }"); fold("function f() { if (x) { return a } return a; }", "function f() { if (x) {} return a; }"); foldSame( "function f() { try { if (x) { return a } } catch(e) {} return a; }"); foldSame( "function f() { try { if (x) {} } catch(e) {} return 1; }"); // finally clauses may have side effects foldSame( "function f() { try { if (x) { return a } } finally { a++ } return a; }"); // but they don't matter if the result doesn't have side effects and can't // be affect by side-effects. fold("function f() { try { if (x) { return 1 } } finally {} return 1; }", "function f() { try { if (x) {} } finally {} return 1; }"); fold("function f() { switch(a){ case 1: return a; } return a; }", "function f() { switch(a){ case 1: } return a; }"); fold("function f() { switch(a){ " + " case 1: return a; case 2: return a; } return a; }", "function f() { switch(a){ " + " case 1: break; case 2: } return a; }"); } public void testRemoveDuplicateThrow() { foldSame("function f() { throw a; }"); fold("function f() { if (x) { throw a } throw a; }", "function f() { if (x) {} throw a; }"); foldSame( "function f() { try { if (x) {throw a} } catch(e) {} throw a; }"); foldSame( "function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }"); foldSame( "function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }"); foldSame( "function f() { try { if (x) {throw 1} } catch(e) {throw 1}}"); fold( "function f() { try { if (x) {throw 1} } catch(e) {throw 1} throw 1; }", "function f() { try { if (x) {throw 1} } catch(e) {} throw 1; }"); // finally clauses may have side effects foldSame( "function f() { try { if (x) { throw a } } finally { a++ } throw a; }"); // but they don't matter if the result doesn't have side effects and can't // be affect by side-effects. fold("function f() { try { if (x) { throw 1 } } finally {} throw 1; }", "function f() { try { if (x) {} } finally {} throw 1; }"); fold("function f() { switch(a){ case 1: throw a; } throw a; }", "function f() { switch(a){ case 1: } throw a; }"); fold("function f() { switch(a){ " + "case 1: throw a; case 2: throw a; } throw a; }", "function f() { switch(a){ case 1: break; case 2: } throw a; }"); } public void testNestedIfCombine() { fold("if(x)if(y){while(1){}}", "if(x&&y){while(1){}}"); fold("if(x||z)if(y){while(1){}}", "if((x||z)&&y){while(1){}}"); fold("if(x)if(y||z){while(1){}}", "if((x)&&(y||z)){while(1){}}"); foldSame("if(x||z)if(y||z){while(1){}}"); fold("if(x)if(y){if(z){while(1){}}}", "if(x&&y&&z){while(1){}}"); } public void testFoldTrueFalse() { fold("x = true", "x = !0"); fold("x = false", "x = !1"); } public void testIssue291() { fold("if (true) { f.onchange(); }", "if (1) f.onchange();"); foldSame("if (f) { f.onchange(); }"); foldSame("if (f) { f.bar(); } else { f.onchange(); }"); fold("if (f) { f.bonchange(); }", "f && f.bonchange();"); foldSame("if (f) { f['x'](); }"); } public void testUndefined() { foldSame("var x = undefined"); foldSame("function f(f) {var undefined=2;var x = undefined;}"); this.enableNormalize(); fold("var x = undefined", "var x=void 0"); foldSame( "var undefined = 1;" + "function f() {var undefined=2;var x = undefined;}"); foldSame("function f(undefined) {}"); foldSame("try {} catch(undefined) {}"); foldSame("for (undefined in {}) {}"); foldSame("undefined++;"); fold("undefined += undefined;", "undefined += void 0;"); } public void testSplitCommaExpressions() { late = false; // Don't try to split in expressions. foldSame("while (foo(), !0) boo()"); foldSame("var a = (foo(), !0);"); foldSame("a = (foo(), !0);"); // Don't try to split COMMA under LABELs. foldSame("a:a(),b()"); fold("(x=2), foo()", "x=2; foo()"); fold("foo(), boo();", "foo(); boo()"); fold("(a(), b()), (c(), d());", "a(); b(); (c(), d());"); fold("a(); b(); (c(), d());", "a(); b(); c(); d();"); fold("foo(), true", "foo();true"); fold("foo();true", "foo();1"); fold("function x(){foo(), !0}", "function x(){foo(); !0}"); fold("function x(){foo(); !0}", "function x(){foo(); 1}"); } public void testComma1() { late = false; fold("1, 2", "1; 2"); fold("1; 2", "1; 1"); late = true; foldSame("1, 2"); } public void testComma2() { late = false; test("1, a()", "1; a()"); late = true; foldSame("1, a()"); } public void testComma3() { late = false; test("1, a(), b()", "1; a(); b()"); late = true; foldSame("1, a(), b()"); } public void testComma4() { late = false; test("a(), b()", "a();b()"); late = true; foldSame("a(), b()"); } public void testComma5() { late = false; test("a(), b(), 1", "a();b();1"); late = true; foldSame("a(), b(), 1"); } public void testObjectLiteral() { test("({})", "1"); test("({a:1})", "1"); testSame("({a:foo()})"); testSame("({'a':foo()})"); } public void testArrayLiteral() { test("([])", "1"); test("([1])", "1"); test("([a])", "1"); testSame("([foo()])"); } public void testStringArraySplitting() { testSame("var x=['1','2','3','4']"); testSame("var x=['1','2','3','4','5']"); test("var x=['1','2','3','4','5','6']", "var x='123456'.split('')"); test("var x=['1','2','3','4','5','00']", "var x='1 2 3 4 5 00'.split(' ')"); test("var x=['1','2','3','4','5','6','7']", "var x='1234567'.split('')"); test("var x=['1','2','3','4','5','6','00']", "var x='1 2 3 4 5 6 00'.split(' ')"); test("var x=[' ,',',',',',',',',',',']", "var x=' ,;,;,;,;,;,'.split(';')"); test("var x=[',,',' ',',',',',',',',']", "var x=',,; ;,;,;,;,'.split(';')"); test("var x=['a,',' ',',',',',',',',']", "var x='a,; ;,;,;,;,'.split(';')"); // all possible delimiters used, leave it alone testSame("var x=[',', ' ', ';', '{', '}']"); } public void testRemoveElseCause() { test("function f() {" + " if(x) return 1;" + " else if(x) return 2;" + " else if(x) return 3 }", "function f() {" + " if(x) return 1;" + "{ if(x) return 2;" + "{ if(x) return 3 } } }"); } public void testRemoveElseCause1() { test("function f() { if (x) throw 1; else f() }", "function f() { if (x) throw 1; { f() } }"); } public void testRemoveElseCause2() { test("function f() { if (x) return 1; else f() }", "function f() { if (x) return 1; { f() } }"); test("function f() { if (x) return; else f() }", "function f() { if (x) {} else { f() } }"); // This case is handled by minimize exit points. testSame("function f() { if (x) return; f() }"); } public void testRemoveElseCause3() { testSame("function f() { a:{if (x) break a; else f() } }"); testSame("function f() { if (x) { a:{ break a } } else f() }"); testSame("function f() { if (x) a:{ break a } else f() }"); } public void testRemoveElseCause4() { testSame("function f() { if (x) { if (y) { return 1; } } else f() }"); } public void testIssue925() { test( "if (x[--y] === 1) {\n" + " x[y] = 0;\n" + "} else {\n" + " x[y] = 1;\n" + "}", "(x[--y] === 1) ? x[y] = 0 : x[y] = 1;"); test( "if (x[--y]) {\n" + " a = 0;\n" + "} else {\n" + " a = 1;\n" + "}", "a = (x[--y]) ? 0 : 1;"); test("if (x++) { x += 2 } else { x += 3 }", "x++ ? x += 2 : x += 3"); test("if (x++) { x = x + 2 } else { x = x + 3 }", "x = x++ ? x + 2 : x + 3"); } public void testBindToCall1() { test("(goog.bind(f))()", "f()"); test("(goog.bind(f,a))()", "f.call(a)"); test("(goog.bind(f,a,b))()", "f.call(a,b)"); test("(goog.bind(f))(a)", "f(a)"); test("(goog.bind(f,a))(b)", "f.call(a,b)"); test("(goog.bind(f,a,b))(c)", "f.call(a,b,c)"); test("(goog.partial(f))()", "f()"); test("(goog.partial(f,a))()", "f(a)"); test("(goog.partial(f,a,b))()", "f(a,b)"); test("(goog.partial(f))(a)", "f(a)"); test("(goog.partial(f,a))(b)", "f(a,b)"); test("(goog.partial(f,a,b))(c)", "f(a,b,c)"); test("((function(){}).bind())()", "((function(){}))()"); test("((function(){}).bind(a))()", "((function(){})).call(a)"); test("((function(){}).bind(a,b))()", "((function(){})).call(a,b)"); test("((function(){}).bind())(a)", "((function(){}))(a)"); test("((function(){}).bind(a))(b)", "((function(){})).call(a,b)"); test("((function(){}).bind(a,b))(c)", "((function(){})).call(a,b,c)"); // Without using type information we don't know "f" is a function. testSame("(f.bind())()"); testSame("(f.bind(a))()"); testSame("(f.bind())(a)"); testSame("(f.bind(a))(b)"); // Don't rewrite if the bind isn't the immediate call target testSame("(goog.bind(f)).call(g)"); } public void testBindToCall2() { test("(goog$bind(f))()", "f()"); test("(goog$bind(f,a))()", "f.call(a)"); test("(goog$bind(f,a,b))()", "f.call(a,b)"); test("(goog$bind(f))(a)", "f(a)"); test("(goog$bind(f,a))(b)", "f.call(a,b)"); test("(goog$bind(f,a,b))(c)", "f.call(a,b,c)"); test("(goog$partial(f))()", "f()"); test("(goog$partial(f,a))()", "f(a)"); test("(goog$partial(f,a,b))()", "f(a,b)"); test("(goog$partial(f))(a)", "f(a)"); test("(goog$partial(f,a))(b)", "f(a,b)"); test("(goog$partial(f,a,b))(c)", "f(a,b,c)"); // Don't rewrite if the bind isn't the immediate call target testSame("(goog$bind(f)).call(g)"); } public void testBindToCall3() { // TODO(johnlenz): The code generator wraps free calls with (0,...) to // prevent leaking "this", but the parser doesn't unfold it, making a // AST comparison fail. For now do a string comparison to validate the // correct code is in fact generated. // The FREE call wrapping should be moved out of the code generator // and into a denormalizing pass. new StringCompareTestCase().testBindToCall3(); } public void testSimpleFunctionCall() { test("var a = String(23)", "var a = '' + 23"); test("var a = String('hello')", "var a = '' + 'hello'"); testSame("var a = String('hello', bar());"); testSame("var a = String({valueOf: function() { return 1; }});"); } private static class StringCompareTestCase extends CompilerTestCase { StringCompareTestCase() { super("", false); } @Override protected CompilerPass getProcessor(Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeSubstituteAlternateSyntax(false)); return peepholePass; } public void testBindToCall3() { test("(goog.bind(f.m))()", "(0,f.m)()"); test("(goog.bind(f.m,a))()", "f.m.call(a)"); test("(goog.bind(f.m))(a)", "(0,f.m)(a)"); test("(goog.bind(f.m,a))(b)", "f.m.call(a,b)"); test("(goog.partial(f.m))()", "(0,f.m)()"); test("(goog.partial(f.m,a))()", "(0,f.m)(a)"); test("(goog.partial(f.m))(a)", "(0,f.m)(a)"); test("(goog.partial(f.m,a))(b)", "(0,f.m)(a,b)"); // Without using type information we don't know "f" is a function. testSame("f.m.bind()()"); testSame("f.m.bind(a)()"); testSame("f.m.bind()(a)"); testSame("f.m.bind(a)(b)"); // Don't rewrite if the bind isn't the immediate call target testSame("goog.bind(f.m).call(g)"); } } }
public void testExternalIssue1053() { testSame( "var u; function f() { u = Random(); var x = u; f(); alert(x===u)}"); }
com.google.javascript.jscomp.InlineVariablesTest::testExternalIssue1053
test/com/google/javascript/jscomp/InlineVariablesTest.java
1,070
test/com/google/javascript/jscomp/InlineVariablesTest.java
testExternalIssue1053
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Verifies that valid candidates for inlining are inlined, but * that no dangerous inlining occurs. * * @author kushal@google.com (Kushal Dave) */ public class InlineVariablesTest extends CompilerTestCase { private boolean inlineAllStrings = false; private boolean inlineLocalsOnly = false; public InlineVariablesTest() { enableNormalize(); } @Override public void setUp() { super.enableLineNumberCheck(true); } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new InlineVariables( compiler, (inlineLocalsOnly) ? InlineVariables.Mode.LOCALS_ONLY : InlineVariables.Mode.ALL, inlineAllStrings); } @Override public void tearDown() { inlineAllStrings = false; inlineLocalsOnly = false; } // Test respect for scopes and blocks public void testInlineGlobal() { test("var x = 1; var z = x;", "var z = 1;"); } public void testNoInlineExportedName() { testSame("var _x = 1; var z = _x;"); } public void testNoInlineExportedName2() { testSame("var f = function() {}; var _x = f;" + "var y = function() { _x(); }; var _y = f;"); } public void testDoNotInlineIncrement() { testSame("var x = 1; x++;"); } public void testDoNotInlineDecrement() { testSame("var x = 1; x--;"); } public void testDoNotInlineIntoLhsOfAssign() { testSame("var x = 1; x += 3;"); } public void testInlineIntoRhsOfAssign() { test("var x = 1; var y = x;", "var y = 1;"); } public void testInlineInFunction() { test("function baz() { var x = 1; var z = x; }", "function baz() { var z = 1; }"); } public void testInlineInFunction2() { test("function baz() { " + "var a = new obj();"+ "result = a;" + "}", "function baz() { " + "result = new obj()" + "}"); } public void testInlineInFunction3() { testSame( "function baz() { " + "var a = new obj();" + "(function(){a;})();" + "result = a;" + "}"); } public void testInlineInFunction4() { testSame( "function baz() { " + "var a = new obj();" + "foo.result = a;" + "}"); } public void testInlineInFunction5() { testSame( "function baz() { " + "var a = (foo = new obj());" + "foo.x();" + "result = a;" + "}"); } public void testInlineAcrossModules() { // TODO(kushal): Make decision about overlap with CrossModuleCodeMotion test(createModules("var a = 2;", "var b = a;"), new String[] { "", "var b = 2;" }); } public void testDoNotExitConditional1() { testSame("if (true) { var x = 1; } var z = x;"); } public void testDoNotExitConditional2() { testSame("if (true) var x = 1; var z = x;"); } public void testDoNotExitConditional3() { testSame("var x; if (true) x=1; var z = x;"); } public void testDoNotExitLoop() { testSame("while (z) { var x = 3; } var y = x;"); } public void testDoNotExitForLoop() { test("for (var i = 1; false; false) var z = i;", "for (;false;false) var z = 1;"); testSame("for (; false; false) var i = 1; var z = i;"); testSame("for (var i in {}); var z = i;"); } public void testDoNotEnterSubscope() { testSame( "var x = function() {" + " var self = this; " + " return function() { var y = self; };" + "}"); testSame( "var x = function() {" + " var y = [1]; " + " return function() { var z = y; };" + "}"); } public void testDoNotExitTry() { testSame("try { var x = y; } catch (e) {} var z = y; "); testSame("try { throw e; var x = 1; } catch (e) {} var z = x; "); } public void testDoNotEnterCatch() { testSame("try { } catch (e) { var z = e; } "); } public void testDoNotEnterFinally() { testSame("try { throw e; var x = 1; } catch (e) {} " + "finally { var z = x; } "); } public void testInsideIfConditional() { test("var a = foo(); if (a) { alert(3); }", "if (foo()) { alert(3); }"); test("var a; a = foo(); if (a) { alert(3); }", "if (foo()) { alert(3); }"); } public void testOnlyReadAtInitialization() { test("var a; a = foo();", "foo();"); test("var a; if (a = foo()) { alert(3); }", "if (foo()) { alert(3); }"); test("var a; switch (a = foo()) {}", "switch(foo()) {}"); test("var a; function f(){ return a = foo(); }", "function f(){ return foo(); }"); test("function f(){ var a; return a = foo(); }", "function f(){ return foo(); }"); test("var a; with (a = foo()) { alert(3); }", "with (foo()) { alert(3); }"); test("var a; b = (a = foo());", "b = foo();"); test("var a; while(a = foo()) { alert(3); }", "while(foo()) { alert(3); }"); test("var a; for(;a = foo();) { alert(3); }", "for(;foo();) { alert(3); }"); test("var a; do {} while(a = foo()) { alert(3); }", "do {} while(foo()) { alert(3); }"); } public void testImmutableWithSingleReferenceAfterInitialzation() { test("var a; a = 1;", "1;"); test("var a; if (a = 1) { alert(3); }", "if (1) { alert(3); }"); test("var a; switch (a = 1) {}", "switch(1) {}"); test("var a; function f(){ return a = 1; }", "function f(){ return 1; }"); test("function f(){ var a; return a = 1; }", "function f(){ return 1; }"); test("var a; with (a = 1) { alert(3); }", "with (1) { alert(3); }"); test("var a; b = (a = 1);", "b = 1;"); test("var a; while(a = 1) { alert(3); }", "while(1) { alert(3); }"); test("var a; for(;a = 1;) { alert(3); }", "for(;1;) { alert(3); }"); test("var a; do {} while(a = 1) { alert(3); }", "do {} while(1) { alert(3); }"); } public void testSingleReferenceAfterInitialzation() { test("var a; a = foo();a;", "foo();"); testSame("var a; if (a = foo()) { alert(3); } a;"); testSame("var a; switch (a = foo()) {} a;"); testSame("var a; function f(){ return a = foo(); } a;"); testSame("function f(){ var a; return a = foo(); a;}"); testSame("var a; with (a = foo()) { alert(3); } a;"); testSame("var a; b = (a = foo()); a;"); testSame("var a; while(a = foo()) { alert(3); } a;"); testSame("var a; for(;a = foo();) { alert(3); } a;"); testSame("var a; do {} while(a = foo()) { alert(3); } a;"); } public void testInsideIfBranch() { testSame("var a = foo(); if (1) { alert(a); }"); } public void testInsideAndConditional() { test("var a = foo(); a && alert(3);", "foo() && alert(3);"); } public void testInsideAndBranch() { testSame("var a = foo(); 1 && alert(a);"); } public void testInsideOrBranch() { testSame("var a = foo(); 1 || alert(a);"); } public void testInsideHookBranch() { testSame("var a = foo(); 1 ? alert(a) : alert(3)"); } public void testInsideHookConditional() { test("var a = foo(); a ? alert(1) : alert(3)", "foo() ? alert(1) : alert(3)"); } public void testInsideOrBranchInsideIfConditional() { testSame("var a = foo(); if (x || a) {}"); } public void testInsideOrBranchInsideIfConditionalWithConstant() { // We don't inline non-immutable constants into branches. testSame("var a = [false]; if (x || a) {}"); } public void testCrossFunctionsAsLeftLeaves() { // Ensures getNext() understands how to walk past a function leaf test( new String[] { "var x = function() {};", "", "function cow() {} var z = x;"}, new String[] { "", "", "function cow() {} var z = function() {};" }); test( new String[] { "var x = function() {};", "", "var cow = function() {}; var z = x;"}, new String[] { "", "", "var cow = function() {}; var z = function() {};" }); testSame( new String[] { "var x = a;", "", "(function() { a++; })(); var z = x;"}); test( new String[] { "var x = a;", "", "function cow() { a++; }; cow(); var z = x;"}, new String[] { "var x = a;", "", ";(function cow(){ a++; })(); var z = x;"}); testSame( new String[] { "var x = a;", "", "cow(); var z = x; function cow() { a++; };"}); } // Test movement of constant values public void testDoCrossFunction() { // We know foo() does not affect x because we require that x is only // referenced twice. test("var x = 1; foo(); var z = x;", "foo(); var z = 1;"); } public void testDoNotCrossReferencingFunction() { testSame( "var f = function() { var z = x; };" + "var x = 1;" + "f();" + "var z = x;" + "f();"); } // Test tricky declarations and references public void testChainedAssignment() { test("var a = 2, b = 2; var c = b;", "var a = 2; var c = 2;"); test("var a = 2, b = 2; var c = a;", "var b = 2; var c = 2;"); test("var a = b = 2; var f = 3; var c = a;", "var f = 3; var c = b = 2;"); testSame("var a = b = 2; var c = b;"); } public void testForIn() { testSame("for (var i in j) { var c = i; }"); testSame("var i = 0; for (i in j) ;"); testSame("var i = 0; for (i in j) { var c = i; }"); testSame("i = 0; for (var i in j) { var c = i; }"); testSame("var j = {'key':'value'}; for (var i in j) {print(i)};"); } // Test movement of values that have (may) side effects public void testDoCrossNewVariables() { test("var x = foo(); var z = x;", "var z = foo();"); } public void testDoNotCrossFunctionCalls() { testSame("var x = foo(); bar(); var z = x;"); } // Test movement of values that are complex but lack side effects public void testDoNotCrossAssignment() { testSame("var x = {}; var y = x.a; x.a = 1; var z = y;"); testSame("var a = this.id; foo(this.id = 3, a);"); } public void testDoNotCrossDelete() { testSame("var x = {}; var y = x.a; delete x.a; var z = y;"); } public void testDoNotCrossAssignmentPlus() { testSame("var a = b; b += 2; var c = a;"); } public void testDoNotCrossIncrement() { testSame("var a = b.c; b.c++; var d = a;"); } public void testDoNotCrossConstructor() { testSame("var a = b; new Foo(); var c = a;"); } public void testDoCrossVar() { // Assumes we do not rely on undefined variables (not technically correct!) test("var a = b; var b = 3; alert(a)", "alert(3);"); } public void testOverlappingInlines() { String source = "a = function(el, x, opt_y) { " + " var cur = bar(el); " + " opt_y = x.y; " + " x = x.x; " + " var dx = x - cur.x; " + " var dy = opt_y - cur.y;" + " foo(el, el.offsetLeft + dx, el.offsetTop + dy); " + "};"; String expected = "a = function(el, x, opt_y) { " + " var cur = bar(el); " + " opt_y = x.y; " + " x = x.x; " + " foo(el, el.offsetLeft + (x - cur.x)," + " el.offsetTop + (opt_y - cur.y)); " + "};"; test(source, expected); } public void testOverlappingInlineFunctions() { String source = "a = function() { " + " var b = function(args) {var n;}; " + " var c = function(args) {}; " + " d(b,c); " + "};"; String expected = "a = function() { " + " d(function(args){var n;}, function(args){}); " + "};"; test(source, expected); } public void testInlineIntoLoops() { test("var x = true; while (true) alert(x);", "while (true) alert(true);"); test("var x = true; while (true) for (var i in {}) alert(x);", "while (true) for (var i in {}) alert(true);"); testSame("var x = [true]; while (true) alert(x);"); } public void testInlineIntoFunction() { test("var x = false; var f = function() { alert(x); };", "var f = function() { alert(false); };"); testSame("var x = [false]; var f = function() { alert(x); };"); } public void testNoInlineIntoNamedFunction() { testSame("f(); var x = false; function f() { alert(x); };"); } public void testInlineIntoNestedNonHoistedNamedFunctions() { test("f(); var x = false; if (false) function f() { alert(x); };", "f(); if (false) function f() { alert(false); };"); } public void testNoInlineIntoNestedNamedFunctions() { testSame("f(); var x = false; function f() { if (false) { alert(x); } };"); } public void testNoInlineMutatedVariable() { testSame("var x = false; if (true) { var y = x; x = true; }"); } public void testInlineImmutableMultipleTimes() { test("var x = null; var y = x, z = x;", "var y = null, z = null;"); test("var x = 3; var y = x, z = x;", "var y = 3, z = 3;"); } public void testNoInlineStringMultipleTimesIfNotWorthwhile() { testSame("var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;"); } public void testInlineStringMultipleTimesWhenAliasingAllStrings() { inlineAllStrings = true; test("var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;", "var y = 'abcdefghijklmnopqrstuvwxyz', " + " z = 'abcdefghijklmnopqrstuvwxyz';"); } public void testNoInlineBackwards() { testSame("var y = x; var x = null;"); } public void testNoInlineOutOfBranch() { testSame("if (true) var x = null; var y = x;"); } public void testInterferingInlines() { test("var a = 3; var f = function() { var x = a; alert(x); };", "var f = function() { alert(3); };"); } public void testInlineIntoTryCatch() { test("var a = true; " + "try { var b = a; } " + "catch (e) { var c = a + b; var d = true; } " + "finally { var f = a + b + c + d; }", "try { var b = true; } " + "catch (e) { var c = true + b; var d = true; } " + "finally { var f = true + b + c + d; }"); } // Make sure that we still inline constants that are not provably // written before they're read. public void testInlineConstants() { test("function foo() { return XXX; } var XXX = true;", "function foo() { return true; }"); } public void testInlineStringWhenWorthwhile() { test("var x = 'a'; foo(x, x, x);", "foo('a', 'a', 'a');"); } public void testInlineConstantAlias() { test("var XXX = new Foo(); q(XXX); var YYY = XXX; bar(YYY)", "var XXX = new Foo(); q(XXX); bar(XXX)"); } public void testInlineConstantAliasWithAnnotation() { test("/** @const */ var xxx = new Foo(); q(xxx); var YYY = xxx; bar(YYY)", "/** @const */ var xxx = new Foo(); q(xxx); bar(xxx)"); } public void testInlineConstantAliasWithNonConstant() { test("var XXX = new Foo(); q(XXX); var y = XXX; bar(y); baz(y)", "var XXX = new Foo(); q(XXX); bar(XXX); baz(XXX)"); } public void testCascadingInlines() { test("var XXX = 4; " + "function f() { var YYY = XXX; bar(YYY); baz(YYY); }", "function f() { bar(4); baz(4); }"); } public void testNoInlineGetpropIntoCall() { test("var a = b; a();", "b();"); test("var a = b.c; f(a);", "f(b.c);"); testSame("var a = b.c; a();"); } public void testInlineFunctionDeclaration() { test("var f = function () {}; var a = f;", "var a = function () {};"); test("var f = function () {}; foo(); var a = f;", "foo(); var a = function () {};"); test("var f = function () {}; foo(f);", "foo(function () {});"); testSame("var f = function () {}; function g() {var a = f;}"); testSame("var f = function () {}; function g() {h(f);}"); } public void test2388531() { testSame("var f = function () {};" + "var g = function () {};" + "goog.inherits(f, g);"); testSame("var f = function () {};" + "var g = function () {};" + "goog$inherits(f, g);"); } public void testRecursiveFunction1() { testSame("var x = 0; (function x() { return x ? x() : 3; })();"); } public void testRecursiveFunction2() { testSame("function y() { return y(); }"); } public void testUnreferencedBleedingFunction() { testSame("var x = function y() {}"); } public void testReferencedBleedingFunction() { testSame("var x = function y() { return y(); }"); } public void testInlineAliases1() { test("var x = this.foo(); this.bar(); var y = x; this.baz(y);", "var x = this.foo(); this.bar(); this.baz(x);"); } public void testInlineAliases1b() { test("var x = this.foo(); this.bar(); var y; y = x; this.baz(y);", "var x = this.foo(); this.bar(); x; this.baz(x);"); } public void testInlineAliases1c() { test("var x; x = this.foo(); this.bar(); var y = x; this.baz(y);", "var x; x = this.foo(); this.bar(); this.baz(x);"); } public void testInlineAliases1d() { test("var x; x = this.foo(); this.bar(); var y; y = x; this.baz(y);", "var x; x = this.foo(); this.bar(); x; this.baz(x);"); } public void testInlineAliases2() { test("var x = this.foo(); this.bar(); " + "function f() { var y = x; this.baz(y); }", "var x = this.foo(); this.bar(); function f() { this.baz(x); }"); } public void testInlineAliases2b() { test("var x = this.foo(); this.bar(); " + "function f() { var y; y = x; this.baz(y); }", "var x = this.foo(); this.bar(); function f() { this.baz(x); }"); } public void testInlineAliases2c() { test("var x; x = this.foo(); this.bar(); " + "function f() { var y = x; this.baz(y); }", "var x; x = this.foo(); this.bar(); function f() { this.baz(x); }"); } public void testInlineAliases2d() { test("var x; x = this.foo(); this.bar(); " + "function f() { var y; y = x; this.baz(y); }", "var x; x = this.foo(); this.bar(); function f() { this.baz(x); }"); } public void testInlineAliasesInLoop() { test( "function f() { " + " var x = extern();" + " for (var i = 0; i < 5; i++) {" + " (function() {" + " var y = x; window.setTimeout(function() { extern(y); }, 0);" + " })();" + " }" + "}", "function f() { " + " var x = extern();" + " for (var i = 0; i < 5; i++) {" + " (function() {" + " window.setTimeout(function() { extern(x); }, 0);" + " })();" + " }" + "}"); } public void testNoInlineAliasesInLoop() { testSame( "function f() { " + " for (var i = 0; i < 5; i++) {" + " var x = extern();" + " (function() {" + " var y = x; window.setTimeout(function() { extern(y); }, 0);" + " })();" + " }" + "}"); } public void testNoInlineAliases1() { testSame( "var x = this.foo(); this.bar(); var y = x; x = 3; this.baz(y);"); } public void testNoInlineAliases1b() { testSame( "var x = this.foo(); this.bar(); var y; y = x; x = 3; this.baz(y);"); } public void testNoInlineAliases2() { testSame( "var x = this.foo(); this.bar(); var y = x; y = 3; this.baz(y); "); } public void testNoInlineAliases2b() { testSame( "var x = this.foo(); this.bar(); var y; y = x; y = 3; this.baz(y); "); } public void testNoInlineAliases3() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y = x; g(); this.baz(y); } " + "function g() { x = 3; }"); } public void testNoInlineAliases3b() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y; y = x; g(); this.baz(y); } " + "function g() { x = 3; }"); } public void testNoInlineAliases4() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y = x; y = 3; this.baz(y); }"); } public void testNoInlineAliases4b() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y; y = x; y = 3; this.baz(y); }"); } public void testNoInlineAliases5() { testSame( "var x = this.foo(); this.bar(); var y = x; this.bing();" + "this.baz(y); x = 3;"); } public void testNoInlineAliases5b() { testSame( "var x = this.foo(); this.bar(); var y; y = x; this.bing();" + "this.baz(y); x = 3;"); } public void testNoInlineAliases6() { testSame( "var x = this.foo(); this.bar(); var y = x; this.bing();" + "this.baz(y); y = 3;"); } public void testNoInlineAliases6b() { testSame( "var x = this.foo(); this.bar(); var y; y = x; this.bing();" + "this.baz(y); y = 3;"); } public void testNoInlineAliases7() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y = x; this.bing(); this.baz(y); x = 3; }"); } public void testNoInlineAliases7b() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y; y = x; this.bing(); this.baz(y); x = 3; }"); } public void testNoInlineAliases8() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y = x; this.baz(y); y = 3; }"); } public void testNoInlineAliases8b() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y; y = x; this.baz(y); y = 3; }"); } public void testSideEffectOrder() { // z can not be changed by the call to y, so x can be inlined. String EXTERNS = "var z; function f(){}"; test(EXTERNS, "var x = f(y.a, y); z = x;", "z = f(y.a, y);", null, null); // z.b can be changed by the call to y, so x can not be inlined. testSame(EXTERNS, "var x = f(y.a, y); z.b = x;", null, null); } public void testInlineParameterAlias1() { test( "function f(x) {" + " var y = x;" + " g();" + " y;y;" + "}", "function f(x) {" + " g();" + " x;x;" + "}" ); } public void testInlineParameterAlias2() { test( "function f(x) {" + " var y; y = x;" + " g();" + " y;y;" + "}", "function f(x) {" + " x;" + " g();" + " x;x;" + "}" ); } public void testInlineFunctionAlias1a() { test( "function f(x) {}" + "var y = f;" + "g();" + "y();y();", "var y = function f(x) {};" + "g();" + "y();y();" ); } public void testInlineFunctionAlias1b() { test( "function f(x) {};" + "f;var y = f;" + "g();" + "y();y();", "function f(x) {};" + "f;g();" + "f();f();" ); } public void testInlineFunctionAlias2a() { test( "function f(x) {}" + "var y; y = f;" + "g();" + "y();y();", "var y; y = function f(x) {};" + "g();" + "y();y();" ); } public void testInlineFunctionAlias2b() { test( "function f(x) {};" + "f; var y; y = f;" + "g();" + "y();y();", "function f(x) {};" + "f; f;" + "g();" + "f();f();" ); } public void testInlineCatchAlias1() { test( "try {" + "} catch (e) {" + " var y = e;" + " g();" + " y;y;" + "}", "try {" + "} catch (e) {" + " g();" + " e;e;" + "}" ); } public void testInlineCatchAlias2() { test( "try {" + "} catch (e) {" + " var y; y = e;" + " g();" + " y;y;" + "}", "try {" + "} catch (e) {" + " e;" + " g();" + " e;e;" + "}" ); } public void testLocalsOnly1() { inlineLocalsOnly = true; test( "var x=1; x; function f() {var x = 1; x;}", "var x=1; x; function f() {1;}"); } public void testLocalsOnly2() { inlineLocalsOnly = true; test( "/** @const */\n" + "var X=1; X;\n" + "function f() {\n" + " /** @const */\n" + " var X = 1; X;\n" + "}", "var X=1; X; function f() {1;}"); } public void testInlineUndefined1() { test("var x; x;", "void 0;"); } public void testInlineUndefined2() { testSame("var x; x++;"); } public void testInlineUndefined3() { testSame("var x; var x;"); } public void testInlineUndefined4() { test("var x; x; x;", "void 0; void 0;"); } public void testInlineUndefined5() { test("var x; for(x in a) {}", "var x; for(x in a) {}"); } public void testIssue90() { test("var x; x && alert(1)", "void 0 && alert(1)"); } public void testRenamePropertyFunction() { testSame("var JSCompiler_renameProperty; " + "JSCompiler_renameProperty('foo')"); } public void testThisAlias() { test("function f() { var a = this; a.y(); a.z(); }", "function f() { this.y(); this.z(); }"); } public void testThisEscapedAlias() { testSame( "function f() { var a = this; var g = function() { a.y(); }; a.z(); }"); } public void testInlineNamedFunction() { test("function f() {} f();", "(function f(){})()"); } public void testIssue378ModifiedArguments1() { testSame( "function g(callback) {\n" + " var f = callback;\n" + " arguments[0] = this;\n" + " f.apply(this, arguments);\n" + "}"); } public void testIssue378ModifiedArguments2() { testSame( "function g(callback) {\n" + " /** @const */\n" + " var f = callback;\n" + " arguments[0] = this;\n" + " f.apply(this, arguments);\n" + "}"); } public void testIssue378EscapedArguments1() { testSame( "function g(callback) {\n" + " var f = callback;\n" + " h(arguments,this);\n" + " f.apply(this, arguments);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}"); } public void testIssue378EscapedArguments2() { testSame( "function g(callback) {\n" + " /** @const */\n" + " var f = callback;\n" + " h(arguments,this);\n" + " f.apply(this);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}"); } public void testIssue378EscapedArguments3() { test( "function g(callback) {\n" + " var f = callback;\n" + " f.apply(this, arguments);\n" + "}\n", "function g(callback) {\n" + " callback.apply(this, arguments);\n" + "}\n"); } public void testIssue378EscapedArguments4() { testSame( "function g(callback) {\n" + " var f = callback;\n" + " h(arguments[0],this);\n" + " f.apply(this, arguments);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}"); } public void testIssue378ArgumentsRead1() { test( "function g(callback) {\n" + " var f = callback;\n" + " var g = arguments[0];\n" + " f.apply(this, arguments);\n" + "}", "function g(callback) {\n" + " var g = arguments[0];\n" + " callback.apply(this, arguments);\n" + "}"); } public void testIssue378ArgumentsRead2() { test( "function g(callback) {\n" + " var f = callback;\n" + " h(arguments[0],this);\n" + " f.apply(this, arguments[0]);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}", "function g(callback) {\n" + " h(arguments[0],this);\n" + " callback.apply(this, arguments[0]);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}"); } public void testArgumentsModifiedInOuterFunction() { test( "function g(callback) {\n" + " var f = callback;\n" + " arguments[0] = this;\n" + " f.apply(this, arguments);\n" + " function inner(callback) {" + " var x = callback;\n" + " x.apply(this);\n" + " }" + "}", "function g(callback) {\n" + " var f = callback;\n" + " arguments[0] = this;\n" + " f.apply(this, arguments);\n" + " function inner(callback) {" + " callback.apply(this);\n" + " }" + "}"); } public void testArgumentsModifiedInInnerFunction() { test( "function g(callback) {\n" + " var f = callback;\n" + " f.apply(this, arguments);\n" + " function inner(callback) {" + " var x = callback;\n" + " arguments[0] = this;\n" + " x.apply(this);\n" + " }" + "}", "function g(callback) {\n" + " callback.apply(this, arguments);\n" + " function inner(callback) {" + " var x = callback;\n" + " arguments[0] = this;\n" + " x.apply(this);\n" + " }" + "}"); } public void testNoInlineRedeclaredExterns() { String externs = "var test = 1;"; String code = "/** @suppress {duplicate} */ var test = 2;alert(test);"; test(externs, code, code, null, null); } public void testBug6598844() { testSame( "function F() { this.a = 0; }" + "F.prototype.inc = function() { this.a++; return 10; };" + "F.prototype.bar = function() { var x = this.inc(); this.a += x; };"); } public void testExternalIssue1053() { testSame( "var u; function f() { u = Random(); var x = u; f(); alert(x===u)}"); } }
// You are a professional Java test case writer, please create a test case named `testExternalIssue1053` for the issue `Closure-1053`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1053 // // ## Issue-Title: // Overzealous optimization confuses variables // // ## Issue-Description: // The following code: // // // ==ClosureCompiler== // // @compilation\_level ADVANCED\_OPTIMIZATIONS // // ==/ClosureCompiler== // var uid; // function reset() { // uid = Math.random(); // } // function doStuff() { // reset(); // var \_uid = uid; // // if (uid < 0.5) { // doStuff(); // } // // if (\_uid !== uid) { // throw 'reset() was called'; // } // } // doStuff(); // // ...gets optimized to: // // var a;function b(){a=Math.random();0.5>a&&b();if(a!==a)throw"reset() was called";}b(); // // Notice how \_uid gets optimized away and (uid!==\_uid) becomes (a!==a) even though doStuff() might have been called and uid's value may have changed and become different from \_uid. // // As an aside, replacing the declaration with "var \_uid = +uid;" fixes it, as does adding an extra "uid = \_uid" after "var \_uid = uid". // // public void testExternalIssue1053() {
1,070
120
1,067
test/com/google/javascript/jscomp/InlineVariablesTest.java
test
```markdown ## Issue-ID: Closure-1053 ## Issue-Title: Overzealous optimization confuses variables ## Issue-Description: The following code: // ==ClosureCompiler== // @compilation\_level ADVANCED\_OPTIMIZATIONS // ==/ClosureCompiler== var uid; function reset() { uid = Math.random(); } function doStuff() { reset(); var \_uid = uid; if (uid < 0.5) { doStuff(); } if (\_uid !== uid) { throw 'reset() was called'; } } doStuff(); ...gets optimized to: var a;function b(){a=Math.random();0.5>a&&b();if(a!==a)throw"reset() was called";}b(); Notice how \_uid gets optimized away and (uid!==\_uid) becomes (a!==a) even though doStuff() might have been called and uid's value may have changed and become different from \_uid. As an aside, replacing the declaration with "var \_uid = +uid;" fixes it, as does adding an extra "uid = \_uid" after "var \_uid = uid". ``` You are a professional Java test case writer, please create a test case named `testExternalIssue1053` for the issue `Closure-1053`, utilizing the provided issue report information and the following function signature. ```java public void testExternalIssue1053() { ```
1,067
[ "com.google.javascript.jscomp.ReferenceCollectingCallback" ]
0b1e20643f18c1d4b2d447b868dc0741f9002554dc8286d52f2b5af3d6439a05
public void testExternalIssue1053()
// You are a professional Java test case writer, please create a test case named `testExternalIssue1053` for the issue `Closure-1053`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1053 // // ## Issue-Title: // Overzealous optimization confuses variables // // ## Issue-Description: // The following code: // // // ==ClosureCompiler== // // @compilation\_level ADVANCED\_OPTIMIZATIONS // // ==/ClosureCompiler== // var uid; // function reset() { // uid = Math.random(); // } // function doStuff() { // reset(); // var \_uid = uid; // // if (uid < 0.5) { // doStuff(); // } // // if (\_uid !== uid) { // throw 'reset() was called'; // } // } // doStuff(); // // ...gets optimized to: // // var a;function b(){a=Math.random();0.5>a&&b();if(a!==a)throw"reset() was called";}b(); // // Notice how \_uid gets optimized away and (uid!==\_uid) becomes (a!==a) even though doStuff() might have been called and uid's value may have changed and become different from \_uid. // // As an aside, replacing the declaration with "var \_uid = +uid;" fixes it, as does adding an extra "uid = \_uid" after "var \_uid = uid". // //
Closure
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Verifies that valid candidates for inlining are inlined, but * that no dangerous inlining occurs. * * @author kushal@google.com (Kushal Dave) */ public class InlineVariablesTest extends CompilerTestCase { private boolean inlineAllStrings = false; private boolean inlineLocalsOnly = false; public InlineVariablesTest() { enableNormalize(); } @Override public void setUp() { super.enableLineNumberCheck(true); } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new InlineVariables( compiler, (inlineLocalsOnly) ? InlineVariables.Mode.LOCALS_ONLY : InlineVariables.Mode.ALL, inlineAllStrings); } @Override public void tearDown() { inlineAllStrings = false; inlineLocalsOnly = false; } // Test respect for scopes and blocks public void testInlineGlobal() { test("var x = 1; var z = x;", "var z = 1;"); } public void testNoInlineExportedName() { testSame("var _x = 1; var z = _x;"); } public void testNoInlineExportedName2() { testSame("var f = function() {}; var _x = f;" + "var y = function() { _x(); }; var _y = f;"); } public void testDoNotInlineIncrement() { testSame("var x = 1; x++;"); } public void testDoNotInlineDecrement() { testSame("var x = 1; x--;"); } public void testDoNotInlineIntoLhsOfAssign() { testSame("var x = 1; x += 3;"); } public void testInlineIntoRhsOfAssign() { test("var x = 1; var y = x;", "var y = 1;"); } public void testInlineInFunction() { test("function baz() { var x = 1; var z = x; }", "function baz() { var z = 1; }"); } public void testInlineInFunction2() { test("function baz() { " + "var a = new obj();"+ "result = a;" + "}", "function baz() { " + "result = new obj()" + "}"); } public void testInlineInFunction3() { testSame( "function baz() { " + "var a = new obj();" + "(function(){a;})();" + "result = a;" + "}"); } public void testInlineInFunction4() { testSame( "function baz() { " + "var a = new obj();" + "foo.result = a;" + "}"); } public void testInlineInFunction5() { testSame( "function baz() { " + "var a = (foo = new obj());" + "foo.x();" + "result = a;" + "}"); } public void testInlineAcrossModules() { // TODO(kushal): Make decision about overlap with CrossModuleCodeMotion test(createModules("var a = 2;", "var b = a;"), new String[] { "", "var b = 2;" }); } public void testDoNotExitConditional1() { testSame("if (true) { var x = 1; } var z = x;"); } public void testDoNotExitConditional2() { testSame("if (true) var x = 1; var z = x;"); } public void testDoNotExitConditional3() { testSame("var x; if (true) x=1; var z = x;"); } public void testDoNotExitLoop() { testSame("while (z) { var x = 3; } var y = x;"); } public void testDoNotExitForLoop() { test("for (var i = 1; false; false) var z = i;", "for (;false;false) var z = 1;"); testSame("for (; false; false) var i = 1; var z = i;"); testSame("for (var i in {}); var z = i;"); } public void testDoNotEnterSubscope() { testSame( "var x = function() {" + " var self = this; " + " return function() { var y = self; };" + "}"); testSame( "var x = function() {" + " var y = [1]; " + " return function() { var z = y; };" + "}"); } public void testDoNotExitTry() { testSame("try { var x = y; } catch (e) {} var z = y; "); testSame("try { throw e; var x = 1; } catch (e) {} var z = x; "); } public void testDoNotEnterCatch() { testSame("try { } catch (e) { var z = e; } "); } public void testDoNotEnterFinally() { testSame("try { throw e; var x = 1; } catch (e) {} " + "finally { var z = x; } "); } public void testInsideIfConditional() { test("var a = foo(); if (a) { alert(3); }", "if (foo()) { alert(3); }"); test("var a; a = foo(); if (a) { alert(3); }", "if (foo()) { alert(3); }"); } public void testOnlyReadAtInitialization() { test("var a; a = foo();", "foo();"); test("var a; if (a = foo()) { alert(3); }", "if (foo()) { alert(3); }"); test("var a; switch (a = foo()) {}", "switch(foo()) {}"); test("var a; function f(){ return a = foo(); }", "function f(){ return foo(); }"); test("function f(){ var a; return a = foo(); }", "function f(){ return foo(); }"); test("var a; with (a = foo()) { alert(3); }", "with (foo()) { alert(3); }"); test("var a; b = (a = foo());", "b = foo();"); test("var a; while(a = foo()) { alert(3); }", "while(foo()) { alert(3); }"); test("var a; for(;a = foo();) { alert(3); }", "for(;foo();) { alert(3); }"); test("var a; do {} while(a = foo()) { alert(3); }", "do {} while(foo()) { alert(3); }"); } public void testImmutableWithSingleReferenceAfterInitialzation() { test("var a; a = 1;", "1;"); test("var a; if (a = 1) { alert(3); }", "if (1) { alert(3); }"); test("var a; switch (a = 1) {}", "switch(1) {}"); test("var a; function f(){ return a = 1; }", "function f(){ return 1; }"); test("function f(){ var a; return a = 1; }", "function f(){ return 1; }"); test("var a; with (a = 1) { alert(3); }", "with (1) { alert(3); }"); test("var a; b = (a = 1);", "b = 1;"); test("var a; while(a = 1) { alert(3); }", "while(1) { alert(3); }"); test("var a; for(;a = 1;) { alert(3); }", "for(;1;) { alert(3); }"); test("var a; do {} while(a = 1) { alert(3); }", "do {} while(1) { alert(3); }"); } public void testSingleReferenceAfterInitialzation() { test("var a; a = foo();a;", "foo();"); testSame("var a; if (a = foo()) { alert(3); } a;"); testSame("var a; switch (a = foo()) {} a;"); testSame("var a; function f(){ return a = foo(); } a;"); testSame("function f(){ var a; return a = foo(); a;}"); testSame("var a; with (a = foo()) { alert(3); } a;"); testSame("var a; b = (a = foo()); a;"); testSame("var a; while(a = foo()) { alert(3); } a;"); testSame("var a; for(;a = foo();) { alert(3); } a;"); testSame("var a; do {} while(a = foo()) { alert(3); } a;"); } public void testInsideIfBranch() { testSame("var a = foo(); if (1) { alert(a); }"); } public void testInsideAndConditional() { test("var a = foo(); a && alert(3);", "foo() && alert(3);"); } public void testInsideAndBranch() { testSame("var a = foo(); 1 && alert(a);"); } public void testInsideOrBranch() { testSame("var a = foo(); 1 || alert(a);"); } public void testInsideHookBranch() { testSame("var a = foo(); 1 ? alert(a) : alert(3)"); } public void testInsideHookConditional() { test("var a = foo(); a ? alert(1) : alert(3)", "foo() ? alert(1) : alert(3)"); } public void testInsideOrBranchInsideIfConditional() { testSame("var a = foo(); if (x || a) {}"); } public void testInsideOrBranchInsideIfConditionalWithConstant() { // We don't inline non-immutable constants into branches. testSame("var a = [false]; if (x || a) {}"); } public void testCrossFunctionsAsLeftLeaves() { // Ensures getNext() understands how to walk past a function leaf test( new String[] { "var x = function() {};", "", "function cow() {} var z = x;"}, new String[] { "", "", "function cow() {} var z = function() {};" }); test( new String[] { "var x = function() {};", "", "var cow = function() {}; var z = x;"}, new String[] { "", "", "var cow = function() {}; var z = function() {};" }); testSame( new String[] { "var x = a;", "", "(function() { a++; })(); var z = x;"}); test( new String[] { "var x = a;", "", "function cow() { a++; }; cow(); var z = x;"}, new String[] { "var x = a;", "", ";(function cow(){ a++; })(); var z = x;"}); testSame( new String[] { "var x = a;", "", "cow(); var z = x; function cow() { a++; };"}); } // Test movement of constant values public void testDoCrossFunction() { // We know foo() does not affect x because we require that x is only // referenced twice. test("var x = 1; foo(); var z = x;", "foo(); var z = 1;"); } public void testDoNotCrossReferencingFunction() { testSame( "var f = function() { var z = x; };" + "var x = 1;" + "f();" + "var z = x;" + "f();"); } // Test tricky declarations and references public void testChainedAssignment() { test("var a = 2, b = 2; var c = b;", "var a = 2; var c = 2;"); test("var a = 2, b = 2; var c = a;", "var b = 2; var c = 2;"); test("var a = b = 2; var f = 3; var c = a;", "var f = 3; var c = b = 2;"); testSame("var a = b = 2; var c = b;"); } public void testForIn() { testSame("for (var i in j) { var c = i; }"); testSame("var i = 0; for (i in j) ;"); testSame("var i = 0; for (i in j) { var c = i; }"); testSame("i = 0; for (var i in j) { var c = i; }"); testSame("var j = {'key':'value'}; for (var i in j) {print(i)};"); } // Test movement of values that have (may) side effects public void testDoCrossNewVariables() { test("var x = foo(); var z = x;", "var z = foo();"); } public void testDoNotCrossFunctionCalls() { testSame("var x = foo(); bar(); var z = x;"); } // Test movement of values that are complex but lack side effects public void testDoNotCrossAssignment() { testSame("var x = {}; var y = x.a; x.a = 1; var z = y;"); testSame("var a = this.id; foo(this.id = 3, a);"); } public void testDoNotCrossDelete() { testSame("var x = {}; var y = x.a; delete x.a; var z = y;"); } public void testDoNotCrossAssignmentPlus() { testSame("var a = b; b += 2; var c = a;"); } public void testDoNotCrossIncrement() { testSame("var a = b.c; b.c++; var d = a;"); } public void testDoNotCrossConstructor() { testSame("var a = b; new Foo(); var c = a;"); } public void testDoCrossVar() { // Assumes we do not rely on undefined variables (not technically correct!) test("var a = b; var b = 3; alert(a)", "alert(3);"); } public void testOverlappingInlines() { String source = "a = function(el, x, opt_y) { " + " var cur = bar(el); " + " opt_y = x.y; " + " x = x.x; " + " var dx = x - cur.x; " + " var dy = opt_y - cur.y;" + " foo(el, el.offsetLeft + dx, el.offsetTop + dy); " + "};"; String expected = "a = function(el, x, opt_y) { " + " var cur = bar(el); " + " opt_y = x.y; " + " x = x.x; " + " foo(el, el.offsetLeft + (x - cur.x)," + " el.offsetTop + (opt_y - cur.y)); " + "};"; test(source, expected); } public void testOverlappingInlineFunctions() { String source = "a = function() { " + " var b = function(args) {var n;}; " + " var c = function(args) {}; " + " d(b,c); " + "};"; String expected = "a = function() { " + " d(function(args){var n;}, function(args){}); " + "};"; test(source, expected); } public void testInlineIntoLoops() { test("var x = true; while (true) alert(x);", "while (true) alert(true);"); test("var x = true; while (true) for (var i in {}) alert(x);", "while (true) for (var i in {}) alert(true);"); testSame("var x = [true]; while (true) alert(x);"); } public void testInlineIntoFunction() { test("var x = false; var f = function() { alert(x); };", "var f = function() { alert(false); };"); testSame("var x = [false]; var f = function() { alert(x); };"); } public void testNoInlineIntoNamedFunction() { testSame("f(); var x = false; function f() { alert(x); };"); } public void testInlineIntoNestedNonHoistedNamedFunctions() { test("f(); var x = false; if (false) function f() { alert(x); };", "f(); if (false) function f() { alert(false); };"); } public void testNoInlineIntoNestedNamedFunctions() { testSame("f(); var x = false; function f() { if (false) { alert(x); } };"); } public void testNoInlineMutatedVariable() { testSame("var x = false; if (true) { var y = x; x = true; }"); } public void testInlineImmutableMultipleTimes() { test("var x = null; var y = x, z = x;", "var y = null, z = null;"); test("var x = 3; var y = x, z = x;", "var y = 3, z = 3;"); } public void testNoInlineStringMultipleTimesIfNotWorthwhile() { testSame("var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;"); } public void testInlineStringMultipleTimesWhenAliasingAllStrings() { inlineAllStrings = true; test("var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;", "var y = 'abcdefghijklmnopqrstuvwxyz', " + " z = 'abcdefghijklmnopqrstuvwxyz';"); } public void testNoInlineBackwards() { testSame("var y = x; var x = null;"); } public void testNoInlineOutOfBranch() { testSame("if (true) var x = null; var y = x;"); } public void testInterferingInlines() { test("var a = 3; var f = function() { var x = a; alert(x); };", "var f = function() { alert(3); };"); } public void testInlineIntoTryCatch() { test("var a = true; " + "try { var b = a; } " + "catch (e) { var c = a + b; var d = true; } " + "finally { var f = a + b + c + d; }", "try { var b = true; } " + "catch (e) { var c = true + b; var d = true; } " + "finally { var f = true + b + c + d; }"); } // Make sure that we still inline constants that are not provably // written before they're read. public void testInlineConstants() { test("function foo() { return XXX; } var XXX = true;", "function foo() { return true; }"); } public void testInlineStringWhenWorthwhile() { test("var x = 'a'; foo(x, x, x);", "foo('a', 'a', 'a');"); } public void testInlineConstantAlias() { test("var XXX = new Foo(); q(XXX); var YYY = XXX; bar(YYY)", "var XXX = new Foo(); q(XXX); bar(XXX)"); } public void testInlineConstantAliasWithAnnotation() { test("/** @const */ var xxx = new Foo(); q(xxx); var YYY = xxx; bar(YYY)", "/** @const */ var xxx = new Foo(); q(xxx); bar(xxx)"); } public void testInlineConstantAliasWithNonConstant() { test("var XXX = new Foo(); q(XXX); var y = XXX; bar(y); baz(y)", "var XXX = new Foo(); q(XXX); bar(XXX); baz(XXX)"); } public void testCascadingInlines() { test("var XXX = 4; " + "function f() { var YYY = XXX; bar(YYY); baz(YYY); }", "function f() { bar(4); baz(4); }"); } public void testNoInlineGetpropIntoCall() { test("var a = b; a();", "b();"); test("var a = b.c; f(a);", "f(b.c);"); testSame("var a = b.c; a();"); } public void testInlineFunctionDeclaration() { test("var f = function () {}; var a = f;", "var a = function () {};"); test("var f = function () {}; foo(); var a = f;", "foo(); var a = function () {};"); test("var f = function () {}; foo(f);", "foo(function () {});"); testSame("var f = function () {}; function g() {var a = f;}"); testSame("var f = function () {}; function g() {h(f);}"); } public void test2388531() { testSame("var f = function () {};" + "var g = function () {};" + "goog.inherits(f, g);"); testSame("var f = function () {};" + "var g = function () {};" + "goog$inherits(f, g);"); } public void testRecursiveFunction1() { testSame("var x = 0; (function x() { return x ? x() : 3; })();"); } public void testRecursiveFunction2() { testSame("function y() { return y(); }"); } public void testUnreferencedBleedingFunction() { testSame("var x = function y() {}"); } public void testReferencedBleedingFunction() { testSame("var x = function y() { return y(); }"); } public void testInlineAliases1() { test("var x = this.foo(); this.bar(); var y = x; this.baz(y);", "var x = this.foo(); this.bar(); this.baz(x);"); } public void testInlineAliases1b() { test("var x = this.foo(); this.bar(); var y; y = x; this.baz(y);", "var x = this.foo(); this.bar(); x; this.baz(x);"); } public void testInlineAliases1c() { test("var x; x = this.foo(); this.bar(); var y = x; this.baz(y);", "var x; x = this.foo(); this.bar(); this.baz(x);"); } public void testInlineAliases1d() { test("var x; x = this.foo(); this.bar(); var y; y = x; this.baz(y);", "var x; x = this.foo(); this.bar(); x; this.baz(x);"); } public void testInlineAliases2() { test("var x = this.foo(); this.bar(); " + "function f() { var y = x; this.baz(y); }", "var x = this.foo(); this.bar(); function f() { this.baz(x); }"); } public void testInlineAliases2b() { test("var x = this.foo(); this.bar(); " + "function f() { var y; y = x; this.baz(y); }", "var x = this.foo(); this.bar(); function f() { this.baz(x); }"); } public void testInlineAliases2c() { test("var x; x = this.foo(); this.bar(); " + "function f() { var y = x; this.baz(y); }", "var x; x = this.foo(); this.bar(); function f() { this.baz(x); }"); } public void testInlineAliases2d() { test("var x; x = this.foo(); this.bar(); " + "function f() { var y; y = x; this.baz(y); }", "var x; x = this.foo(); this.bar(); function f() { this.baz(x); }"); } public void testInlineAliasesInLoop() { test( "function f() { " + " var x = extern();" + " for (var i = 0; i < 5; i++) {" + " (function() {" + " var y = x; window.setTimeout(function() { extern(y); }, 0);" + " })();" + " }" + "}", "function f() { " + " var x = extern();" + " for (var i = 0; i < 5; i++) {" + " (function() {" + " window.setTimeout(function() { extern(x); }, 0);" + " })();" + " }" + "}"); } public void testNoInlineAliasesInLoop() { testSame( "function f() { " + " for (var i = 0; i < 5; i++) {" + " var x = extern();" + " (function() {" + " var y = x; window.setTimeout(function() { extern(y); }, 0);" + " })();" + " }" + "}"); } public void testNoInlineAliases1() { testSame( "var x = this.foo(); this.bar(); var y = x; x = 3; this.baz(y);"); } public void testNoInlineAliases1b() { testSame( "var x = this.foo(); this.bar(); var y; y = x; x = 3; this.baz(y);"); } public void testNoInlineAliases2() { testSame( "var x = this.foo(); this.bar(); var y = x; y = 3; this.baz(y); "); } public void testNoInlineAliases2b() { testSame( "var x = this.foo(); this.bar(); var y; y = x; y = 3; this.baz(y); "); } public void testNoInlineAliases3() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y = x; g(); this.baz(y); } " + "function g() { x = 3; }"); } public void testNoInlineAliases3b() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y; y = x; g(); this.baz(y); } " + "function g() { x = 3; }"); } public void testNoInlineAliases4() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y = x; y = 3; this.baz(y); }"); } public void testNoInlineAliases4b() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y; y = x; y = 3; this.baz(y); }"); } public void testNoInlineAliases5() { testSame( "var x = this.foo(); this.bar(); var y = x; this.bing();" + "this.baz(y); x = 3;"); } public void testNoInlineAliases5b() { testSame( "var x = this.foo(); this.bar(); var y; y = x; this.bing();" + "this.baz(y); x = 3;"); } public void testNoInlineAliases6() { testSame( "var x = this.foo(); this.bar(); var y = x; this.bing();" + "this.baz(y); y = 3;"); } public void testNoInlineAliases6b() { testSame( "var x = this.foo(); this.bar(); var y; y = x; this.bing();" + "this.baz(y); y = 3;"); } public void testNoInlineAliases7() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y = x; this.bing(); this.baz(y); x = 3; }"); } public void testNoInlineAliases7b() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y; y = x; this.bing(); this.baz(y); x = 3; }"); } public void testNoInlineAliases8() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y = x; this.baz(y); y = 3; }"); } public void testNoInlineAliases8b() { testSame( "var x = this.foo(); this.bar(); " + "function f() { var y; y = x; this.baz(y); y = 3; }"); } public void testSideEffectOrder() { // z can not be changed by the call to y, so x can be inlined. String EXTERNS = "var z; function f(){}"; test(EXTERNS, "var x = f(y.a, y); z = x;", "z = f(y.a, y);", null, null); // z.b can be changed by the call to y, so x can not be inlined. testSame(EXTERNS, "var x = f(y.a, y); z.b = x;", null, null); } public void testInlineParameterAlias1() { test( "function f(x) {" + " var y = x;" + " g();" + " y;y;" + "}", "function f(x) {" + " g();" + " x;x;" + "}" ); } public void testInlineParameterAlias2() { test( "function f(x) {" + " var y; y = x;" + " g();" + " y;y;" + "}", "function f(x) {" + " x;" + " g();" + " x;x;" + "}" ); } public void testInlineFunctionAlias1a() { test( "function f(x) {}" + "var y = f;" + "g();" + "y();y();", "var y = function f(x) {};" + "g();" + "y();y();" ); } public void testInlineFunctionAlias1b() { test( "function f(x) {};" + "f;var y = f;" + "g();" + "y();y();", "function f(x) {};" + "f;g();" + "f();f();" ); } public void testInlineFunctionAlias2a() { test( "function f(x) {}" + "var y; y = f;" + "g();" + "y();y();", "var y; y = function f(x) {};" + "g();" + "y();y();" ); } public void testInlineFunctionAlias2b() { test( "function f(x) {};" + "f; var y; y = f;" + "g();" + "y();y();", "function f(x) {};" + "f; f;" + "g();" + "f();f();" ); } public void testInlineCatchAlias1() { test( "try {" + "} catch (e) {" + " var y = e;" + " g();" + " y;y;" + "}", "try {" + "} catch (e) {" + " g();" + " e;e;" + "}" ); } public void testInlineCatchAlias2() { test( "try {" + "} catch (e) {" + " var y; y = e;" + " g();" + " y;y;" + "}", "try {" + "} catch (e) {" + " e;" + " g();" + " e;e;" + "}" ); } public void testLocalsOnly1() { inlineLocalsOnly = true; test( "var x=1; x; function f() {var x = 1; x;}", "var x=1; x; function f() {1;}"); } public void testLocalsOnly2() { inlineLocalsOnly = true; test( "/** @const */\n" + "var X=1; X;\n" + "function f() {\n" + " /** @const */\n" + " var X = 1; X;\n" + "}", "var X=1; X; function f() {1;}"); } public void testInlineUndefined1() { test("var x; x;", "void 0;"); } public void testInlineUndefined2() { testSame("var x; x++;"); } public void testInlineUndefined3() { testSame("var x; var x;"); } public void testInlineUndefined4() { test("var x; x; x;", "void 0; void 0;"); } public void testInlineUndefined5() { test("var x; for(x in a) {}", "var x; for(x in a) {}"); } public void testIssue90() { test("var x; x && alert(1)", "void 0 && alert(1)"); } public void testRenamePropertyFunction() { testSame("var JSCompiler_renameProperty; " + "JSCompiler_renameProperty('foo')"); } public void testThisAlias() { test("function f() { var a = this; a.y(); a.z(); }", "function f() { this.y(); this.z(); }"); } public void testThisEscapedAlias() { testSame( "function f() { var a = this; var g = function() { a.y(); }; a.z(); }"); } public void testInlineNamedFunction() { test("function f() {} f();", "(function f(){})()"); } public void testIssue378ModifiedArguments1() { testSame( "function g(callback) {\n" + " var f = callback;\n" + " arguments[0] = this;\n" + " f.apply(this, arguments);\n" + "}"); } public void testIssue378ModifiedArguments2() { testSame( "function g(callback) {\n" + " /** @const */\n" + " var f = callback;\n" + " arguments[0] = this;\n" + " f.apply(this, arguments);\n" + "}"); } public void testIssue378EscapedArguments1() { testSame( "function g(callback) {\n" + " var f = callback;\n" + " h(arguments,this);\n" + " f.apply(this, arguments);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}"); } public void testIssue378EscapedArguments2() { testSame( "function g(callback) {\n" + " /** @const */\n" + " var f = callback;\n" + " h(arguments,this);\n" + " f.apply(this);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}"); } public void testIssue378EscapedArguments3() { test( "function g(callback) {\n" + " var f = callback;\n" + " f.apply(this, arguments);\n" + "}\n", "function g(callback) {\n" + " callback.apply(this, arguments);\n" + "}\n"); } public void testIssue378EscapedArguments4() { testSame( "function g(callback) {\n" + " var f = callback;\n" + " h(arguments[0],this);\n" + " f.apply(this, arguments);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}"); } public void testIssue378ArgumentsRead1() { test( "function g(callback) {\n" + " var f = callback;\n" + " var g = arguments[0];\n" + " f.apply(this, arguments);\n" + "}", "function g(callback) {\n" + " var g = arguments[0];\n" + " callback.apply(this, arguments);\n" + "}"); } public void testIssue378ArgumentsRead2() { test( "function g(callback) {\n" + " var f = callback;\n" + " h(arguments[0],this);\n" + " f.apply(this, arguments[0]);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}", "function g(callback) {\n" + " h(arguments[0],this);\n" + " callback.apply(this, arguments[0]);\n" + "}\n" + "function h(a,b) {\n" + " a[0] = b;" + "}"); } public void testArgumentsModifiedInOuterFunction() { test( "function g(callback) {\n" + " var f = callback;\n" + " arguments[0] = this;\n" + " f.apply(this, arguments);\n" + " function inner(callback) {" + " var x = callback;\n" + " x.apply(this);\n" + " }" + "}", "function g(callback) {\n" + " var f = callback;\n" + " arguments[0] = this;\n" + " f.apply(this, arguments);\n" + " function inner(callback) {" + " callback.apply(this);\n" + " }" + "}"); } public void testArgumentsModifiedInInnerFunction() { test( "function g(callback) {\n" + " var f = callback;\n" + " f.apply(this, arguments);\n" + " function inner(callback) {" + " var x = callback;\n" + " arguments[0] = this;\n" + " x.apply(this);\n" + " }" + "}", "function g(callback) {\n" + " callback.apply(this, arguments);\n" + " function inner(callback) {" + " var x = callback;\n" + " arguments[0] = this;\n" + " x.apply(this);\n" + " }" + "}"); } public void testNoInlineRedeclaredExterns() { String externs = "var test = 1;"; String code = "/** @suppress {duplicate} */ var test = 2;alert(test);"; test(externs, code, code, null, null); } public void testBug6598844() { testSame( "function F() { this.a = 0; }" + "F.prototype.inc = function() { this.a++; return 10; };" + "F.prototype.bar = function() { var x = this.inc(); this.a += x; };"); } public void testExternalIssue1053() { testSame( "var u; function f() { u = Random(); var x = u; f(); alert(x===u)}"); } }
public void testEncoder() throws EncoderException { Encoder enc = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64, (byte[]) enc.encode(binary)); assertTrue("Encoder test-" + i, b); } } }
org.apache.commons.codec.binary.Base64Codec13Test::testEncoder
src/test/org/apache/commons/codec/binary/Base64Codec13Test.java
380
src/test/org/apache/commons/codec/binary/Base64Codec13Test.java
testEncoder
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.binary; import junit.framework.TestCase; import junit.framework.TestFailure; import junit.framework.TestResult; import junit.framework.TestSuite; import org.apache.commons.codec.BinaryDecoder; import org.apache.commons.codec.BinaryEncoder; import org.apache.commons.codec.Decoder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.Encoder; import org.apache.commons.codec.EncoderException; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Enumeration; /** * Tests to make sure future versions of commons-codec.jar have identical Base64 * behavior as commons-codec-1.3.jar. * * @author Julius Davies * @since Mar 25, 2010 */ public class Base64Codec13Test extends TestCase { public Base64Codec13Test(String name) { super(name); } private final static String[] STRINGS = new String[181]; private final static String[] CHUNKED_STRINGS = new String[STRINGS.length]; private final static byte[][] BYTES = new byte[STRINGS.length][]; static { initSTRINGS(); initCHUNKED_STRINGS(); initBYTES(); } /* These strings were generated from random byte[] arrays fed into commons-codec-1.3.jar */ private static void initSTRINGS() { String[] s = STRINGS; s[0] = ""; s[1] = "uA=="; s[2] = "z9w="; s[3] = "TQ+Z"; s[4] = "bhjUYA=="; s[5] = "1cO9td8="; s[6] = "sMxHoJf5"; s[7] = "jQcPlDsZzw=="; s[8] = "TAaPnfW/CYU="; s[9] = "cXTZuwzXPONS"; s[10] = "Ltn/ZTV4IjT6OA=="; s[11] = "6fh+jdU31SOmWrc="; s[12] = "E/5MoD4qCvDuTcFA"; s[13] = "2n9YyfCMyMXembtssQ=="; s[14] = "qBka3Bq6V31HmcmHjkY="; s[15] = "WvyZe6kQ8py7m25ucawJ"; s[16] = "oYpxMy6BSpZXhVpOR6dXmA=="; s[63] = "yexFaNKaP+VkVwEUvxQXbC0HSCi/srOY7c036lT25frs4xjIvp214JHCg7OL/XZW3IMe6CDgSMCaaI91eRgM"; s[64] = "vkqgnuJ3plxNtoveiMJuYLN6wZQLpb3Fg48/zHkdFuDucuMKWVRO/niFRgKsFqcxq6VgCxwQbePiP9sRnxz7wg=="; s[65] = "YHks3GCb2uVF47Y2tCieiDGJ879Rm5dBhQhQizYhfWOo+BrB2/K+E7wZWTid14lMpM60+5C0N9JNKAcBESeqZZI="; s[66] = "z8551jmQp/Qs95tw226+HCHWruKx/JvfBCfQ5p0fF77mkSpp66E552ik2gycrBBsMC/NbznAgTZoMzZxehfJwu49"; s[67] = "VsR2whqq/qQm342+TNz1lgOZMoWbpCz+kj2zflq0nx7S/ReEVPUJcqgMtVzrr2FVQPfBAH5VRjR+hkxwv4bssQms8Q=="; s[68] = "5xmIp8dUJZzkisIkuEPsnPXvzDeMo48qWFfHIn2av3jr5qoZHCs0LfNEyepC3v2sa0nCU0FlqsmDyTI5/2jt5zsLtV0="; s[69] = "tGEgXjglUB9NbCtiS88AetLtRqhCAnhzOUKVgvbJZHqOA6x8uOorA1t3NcaIA00ZqbPYALu4LzIm4i4lAL9QgiH/Jg7b"; s[70] = "gFtxEhYJahDmU5dpudYs6ZTsqAx+s2j+06A0zeyb3U7nhZFsbkCDlds0EYUoqerZqZPm7F6CDOOD3dU7nYmelE0DxyMO9A=="; s[71] = "j/h/1JygYA5bjttxzQxr5gBtgh+AYVozhF4WgvcU/g49v0hUy6FdhfZewGK+Phtzj7RabI5p2zXyzvkmLQdFhdI5Um4O5sw="; s[72] = "m+kYVGojIR5pgbz7pGJm2g+3qqk7fhl3cowa2eVrhki7WofyywnRezqTxOkBgVFz6nKs8qxpbbbzALctcPeMsp9dpXUfuUJr"; s[73] = "pPaGnMr0UYmldnJVk/F+3WCJJ1r2otvD5KJdt2u1RnS6LwhHhwLCqfW8O/QEg43WdxKomGL/JM33tn/B9pMPoIU0QTGjq2GRow=="; s[74] = "mOxzGyym6T/BxCV5nSiIYMlfAUmCN7gt7+ZTMg1kd8Ptirk+JF5dk8USbWBu/9ZvNg5ZuiJCeGwfaVpqpZ3K9ySF7C87Jvu1RUE="; s[75] = "VYLOIE4DnhxJn3FKS/2RHHHYLlZiGVdV/k4uBbtAYHUSTpRzaaYPGNAVjdNwbTHIihmeuk/5YQUy8NFsxIom+Li7bnWiBoHKBPP7"; s[76] = "7foMpJ0TknCatjUiSxtnuKSiz4Qvl/idWY9UKiTljoQHZ+C8bcUscnI/bZr13e6AvyUh47MlpdGvzIm05qUdMWWLoZJOaGYvDmvrWQ=="; s[77] = "jxQSGiFs+b1TfE4lDUAPUPJ0SWeUgl03rK6auieWJcarDIHM97gGOHMmyHudRMqkZmIkxYRgYgCCUg/JeU91OZD3tL4U+wNhShywe88="; s[78] = "UGmH/gl7t3Dk801vRhRDEbgsfShtHZ1gZQn4KNZ5Qsw3WiGjW0ImInVHa+LSHBzLUjwC0Z3nXO4i4+CiKYqAspOViE6WqVUY8ZSV0Og4"; s[79] = "wdEoYmJuRng2z2IkAiSgJ1CW2VE7H7oXpYWEFFO8nG0bZn7PHhT8KyhaO2ridl8eUEysja0VXFDyQqSgZnvdUKrCGepWGZbw0/0bDws3Ag=="; s[80] = "5kZqgrUbt+rN5BWAddeUtm9TGT43vYpB6PeyQwTyy9Vbr0+U/4Qzy0Iw37Ra293HmkmpgQzuScVpcIiFGXPAFWwToR+bovwu7aXji/FnMwk="; s[81] = "E467MMmJbmwv8Omc2TdcyMr/30B8izWbf+CAuJtw67b1g9trhC6n4GYnXjeW9DYvmWoIJPx0zvU/Q+gqv0cteg2bx9P2mrgMDARb6egowqjx"; s[82] = "Vpt8hYb4jx1F+7REX7K65v6eO5F1GDg/K8SVLWDSp0srupYEQkBVRxnB9dmhSo9XHpz4C8pRl8r82fxXZummEf4U2Oh0Dip5rnNtDL+IJvL8lQ=="; s[121] = "hf69xr9mtFf4N3j2uA9MgLL5Zy94Hjv+VQi94+LS8972JJgDHCQOwP5whdQkV+SJpXkiyHGaSsQ4fhepPwzuZcEpYER+beny1j+M0HSZe36MdRIhlTqno+4qsXckL0CjXsYkJJM0NAfOYjHAus5G1bgi9VhmiMfAMA=="; s[122] = "yKzTh5hPp9/PBeZtrZXsFHAR9ywOM3hRaBDkgG9E09wFW8MZD0xMGegcp0QrTJcP8QYOaYhTDVimPqsNTVOmjdjkvS+2WhjJW4mVOXQ8KID91yaBtPo+DStL5GMgctcP5MoVf1Vp8w/mYtofqbllfDm5NfYzh2A7ijY="; s[123] = "csFmwvDzoO4IO6ySDA4B2V7emEetAwCgO66zzlfWb3KDrPfFZc3Jgr4+dlaUkEIDHYeLHETdTssWOl2KrPHBEsULpDTR+3OhurXb1Qr2NvHiHFuqT3Geb6EYw2albfTmXxch82ablt4WKl4qPcSey54v6tsCuUuZzrkt"; s[124] = "5InxvKwpoCV7EK78OzU/tL9/NmK14Prw9tOCAyK+xpUNLZriuVEVdgpoZ05rliufaUDGHH8dPAem8G9DN/VOPktB6vXKtc2kMUgnMTiZwv/UVd+xyqnT8PLEdNQ8rCWxyiCcLdXFf0+xcE7qCcwzC+D7+cRW+i6dnpZkyw=="; s[125] = "cEx7oTsSHWUFPj92cstdy5wGbRcxH+VRWN8kaNTTCPWqSckyU9Xk/jj5/gj9DFwjfsCSp60xutf4/rFanjtwqtRg6dJLP4JAgpOKswDlHi6Vt7zF/w7HidMf2sdtlsqzayZmT2Hn7iOo3CExzr5Z5JfmMFAX8R9peUN4t5U="; s[126] = "AeXetVbj+7mmGiCs3BGUSZDLlq2odMsN8JAHQM64Cly8y5jw75PpISocWRFFQmmXYP7ckKmtuhIvD69HtZxGhNRsl1l1gXzKFhsWykcRtG87F8sS1Uv/i6QvGiRIDVEGGIzWrzRIISkBb9wCxJ2HESfleWwrz/GqryjoN26B"; s[127] = "aj1/8/+U8VO3D2iAwvQXZ4H0KwtuzDm4JCC8+22ccqk+UzKvqjGs87XngwfsMfSkeGVAi6VB6tfNJTjYctaj7R8dwh2PIfLSrvaphw4wNB2REjplnPojoOb9bNUNtUvdK3b1bArOWugIRJWLnMl72yEHFb1iBfBmn7uIa7KT2Q=="; s[128] = "kiMuF/1CMRlgoS/uLKn1mNZFZNHJNkRQnivOrzj8HQAagwzvTXvsGgI9hXX3qaeZL9/x/Oq+Y5F6Dh+wXo+0kp6JagFjvbTJcQSowFzIwg7/V9sans0NE0Ejow5BfZKvihFI46sHiALl1qzoXqLQq+5fZGIFRyyY8wFW1uiNu9k="; s[129] = "YXmCWhiNz4/IhyxQIYjgNvjX+XwDiPTSBMaFELm5X8Y4knGRnkF4/zix8l9wHBb+7Cgfrr46rF7eiIzaAFLjLjjewy63duBJiVbEWjqFO0fu6T9iIjuEaF2sTppvuZNPHx80vN+HLAnAVmgFESw5APXWn15dizvuUfVHd5isCqbA"; s[130] = "GJfUoBivW5uqDpUxTRfjGWNYfN3/dTFtdRqCIH5L2c1nWX0dgY3ba1+fW/YX1Oh5aw4lC6BIiiThjJoV1VrNnlXzbcUcMy+GsDUUB8Qe8lBvfe/t4RmNPB0hVgrS89ntbuU0SsCmWw+9DqM3nidPebANKERig1zZTBBKgpVf7HPFCA=="; s[131] = "eTerNs7dOqJAxAxcMQRnUDc2cBj2x0jU1g1D3G+b22kDz7JBzOy/mxhGXAQ3130lavWMhImSBkReU+z0A13EYVMUv9PFzD747KCvns+SCo52YNHB0896b4l47q8hu8jsD17TZ2uWWJhS4cNnSE1jeM6NoXGKvf90yxfzwucNYc4RdaQ="; s[132] = "lbrGsjbzE521q8tzVHV7vcTPchUnzI/UfeR2R+cmOa29YljPWLht9Wx2JrjiKv4Of5nXe7kvhi+LYUuFVqgaqIFhC/PLbqOFiT2VZcXorToaRT9CLiqV5b6nHN/Txz6SI7MiD3hnk7psDbglPOo+ytqc9sFHj7UkR1ZctQjwFYwJjlxf"; s[133] = "mQwAPzYzfxz9FXEiZ6M8u1oN3EJbFYmNVfpm+j0DqgU+OPI4URHBIrF4xvdMvAPn0WuarbQy/ZVN0eKL7S4K3Mvan0flAwaZdI+e5HpkfxOoGTp8Dk5EFTXjmZ/s+GonePEQEGNVPL1WYoD6xXqAAvMLKtyrFcpoiGS9eDBlsZDQzPzz/g=="; s[134] = "3G6d12UY4l5W7Nnw0BL0HnViVg9SdEuLMqeZwy0RlJR/Ytcgd/mIxIuXXAlGhvhoX6Xc2BGU7RpTi1jYKzA86yul0j96dbcE4OtrP9lUBJlcY9eWz59dvLqKxwt3cEOBwrPf69MHuIa256es3AOCobfC8RQScW0PQ0QUa1VHB/eXSsVTSWg="; s[135] = "AxgrZKTFk5JvLC3DBACHwp266FxKI/yn9F+1tYkzL57RVs5HCJYS47VuG0T0E2wqzHqcLKPQMZWU7vbRoyMGNL3ZtaHoZqTqcq9KWtODC+OnEvSS7+1P4SmQDuyL2MJ/eJABJKNcu1K/Lk0buAaO0FvX6OGBcPzu1+dv/ZkwuORK07qRnxqQ"; s[136] = "atkG8l2U/Nnm+zLu7zjenrfcAVQJMUqHimFZ3cQfaUp4qyrFn1UiwZ33j66Vt63eVaT/FXx+LlEnsHn6ATPBMp3iEYoBJYyNpjz/zROhBbcznQAMdWUTcyKInvnG3x6ExgBXpyqfxxp/Pm8by7LlSUT5MKHdcu+TEfUXRokCr2iPnt7NYsNDfA=="; s[137] = "dciU1mSHGcBxOAVBgJx75J6DaQdBZfTIzQ04WhkkdRMupOZWSnv19xhz8hiO+ZnbBtDJuO5rHsUGzH/jYacfZyCQ924roRvkh3T1yxsLq3abZJUCD9HYnPTELVhv1+cEF4aoO3vGOu2FpfLUn5QTd0PozsIqcqZVB2V57B7DjfizUe3D8Yf5Vco="; s[138] = "dgR1PPacBvtILBmg33s9KWtuc67ndh3rCHZ/lIN7sENgbFqJQy5DC3XIeHTV7oWd+tJQaXxoC71/SU7Rz6OClAMKXLbMz8U6RPiqn3M7MRCQcDfNjA5cCNknXT9Ehz/IZF/7lcWrwxBKYm4B98lPkpZtR2QHndiQ3venzWrP0P5y27mReaFuaJ++"; s[139] = "1Q8rfp1HuGsxurTgGMakxj5SwNF7EixXxVPnfGADWDcygh5C1BMXqiL1AuVXOVFOsaydfLWGC8Kbh/JiL6H+12lYrNGUT9yJRIzRDi4XylMnrYwBtwCJjoHSi4exz5K2ih54utVAuzXZg6mnc9ied/mNRjj9d2HFD5mv0w/qTN/WFxEmtuZM/nMMag=="; s[140] = "w01TnPP/F3Vni3fBdV32Bnbb4J1FcbaE+Xn44no5ug77U8FS1gSm3LqJ8yTyXduzl5v2dwBEfziEfTuyqgeLLsCYTBjXmYOIHQosEl6DyAknu4XK52eQW+Fes9eSs2Nq+G4aaR4y4leeFNmCoZ9BQmAAZr0LFkqnvqaKmBVgcgxPs7/8SQHnpqvaU6Y="; s[141] = "OfzIF38Tp5g1W5eVbrkrMe0Mm7e0wBYg5hVvLpn/5MW5OFcmRDuBp15ayRBnJ1sBI93+CNl0LwP8Q0z9IXFjTER5gHZ1KfG8NV+oacKNG7aYrbUftkSL/oPfRNPez6U0FuWgvVrXUB6cwKTWvwb9KoD7s6AGYRdH50ZgJdBniFD7dKoOQnJ/ECuTUXI+"; s[142] = "4hoX0sjqlkSJPUq627iJkNYRbtD+V2qErCuTikaeRDEZvVHWvzdvwj4W1xxJjz+yHAN6z2EjCWidcSsVgTejQ1bH8uTzJgh/zq3yGUSsJoJWrecqxsge8bEBjkm+qUO8G3kAnC6FMjJ2NYQeXf6OK6OgsqyJwlHPTyAms2/IoYTB4iEqgIFG/2fNEJEIag=="; s[143] = "M/dy14xNbZMRfHiKKFdmD/OrEB+8MexrRO8mMh0i5LrNA5WUtLXdwUfAysYmal94MSoNJfgmwGCoqNwlWZBW1kpQaPdqsrn2cvc6JcZW9FlOx07DERJGbZ6l6ofbzZWgF+yf+hvT6jnJvXBVCTT3lfO3qo4leNuEJwsuU6erXGC3Ch53uPtGIrdDUpcX6/U="; s[144] = "GgLr2hd3nK64IZv0JksKAT/yJNQ38ayuWyBnWLjXbEmT048UDppsrrnP6hikRo5v2TlHGhD2dcwG9NLK3Ph8IoIo9Wf2vZWBB+SMI9FpgZxBWLEjwHbOWsHaEQMVsQfk38EWQP0Fr6VyMKlEQfpsRkuCpp1KxscaxK7g5BgXUlb0a2x0F+C9hEB0OVPsj4JN"; s[145] = "W9lKcLDqNGQAG/sKQNaRmeOUmLJ7GcMNqBaGZ659Rnjr6RTrfnmkp5Z9meALnwXoHjPjzSQDJnVYsY+xyMnuPgl6gMVAhAm+XprYVpsne4vt+7ojUqavVPBqLy5dtnhp1qfcnAiV5cZhHXX7NbxkUOzptjEGCQjnhSH4rPbZtgoIWE8Z6boF3l/thLnFX+AiiQ=="; s[146] = "iYLn5h9lIhD/x9moaPRnTX6mJEJKThg4WXxS7IrR2zblH26uOkINz0dJNTJVets0ZNYDnsnT7J2iI3Y6hTVWPGoYU49J3B2LhCREs0DZQ3C7080FtiOcfHbfBLNn0DyCK1LeAC7YB/bNdiyhLqH8fKl+0+KhiPDIUBJY2e7IbZR/9t0sxJbIXx6cRvI5AXex12o="; s[147] = "SlRJEc7npTUvQq8SgBYKmVY/3wHYp2gsDxafN/JLUuEqEjmWMtW7fxASi+ePX4gmJJqLhD5t+AZxiCwYK3L3ceuJx4TiqVgJz8d6sc7fgWXluh1K+BcGPbZ7+Cq4Vsga7JEBVekviEZ5Ah4apNr8RkB7oMOUVPGxRcyyaVE4zBW+scA6c1yi/HQXddQ9rWyLUsVo"; s[148] = "AAlbGR6ekLOzx4hpqZTUqVUQ0FL2CFpgCMOp6CuuUzkSnWXpUjvOiSDkNPgoTPgpgmg3uYvMsX43mkPGUGC9awDThXyGQh6u3WfWtmhiPRqXnjFek+EPd0LYXps71non6C9m7nUlYNWzBJ1YzrzWjlB5LLPBN8bsZG6RbdZkYMxJ9J5ta/c30m8wDDNuTm0nEE0ZVQ=="; s[149] = "nWWbBhzObqwEFh/TiKREcsqLYbRjIcZflJpol16Mi4YDL6EZri22qRnTgrBtIY+HieTYWuLaCSk/B9WcYujoS6Jb5dyg3FQ6XF9bYaNQGx2w8DHgx0k2nqH/0U1sAU0kft32aD2orqCMIprbO1WJIt2auRnvcOTFoOax926nAkxvR3nrFVDevFjDbugpWHkGwic6G7o="; s[150] = "WNk1Rn2qtG+gk0AEewrgo+aRbNrG4CgQpOR8Uo7c2m2XQY8MVDu4uRA6rzYGGdgqTcICKky9MvHeJeNWVAXOxmA4EdXQ2xItFJdQtxBt56cad9FBXXsz21yVsPr5d453abi7T3XfHVTToekiOlxAJs+bpat9cFRbIdHghO9wc/ucoArT53vpYsnyeVnmZG2PX48lXpNS"; s[151] = "wVmiO6mdf2aahrJlcmnBD0Qa58y8AvzXtJ54ImxgPLPn0NCQIrmUxzNZNTODE3WO6kZMECaT/REqT3PoOBp9stCHCFNXOM7979J44C1ZRU0yPCha00kQZBF5EmcLitVCz10tP8gG1fiIvMjwpd2ZTOaY4/g4NeJHLjJPll0c5nbH7n4v+1I+xG7/7k7G6N8sp21pbgpTYA=="; s[152] = "OoiVZosI+KG0EZTu+WpH7kKISxmO1zRYaSPMBMW0AyRiC2iZVEkOMiKn12XPqIDSW/kVA58cvv/ysTAzKLTu78Uo+sVcJe3AtLdgeA9vORFELTP4v9DQ/mAmehe3N8xk+VTLY6xHWi6f4j9cTDW/BDyJSDRY00oYoHlvnjgHo4CHBo0sMGgX3CwcnK2hpMFVtB/3qPl6v2w="; s[153] = "97ZVsTYwD8VrgN1FOIRZ8jm8OMgrxG3o1aJoYtPVWXp9cjjlgXqTMZVsoWr3pr7pudw+LYo1Ejz3JpiUPHqWcZ2PWrWs7PR1akYGuwdCBHYvCGTcZYFe/yu1AB8w5zYsl1eJR45g0u1DlXfx5BUAUzc4yJDjc48Ls62bn8t0EJ7+30sWwifqKuz2EHpsqp1j/iMlwzKJGjGE"; s[154] = "0NSYKTvBKKInwL9PJ/pWUWVX4gjF3igsA2qqQMsRew0lI1LcCB18eGCYk0AnyUCe99w5lWHGFUMMeH6DZciAylWGeDn19JdzVOTevBWk3LIujI1GvsEB3oVqf2Zl9IZeDGCT4+bQKBWvgcXHjysZfnn/5z9Xz06qrPqac5LfS36fDcwnkrUYQWDsL2Ike32ALmOnkcDjNq1BoA=="; s[155] = "5ok+rYI4LCgGa2psGUN/fdkT2gQEToB9HRiFXQpe2YcQvEN2z7YlJCETx4jSWw06p5Y8tZcp08moKNYwUJ40DvPpGlDG+wUpFhC4kkfo6vj6TrCj5yoWJi5D+qdgH2T0JeWM80cYN0bsOsetdaqNhDONlYXZ2lVYkyVS/wzw8K5xX87EWktwOwFq/yYhuWCYJ9GZL7QuDipJjEE="; s[156] = "KHzTalU9wPSnIjh5g0eHi1HUaFufxJpXpjDe0N3wEKINqbgzhbj3Kf4qWjb2d1A+0Mlu9tYF/kA9ONjda5jYfRgCHm5mUrjU0TAyT7EQFZ2u6WFK/sFHP++ycJQk8k7KLPUWA5OWScy1EO+dYF4d0r6K5O+7H/rpknxN6M9FlP8sH83DXK1Sd+UXL32D+4flF580FaZ5B3Tkx3dH"; s[157] = "RrJVxIKoDXtCviWMv/SXMO42Dn6UWOKDy2hh2ASXssT0e+G6m7F1230iJWlEN0wBR8p+BlTdBhQrn25098P3K16rBmZpzw/5dmesIJxhYPaM4GiaOgztFjuScTgkmV0Jl/vZ9eCXdEVNISeXkIixM4pssTFuUV7PY/Upzdj55rDKGLr1eT7AFVSNP30PhL8zZs8MANqKBeKBBDvtww=="; s[158] = "sy4t5rFA75GRBE+Dqa9sQxjPluKt/JnEY54guHnKqccmx3HGiyJ0jUA+et4XO8Xg69wCA9xVxJZQL73z80mVfIf43HIKOxgxT2IjG7EKMOD/qx6NnMTve4BryggLtbLQUeRfhriQeY7h65tD9ierhccXoXDpGnmBn9m2BQP78y+Qhc4eIsa3LcxbQJUIwvURjFp/rgMD7lhOLboa/2Y="; s[159] = "Zs/BfFoWImYau2dZLb7JneeTQp7sQ06yonEq0Ya4BNOJGy/5dGH42ozt0PpP2IZ/S58X7esVgc6jA1y3Bcxj3MPoDjQJSZHFEtR3G31T8eF5OpPVC4dw9s9clllM05tvcemssLdcd85UP/xBaDrmpAl8ZDSc73zflK3nJw8e0HQFYntNnlZPFyyyBLHnLycb6Jlvq7F2OqrZR+FXZnL3"; s[160] = "hdeDJuRnmb8q9EYec8+futT/CvqhpqoUdtmG6E31RrYJDs96M5Wfng90IEqrncZe4rVYDocRZK23dvqtJaPhTUBXXh42IyMlUnro69KI+075FvYYwgVaUd10r7ExWM5Z7DCQ2x8Tm1meK2YCTPkF1VXXexl1UjYCnRQuQxppdophMwroJK8VqlJbFFslchTSBFuI7wgcdy+f/LHMbMsusQ=="; s[161] = "ClCCOv0mD9//LR0OisHfamxcTvmlwMLgAIQt3hbOjRPkXwEgaDzP0u6LN8BNwdOVw+LhrbzMI8zQzHvo7mGPkQICeeim/x+xmGPQtmWnXxCWiL1uf/8eR5Wuy9Er8skTB8rG4/ubb2ssvCkubObPAkMSOgFnX9UtxnCN4+nMNV2vvn4xMTSvvQyYWewfnlNkflTyva1epE9RVW2RqRtJikY="; s[162] = "Fs+AmFCnUr/imw8D0GpNidIP9qwW8yRAzmtqPS+vT6n5U4YFQcpgbznrYO4TPqkVF2oz1mpgLYIgx/u2XsrtljGX46LfY8OyUPaw4/da38QGngoIlS2cN01cgN3efSjMlnZFo1x8T9p0Nn1IgRgevOd5ezVUL7WdY7eeiE1pXXcGBgDYn7NDQph0dC6HDlBiS95bDFcZ+6FYigE4WybpsOHL"; s[163] = "wgO4DdGZy9g13IuOhkJGJcToyLuCBVm9T/c8qY4NOheVU1NW2g8sPIo+RiEsSST8sx6+Jh/A/kaCxYvJ9CsgnBjZMMWRsd383HZAoJtkxwKvyoeXzzD+puFvqKQBEKrlBEwffXhLDoFQAW2ycYtBGztl0GsUtoOob2nv7ienx1xD6KNZNaxYx2ObRAYS/e8LS3pg5dku9MPBp1X12m8ZIXRAaw=="; s[164] = "EkXt02SaRUIjFmoLxyO6N+giL4iA4fY0Exao+mjgEfZ+Wv6w95GXHBI1xlYMVLkOcnu9nescvcXQH0OrqL9uforEUTGTSg2ci67m4GrwAryMy+5eUo77Q5GpWKfsg8nDbD8a3gUI/9EE0sCNp7tMaKwoJ56cxhbG3TJYpqWTpq3/S3q76x+3ETL+zxh6EMh8MJPfWcIxlDS7evKqdPgS00KgUtk="; s[165] = "OuBqx5LFJroRbDn41+4azFHlKgw6bMgbsRGaK9UnPvi5xfmV4SLQ2YzIhopGi1F57L6vKukaW0XlFk/Ff5Td5IMC7U+kvXKlf8fGIIQ8FaHI0vbIX89OJlBqlICqftSNiVRxtaE+aCh0rBoDfgPwuC8qBC20I1O3ZLuKfeUVGkMOLEWeZLS6mmcn3cSERj9o/dEl8QYwQvhH+VG6YWF//yki1Vu8"; s[166] = "SO/vDsqZDdImOdH19sZI7FUVhlx1EI0XRr8ArTuAG5F8LDK76Bct2C7fXTUowilXnJWhQxvbGiulkUGSuVjVP12zac9bShRpr1L3ucde7n1f9y/NcHJCwdqTLq7RYygItQ4ppQGiP9jXf2Dn/qmVZZTh+SY3AZCIS+OVo2LAiYJHWnzzoX8Zt+dOYiOA/ZQKZieVJlc8ks+2xqYPD55eH0btZn5hzA=="; s[167] = "tZL/qACMO9SzmgJhWQMsbKgE5lPAEbxn3NR7504ilgArR8j7uv1KF46uQyjrkEnyBormYB/6nLGlHht62IQftMYf5gHpHFfTvukRKF8728yIYAAYHPQ/WjHzHdVSqUJqF2a8RE6SvvY+KSKWLMU3hjn1f6dqX599hYD7AnbPGTpFKDU5sLFOXbuynU1sPUhP+a4Hev9yNU6atLDo4CkX/Yq3FbpWVuQ="; s[168] = "GRe7uF1wH5/71B3vmGF+pN3H9PKO1tLwsnb0D4/Pm7Pu5KAe4OfelkfFIBgyjuoZrpeEkGZnb+qf+Kn7Kt1hDwYr/Mb9ewuwOXsbIpLQMgfh0I5XsPrWocduVzn+u/cm3cr0Z11zsx0AZjTqvslACkDqiquY41JhtGdc22RCvIYom2l+zzMIMyCPsHeCSB1MBu8EWK3iP7SD3dWttwzMg0xanoPDgk0U"; s[169] = "8BDFu+29lptlGSjcZe7ghWaUgIzbuUpM5XDFbtJVQPEd3bAE0cGRlQE9EhKXi5J/IskYNrQ357tBhA+UNDNXCibT2AZGpzWAcwE6dP+14FuRL5Gxqh/teuPYKr5IIn7M3SbgOychZzLI7HGCvVhBUiJBu8orI3WmAIVcUhAsMGHsFveck/ZCXQA+Uq/WVnW1VNs6hSmIhsAFc51qsmsQK07z2Wptx4rRjw=="; s[170] = "siPSXD4u36WYtTvvDzRlFPiuZMnRczrL3eA15955JDCc6/V2Cvu6m/HPO6JxogxO0aYTZ5tejYDOIZgBy40DgUZMqPJ2IpYjsmUbjjJU8u/OpwhMon525m3v0EYlvyj2Qp3pwFKDkvncK3aNjN3KaaX6HuIy6kyqsDl0BTEnB5iJyHLRBCkeznTK019u48Yfsrz2oGuZcWzNj5/vKMdxQPiyJ9EHyox8Ark="; s[171] = "+/14PnFQVZ7BTHKUvkTtRrYS7WnPND5gZ5byMhUrDLkJa6UPBV7z0nrDMifEo/dQfUq3EjCiG6xGVhrUvAzgxqOQZTW1Y9p9M0KWW+E0XvCQppHFpuMqF1vYsF0OD6AMiE9JtGnWs3JcaWP/XBF/CvhQlFGbHi3fbrD/haTEBnmpJWBgMdKribdbXHtBSFZ2MzCX2eDtxoDdRdEVGs4v/q8gVBS+WsnZ3TTF"; s[172] = "31I1ja+B+aopKkztGzJYvJEWAshyoAAV5yve4LnP0kdImUQaVETSuo5CDIYr7zM8MCD1eYPpLicmGnA+C927o9QGAVL3ctO/DCWhNinW7NmeYIM+o4diKBkDPjHmSWa+nq4nr+gOap4CtwL2wW2B5Yqt26pKgN9uAU5CmTL26hYFgMEOZfrkQ7XdYGy2CN8RJLmjeSFVVNBG/FTaK7tpuy0LQSkko6wczBYGeg=="; s[173] = "XbRfDqGe3eeI1tHx8UnPneDB57N8VeSSzXzVCNSgxOEfd6d/un5CDxHG+m4w3tIbtSky4R2+zMF+S5cRvTOwZ/veegYtLKTxA0mVedWLFkfh/v4NgPJ+NEU+cylbSSZLAeBofDvoJwnYKujN2KFa8PGAxr3Y8ry3qdkS8Ob1ZiHYAmLvKS9sGb/vjTvRy+a4Q7kOepsm7PYisinKelBAvDnjli6/lOutGrenjX4="; s[174] = "jGEj/AaBefac9uOcmGuO9nH+N+zMsC4qAe6ZUEMMIXdTGnSWl7Xt0/nKqyOj3ZH249HwkJ8bn5C+0bzOpQ1eA3PxEq6RfKMrjHJPJmTZXrSESTjfj3oNLU/CqqDOqd8znTgN6nvnUdCeStLMh9bmWF1+0G11nDwg6GQWWQ0zjVDTq5j7ocXcFOyUcu0cyl5YDcUP0i2mA2JullInU2uBte7nToeSGB3FJxKueBbv"; s[175] = "RAzNCxlP2S/8LfbGtlSDShox8cSgmJMOc2xPFs8egZVJiwlmnS3aBWKPRbbxkZiVVYlu4GNJNwbocc6dgrl28HXAsYikE5wwoQ1MeOJWU3zzFiYENh7SLBQfjVPQHucctr8P6Rl7YL5wHc+aC+m92R3bnzm5rp1PeHm7uzy2iUUN0cgfbwJ4FrpXhVMTsAUpTbg1+037EWcGOuxir4dG2xBfgOwa+ejFHkw7y0LWRw=="; s[176] = "08hmZptBGKKqR6Qz9GNc2Wk1etgU/KogbiPQmAh5IXlTBc97DuEToL4Bb889nfObVQ/WelmiCS8wEjSBdmnlkkU7/b5UT3P4k1pB6ZxPH9Qldj5aazkA/yCb0kzDfJlcdFOh1eAcu5LvwTXOizmPwsDvJEnOkaDZrKESZshsHU2A6Mx6awk9/orf6iBlJHQIIH3l4o3b1gx2TNb/hUgdAlwtQDhvKO3skB0PS+rcWAw="; s[177] = "0GhrgbSSHPLWtyS2mnSxrNAj/dyrFQcxIgPjT7+78SZ1ZTGc03vsmlZ4Z/bOO84E9yKblaI5dSHVXrx57L0kikL8tgKCsAkUNO3l/4zv5FfCrRTgGx4sFTFB1NNcLcwagkvFzde764DjYmj4YZhYsXSZCVKi0uu5M8fpgGDZ9UMSFR008cbhaIoFLWSANqiNJYSvTQZhGWfLtIPGLN+gIOMcaKhx1b5vg6OYSz6ScAM/"; s[178] = "2VGiMV/f2hNZAjw3fdeHx/wRIVzeP018lZynzwSySG/zQBxyRmi3YmKVZmh3aJunuiqmvdt0kJ6lX7M8BajYHPCBkqJOx8oPJ/K1oADxVgnavZ69dKYrSy9/Pm6sHxjFrdSz9TelUK9sgoFTWS6GxgzWEqXRBDDpGUnsNbSEcWLPKVLNNoYAcltY98JZaNSZBXcpa9FeSN7sVU43q2IEcDx3ZkJzRJpl/lb7n+ivMwX/OQ=="; s[179] = "iMSCh1m5vct3C7LEn5wKRYtalzvG6pKahG19rTb6Z9q7+buDsML5yM6NqDvoVxt3Dv7KRwdS3xG/Pyb7bJGvQ2a4FhRnTa4HvPvl3cpJdMgCCvsXeXXoML4pHzFlpP0bNsMoupmhQ0khAW51PAr4B165u1y5ULpruxE+dGx/HJUQyMfGhOSZ5jDKKxD5TNYQkDEY28Xqln6Fj8duzQLzMIgSoD8KGZKD8jm6/f8Vwvf43NE="; s[180] = "hN4+x/sK9FRZn5llaw7/XDGwht3BcIxAFP4JoGqVQCw8c5IOlSqKEOViYss1mnvko6kVrc2iMEA8h8RssJ4dJBpFDZ/bkehCyhQmWpspZtAvRN59mj6nx0SBglYGccPyrn3e0uvvGJ5nYmjTA7gqB0Y+FFGAYwgAO345ipxTrMFsnJ8a913GzpobJdcHiw5hfqYK2iqo8STzVljaGMc5WSzP69vFDTHSS39YSfbE890TPBgm"; } /* These are chunked versions of the strings above (chunked by commons-codec-1.3.jar) */ private static void initCHUNKED_STRINGS() { String[] c = CHUNKED_STRINGS; c[0] = ""; c[1] = "uA==\r\n"; c[2] = "z9w=\r\n"; c[3] = "TQ+Z\r\n"; c[4] = "bhjUYA==\r\n"; c[5] = "1cO9td8=\r\n"; c[6] = "sMxHoJf5\r\n"; c[7] = "jQcPlDsZzw==\r\n"; c[8] = "TAaPnfW/CYU=\r\n"; c[9] = "cXTZuwzXPONS\r\n"; c[10] = "Ltn/ZTV4IjT6OA==\r\n"; c[11] = "6fh+jdU31SOmWrc=\r\n"; c[12] = "E/5MoD4qCvDuTcFA\r\n"; c[13] = "2n9YyfCMyMXembtssQ==\r\n"; c[14] = "qBka3Bq6V31HmcmHjkY=\r\n"; c[15] = "WvyZe6kQ8py7m25ucawJ\r\n"; c[16] = "oYpxMy6BSpZXhVpOR6dXmA==\r\n"; c[63] = "yexFaNKaP+VkVwEUvxQXbC0HSCi/srOY7c036lT25frs4xjIvp214JHCg7OL/XZW3IMe6CDgSMCa\r\naI91eRgM\r\n"; c[64] = "vkqgnuJ3plxNtoveiMJuYLN6wZQLpb3Fg48/zHkdFuDucuMKWVRO/niFRgKsFqcxq6VgCxwQbePi\r\nP9sRnxz7wg==\r\n"; c[65] = "YHks3GCb2uVF47Y2tCieiDGJ879Rm5dBhQhQizYhfWOo+BrB2/K+E7wZWTid14lMpM60+5C0N9JN\r\nKAcBESeqZZI=\r\n"; c[66] = "z8551jmQp/Qs95tw226+HCHWruKx/JvfBCfQ5p0fF77mkSpp66E552ik2gycrBBsMC/NbznAgTZo\r\nMzZxehfJwu49\r\n"; c[67] = "VsR2whqq/qQm342+TNz1lgOZMoWbpCz+kj2zflq0nx7S/ReEVPUJcqgMtVzrr2FVQPfBAH5VRjR+\r\nhkxwv4bssQms8Q==\r\n"; c[68] = "5xmIp8dUJZzkisIkuEPsnPXvzDeMo48qWFfHIn2av3jr5qoZHCs0LfNEyepC3v2sa0nCU0FlqsmD\r\nyTI5/2jt5zsLtV0=\r\n"; c[69] = "tGEgXjglUB9NbCtiS88AetLtRqhCAnhzOUKVgvbJZHqOA6x8uOorA1t3NcaIA00ZqbPYALu4LzIm\r\n4i4lAL9QgiH/Jg7b\r\n"; c[70] = "gFtxEhYJahDmU5dpudYs6ZTsqAx+s2j+06A0zeyb3U7nhZFsbkCDlds0EYUoqerZqZPm7F6CDOOD\r\n3dU7nYmelE0DxyMO9A==\r\n"; c[71] = "j/h/1JygYA5bjttxzQxr5gBtgh+AYVozhF4WgvcU/g49v0hUy6FdhfZewGK+Phtzj7RabI5p2zXy\r\nzvkmLQdFhdI5Um4O5sw=\r\n"; c[72] = "m+kYVGojIR5pgbz7pGJm2g+3qqk7fhl3cowa2eVrhki7WofyywnRezqTxOkBgVFz6nKs8qxpbbbz\r\nALctcPeMsp9dpXUfuUJr\r\n"; c[73] = "pPaGnMr0UYmldnJVk/F+3WCJJ1r2otvD5KJdt2u1RnS6LwhHhwLCqfW8O/QEg43WdxKomGL/JM33\r\ntn/B9pMPoIU0QTGjq2GRow==\r\n"; c[74] = "mOxzGyym6T/BxCV5nSiIYMlfAUmCN7gt7+ZTMg1kd8Ptirk+JF5dk8USbWBu/9ZvNg5ZuiJCeGwf\r\naVpqpZ3K9ySF7C87Jvu1RUE=\r\n"; c[75] = "VYLOIE4DnhxJn3FKS/2RHHHYLlZiGVdV/k4uBbtAYHUSTpRzaaYPGNAVjdNwbTHIihmeuk/5YQUy\r\n8NFsxIom+Li7bnWiBoHKBPP7\r\n"; c[76] = "7foMpJ0TknCatjUiSxtnuKSiz4Qvl/idWY9UKiTljoQHZ+C8bcUscnI/bZr13e6AvyUh47MlpdGv\r\nzIm05qUdMWWLoZJOaGYvDmvrWQ==\r\n"; c[77] = "jxQSGiFs+b1TfE4lDUAPUPJ0SWeUgl03rK6auieWJcarDIHM97gGOHMmyHudRMqkZmIkxYRgYgCC\r\nUg/JeU91OZD3tL4U+wNhShywe88=\r\n"; c[78] = "UGmH/gl7t3Dk801vRhRDEbgsfShtHZ1gZQn4KNZ5Qsw3WiGjW0ImInVHa+LSHBzLUjwC0Z3nXO4i\r\n4+CiKYqAspOViE6WqVUY8ZSV0Og4\r\n"; c[79] = "wdEoYmJuRng2z2IkAiSgJ1CW2VE7H7oXpYWEFFO8nG0bZn7PHhT8KyhaO2ridl8eUEysja0VXFDy\r\nQqSgZnvdUKrCGepWGZbw0/0bDws3Ag==\r\n"; c[80] = "5kZqgrUbt+rN5BWAddeUtm9TGT43vYpB6PeyQwTyy9Vbr0+U/4Qzy0Iw37Ra293HmkmpgQzuScVp\r\ncIiFGXPAFWwToR+bovwu7aXji/FnMwk=\r\n"; c[81] = "E467MMmJbmwv8Omc2TdcyMr/30B8izWbf+CAuJtw67b1g9trhC6n4GYnXjeW9DYvmWoIJPx0zvU/\r\nQ+gqv0cteg2bx9P2mrgMDARb6egowqjx\r\n"; c[82] = "Vpt8hYb4jx1F+7REX7K65v6eO5F1GDg/K8SVLWDSp0srupYEQkBVRxnB9dmhSo9XHpz4C8pRl8r8\r\n2fxXZummEf4U2Oh0Dip5rnNtDL+IJvL8lQ==\r\n"; c[121] = "hf69xr9mtFf4N3j2uA9MgLL5Zy94Hjv+VQi94+LS8972JJgDHCQOwP5whdQkV+SJpXkiyHGaSsQ4\r\nfhepPwzuZcEpYER+beny1j+M0HSZe36MdRIhlTqno+4qsXckL0CjXsYkJJM0NAfOYjHAus5G1bgi\r\n9VhmiMfAMA==\r\n"; c[122] = "yKzTh5hPp9/PBeZtrZXsFHAR9ywOM3hRaBDkgG9E09wFW8MZD0xMGegcp0QrTJcP8QYOaYhTDVim\r\nPqsNTVOmjdjkvS+2WhjJW4mVOXQ8KID91yaBtPo+DStL5GMgctcP5MoVf1Vp8w/mYtofqbllfDm5\r\nNfYzh2A7ijY=\r\n"; c[123] = "csFmwvDzoO4IO6ySDA4B2V7emEetAwCgO66zzlfWb3KDrPfFZc3Jgr4+dlaUkEIDHYeLHETdTssW\r\nOl2KrPHBEsULpDTR+3OhurXb1Qr2NvHiHFuqT3Geb6EYw2albfTmXxch82ablt4WKl4qPcSey54v\r\n6tsCuUuZzrkt\r\n"; c[124] = "5InxvKwpoCV7EK78OzU/tL9/NmK14Prw9tOCAyK+xpUNLZriuVEVdgpoZ05rliufaUDGHH8dPAem\r\n8G9DN/VOPktB6vXKtc2kMUgnMTiZwv/UVd+xyqnT8PLEdNQ8rCWxyiCcLdXFf0+xcE7qCcwzC+D7\r\n+cRW+i6dnpZkyw==\r\n"; c[125] = "cEx7oTsSHWUFPj92cstdy5wGbRcxH+VRWN8kaNTTCPWqSckyU9Xk/jj5/gj9DFwjfsCSp60xutf4\r\n/rFanjtwqtRg6dJLP4JAgpOKswDlHi6Vt7zF/w7HidMf2sdtlsqzayZmT2Hn7iOo3CExzr5Z5Jfm\r\nMFAX8R9peUN4t5U=\r\n"; c[126] = "AeXetVbj+7mmGiCs3BGUSZDLlq2odMsN8JAHQM64Cly8y5jw75PpISocWRFFQmmXYP7ckKmtuhIv\r\nD69HtZxGhNRsl1l1gXzKFhsWykcRtG87F8sS1Uv/i6QvGiRIDVEGGIzWrzRIISkBb9wCxJ2HESfl\r\neWwrz/GqryjoN26B\r\n"; c[127] = "aj1/8/+U8VO3D2iAwvQXZ4H0KwtuzDm4JCC8+22ccqk+UzKvqjGs87XngwfsMfSkeGVAi6VB6tfN\r\nJTjYctaj7R8dwh2PIfLSrvaphw4wNB2REjplnPojoOb9bNUNtUvdK3b1bArOWugIRJWLnMl72yEH\r\nFb1iBfBmn7uIa7KT2Q==\r\n"; c[128] = "kiMuF/1CMRlgoS/uLKn1mNZFZNHJNkRQnivOrzj8HQAagwzvTXvsGgI9hXX3qaeZL9/x/Oq+Y5F6\r\nDh+wXo+0kp6JagFjvbTJcQSowFzIwg7/V9sans0NE0Ejow5BfZKvihFI46sHiALl1qzoXqLQq+5f\r\nZGIFRyyY8wFW1uiNu9k=\r\n"; c[129] = "YXmCWhiNz4/IhyxQIYjgNvjX+XwDiPTSBMaFELm5X8Y4knGRnkF4/zix8l9wHBb+7Cgfrr46rF7e\r\niIzaAFLjLjjewy63duBJiVbEWjqFO0fu6T9iIjuEaF2sTppvuZNPHx80vN+HLAnAVmgFESw5APXW\r\nn15dizvuUfVHd5isCqbA\r\n"; c[130] = "GJfUoBivW5uqDpUxTRfjGWNYfN3/dTFtdRqCIH5L2c1nWX0dgY3ba1+fW/YX1Oh5aw4lC6BIiiTh\r\njJoV1VrNnlXzbcUcMy+GsDUUB8Qe8lBvfe/t4RmNPB0hVgrS89ntbuU0SsCmWw+9DqM3nidPebAN\r\nKERig1zZTBBKgpVf7HPFCA==\r\n"; c[131] = "eTerNs7dOqJAxAxcMQRnUDc2cBj2x0jU1g1D3G+b22kDz7JBzOy/mxhGXAQ3130lavWMhImSBkRe\r\nU+z0A13EYVMUv9PFzD747KCvns+SCo52YNHB0896b4l47q8hu8jsD17TZ2uWWJhS4cNnSE1jeM6N\r\noXGKvf90yxfzwucNYc4RdaQ=\r\n"; c[132] = "lbrGsjbzE521q8tzVHV7vcTPchUnzI/UfeR2R+cmOa29YljPWLht9Wx2JrjiKv4Of5nXe7kvhi+L\r\nYUuFVqgaqIFhC/PLbqOFiT2VZcXorToaRT9CLiqV5b6nHN/Txz6SI7MiD3hnk7psDbglPOo+ytqc\r\n9sFHj7UkR1ZctQjwFYwJjlxf\r\n"; c[133] = "mQwAPzYzfxz9FXEiZ6M8u1oN3EJbFYmNVfpm+j0DqgU+OPI4URHBIrF4xvdMvAPn0WuarbQy/ZVN\r\n0eKL7S4K3Mvan0flAwaZdI+e5HpkfxOoGTp8Dk5EFTXjmZ/s+GonePEQEGNVPL1WYoD6xXqAAvML\r\nKtyrFcpoiGS9eDBlsZDQzPzz/g==\r\n"; c[134] = "3G6d12UY4l5W7Nnw0BL0HnViVg9SdEuLMqeZwy0RlJR/Ytcgd/mIxIuXXAlGhvhoX6Xc2BGU7RpT\r\ni1jYKzA86yul0j96dbcE4OtrP9lUBJlcY9eWz59dvLqKxwt3cEOBwrPf69MHuIa256es3AOCobfC\r\n8RQScW0PQ0QUa1VHB/eXSsVTSWg=\r\n"; c[135] = "AxgrZKTFk5JvLC3DBACHwp266FxKI/yn9F+1tYkzL57RVs5HCJYS47VuG0T0E2wqzHqcLKPQMZWU\r\n7vbRoyMGNL3ZtaHoZqTqcq9KWtODC+OnEvSS7+1P4SmQDuyL2MJ/eJABJKNcu1K/Lk0buAaO0FvX\r\n6OGBcPzu1+dv/ZkwuORK07qRnxqQ\r\n"; c[136] = "atkG8l2U/Nnm+zLu7zjenrfcAVQJMUqHimFZ3cQfaUp4qyrFn1UiwZ33j66Vt63eVaT/FXx+LlEn\r\nsHn6ATPBMp3iEYoBJYyNpjz/zROhBbcznQAMdWUTcyKInvnG3x6ExgBXpyqfxxp/Pm8by7LlSUT5\r\nMKHdcu+TEfUXRokCr2iPnt7NYsNDfA==\r\n"; c[137] = "dciU1mSHGcBxOAVBgJx75J6DaQdBZfTIzQ04WhkkdRMupOZWSnv19xhz8hiO+ZnbBtDJuO5rHsUG\r\nzH/jYacfZyCQ924roRvkh3T1yxsLq3abZJUCD9HYnPTELVhv1+cEF4aoO3vGOu2FpfLUn5QTd0Po\r\nzsIqcqZVB2V57B7DjfizUe3D8Yf5Vco=\r\n"; c[138] = "dgR1PPacBvtILBmg33s9KWtuc67ndh3rCHZ/lIN7sENgbFqJQy5DC3XIeHTV7oWd+tJQaXxoC71/\r\nSU7Rz6OClAMKXLbMz8U6RPiqn3M7MRCQcDfNjA5cCNknXT9Ehz/IZF/7lcWrwxBKYm4B98lPkpZt\r\nR2QHndiQ3venzWrP0P5y27mReaFuaJ++\r\n"; c[139] = "1Q8rfp1HuGsxurTgGMakxj5SwNF7EixXxVPnfGADWDcygh5C1BMXqiL1AuVXOVFOsaydfLWGC8Kb\r\nh/JiL6H+12lYrNGUT9yJRIzRDi4XylMnrYwBtwCJjoHSi4exz5K2ih54utVAuzXZg6mnc9ied/mN\r\nRjj9d2HFD5mv0w/qTN/WFxEmtuZM/nMMag==\r\n"; c[140] = "w01TnPP/F3Vni3fBdV32Bnbb4J1FcbaE+Xn44no5ug77U8FS1gSm3LqJ8yTyXduzl5v2dwBEfziE\r\nfTuyqgeLLsCYTBjXmYOIHQosEl6DyAknu4XK52eQW+Fes9eSs2Nq+G4aaR4y4leeFNmCoZ9BQmAA\r\nZr0LFkqnvqaKmBVgcgxPs7/8SQHnpqvaU6Y=\r\n"; c[141] = "OfzIF38Tp5g1W5eVbrkrMe0Mm7e0wBYg5hVvLpn/5MW5OFcmRDuBp15ayRBnJ1sBI93+CNl0LwP8\r\nQ0z9IXFjTER5gHZ1KfG8NV+oacKNG7aYrbUftkSL/oPfRNPez6U0FuWgvVrXUB6cwKTWvwb9KoD7\r\ns6AGYRdH50ZgJdBniFD7dKoOQnJ/ECuTUXI+\r\n"; c[142] = "4hoX0sjqlkSJPUq627iJkNYRbtD+V2qErCuTikaeRDEZvVHWvzdvwj4W1xxJjz+yHAN6z2EjCWid\r\ncSsVgTejQ1bH8uTzJgh/zq3yGUSsJoJWrecqxsge8bEBjkm+qUO8G3kAnC6FMjJ2NYQeXf6OK6Og\r\nsqyJwlHPTyAms2/IoYTB4iEqgIFG/2fNEJEIag==\r\n"; c[143] = "M/dy14xNbZMRfHiKKFdmD/OrEB+8MexrRO8mMh0i5LrNA5WUtLXdwUfAysYmal94MSoNJfgmwGCo\r\nqNwlWZBW1kpQaPdqsrn2cvc6JcZW9FlOx07DERJGbZ6l6ofbzZWgF+yf+hvT6jnJvXBVCTT3lfO3\r\nqo4leNuEJwsuU6erXGC3Ch53uPtGIrdDUpcX6/U=\r\n"; c[144] = "GgLr2hd3nK64IZv0JksKAT/yJNQ38ayuWyBnWLjXbEmT048UDppsrrnP6hikRo5v2TlHGhD2dcwG\r\n9NLK3Ph8IoIo9Wf2vZWBB+SMI9FpgZxBWLEjwHbOWsHaEQMVsQfk38EWQP0Fr6VyMKlEQfpsRkuC\r\npp1KxscaxK7g5BgXUlb0a2x0F+C9hEB0OVPsj4JN\r\n"; c[145] = "W9lKcLDqNGQAG/sKQNaRmeOUmLJ7GcMNqBaGZ659Rnjr6RTrfnmkp5Z9meALnwXoHjPjzSQDJnVY\r\nsY+xyMnuPgl6gMVAhAm+XprYVpsne4vt+7ojUqavVPBqLy5dtnhp1qfcnAiV5cZhHXX7NbxkUOzp\r\ntjEGCQjnhSH4rPbZtgoIWE8Z6boF3l/thLnFX+AiiQ==\r\n"; c[146] = "iYLn5h9lIhD/x9moaPRnTX6mJEJKThg4WXxS7IrR2zblH26uOkINz0dJNTJVets0ZNYDnsnT7J2i\r\nI3Y6hTVWPGoYU49J3B2LhCREs0DZQ3C7080FtiOcfHbfBLNn0DyCK1LeAC7YB/bNdiyhLqH8fKl+\r\n0+KhiPDIUBJY2e7IbZR/9t0sxJbIXx6cRvI5AXex12o=\r\n"; c[147] = "SlRJEc7npTUvQq8SgBYKmVY/3wHYp2gsDxafN/JLUuEqEjmWMtW7fxASi+ePX4gmJJqLhD5t+AZx\r\niCwYK3L3ceuJx4TiqVgJz8d6sc7fgWXluh1K+BcGPbZ7+Cq4Vsga7JEBVekviEZ5Ah4apNr8RkB7\r\noMOUVPGxRcyyaVE4zBW+scA6c1yi/HQXddQ9rWyLUsVo\r\n"; c[148] = "AAlbGR6ekLOzx4hpqZTUqVUQ0FL2CFpgCMOp6CuuUzkSnWXpUjvOiSDkNPgoTPgpgmg3uYvMsX43\r\nmkPGUGC9awDThXyGQh6u3WfWtmhiPRqXnjFek+EPd0LYXps71non6C9m7nUlYNWzBJ1YzrzWjlB5\r\nLLPBN8bsZG6RbdZkYMxJ9J5ta/c30m8wDDNuTm0nEE0ZVQ==\r\n"; c[149] = "nWWbBhzObqwEFh/TiKREcsqLYbRjIcZflJpol16Mi4YDL6EZri22qRnTgrBtIY+HieTYWuLaCSk/\r\nB9WcYujoS6Jb5dyg3FQ6XF9bYaNQGx2w8DHgx0k2nqH/0U1sAU0kft32aD2orqCMIprbO1WJIt2a\r\nuRnvcOTFoOax926nAkxvR3nrFVDevFjDbugpWHkGwic6G7o=\r\n"; c[150] = "WNk1Rn2qtG+gk0AEewrgo+aRbNrG4CgQpOR8Uo7c2m2XQY8MVDu4uRA6rzYGGdgqTcICKky9MvHe\r\nJeNWVAXOxmA4EdXQ2xItFJdQtxBt56cad9FBXXsz21yVsPr5d453abi7T3XfHVTToekiOlxAJs+b\r\npat9cFRbIdHghO9wc/ucoArT53vpYsnyeVnmZG2PX48lXpNS\r\n"; c[151] = "wVmiO6mdf2aahrJlcmnBD0Qa58y8AvzXtJ54ImxgPLPn0NCQIrmUxzNZNTODE3WO6kZMECaT/REq\r\nT3PoOBp9stCHCFNXOM7979J44C1ZRU0yPCha00kQZBF5EmcLitVCz10tP8gG1fiIvMjwpd2ZTOaY\r\n4/g4NeJHLjJPll0c5nbH7n4v+1I+xG7/7k7G6N8sp21pbgpTYA==\r\n"; c[152] = "OoiVZosI+KG0EZTu+WpH7kKISxmO1zRYaSPMBMW0AyRiC2iZVEkOMiKn12XPqIDSW/kVA58cvv/y\r\nsTAzKLTu78Uo+sVcJe3AtLdgeA9vORFELTP4v9DQ/mAmehe3N8xk+VTLY6xHWi6f4j9cTDW/BDyJ\r\nSDRY00oYoHlvnjgHo4CHBo0sMGgX3CwcnK2hpMFVtB/3qPl6v2w=\r\n"; c[153] = "97ZVsTYwD8VrgN1FOIRZ8jm8OMgrxG3o1aJoYtPVWXp9cjjlgXqTMZVsoWr3pr7pudw+LYo1Ejz3\r\nJpiUPHqWcZ2PWrWs7PR1akYGuwdCBHYvCGTcZYFe/yu1AB8w5zYsl1eJR45g0u1DlXfx5BUAUzc4\r\nyJDjc48Ls62bn8t0EJ7+30sWwifqKuz2EHpsqp1j/iMlwzKJGjGE\r\n"; c[154] = "0NSYKTvBKKInwL9PJ/pWUWVX4gjF3igsA2qqQMsRew0lI1LcCB18eGCYk0AnyUCe99w5lWHGFUMM\r\neH6DZciAylWGeDn19JdzVOTevBWk3LIujI1GvsEB3oVqf2Zl9IZeDGCT4+bQKBWvgcXHjysZfnn/\r\n5z9Xz06qrPqac5LfS36fDcwnkrUYQWDsL2Ike32ALmOnkcDjNq1BoA==\r\n"; c[155] = "5ok+rYI4LCgGa2psGUN/fdkT2gQEToB9HRiFXQpe2YcQvEN2z7YlJCETx4jSWw06p5Y8tZcp08mo\r\nKNYwUJ40DvPpGlDG+wUpFhC4kkfo6vj6TrCj5yoWJi5D+qdgH2T0JeWM80cYN0bsOsetdaqNhDON\r\nlYXZ2lVYkyVS/wzw8K5xX87EWktwOwFq/yYhuWCYJ9GZL7QuDipJjEE=\r\n"; c[156] = "KHzTalU9wPSnIjh5g0eHi1HUaFufxJpXpjDe0N3wEKINqbgzhbj3Kf4qWjb2d1A+0Mlu9tYF/kA9\r\nONjda5jYfRgCHm5mUrjU0TAyT7EQFZ2u6WFK/sFHP++ycJQk8k7KLPUWA5OWScy1EO+dYF4d0r6K\r\n5O+7H/rpknxN6M9FlP8sH83DXK1Sd+UXL32D+4flF580FaZ5B3Tkx3dH\r\n"; c[157] = "RrJVxIKoDXtCviWMv/SXMO42Dn6UWOKDy2hh2ASXssT0e+G6m7F1230iJWlEN0wBR8p+BlTdBhQr\r\nn25098P3K16rBmZpzw/5dmesIJxhYPaM4GiaOgztFjuScTgkmV0Jl/vZ9eCXdEVNISeXkIixM4ps\r\nsTFuUV7PY/Upzdj55rDKGLr1eT7AFVSNP30PhL8zZs8MANqKBeKBBDvtww==\r\n"; c[158] = "sy4t5rFA75GRBE+Dqa9sQxjPluKt/JnEY54guHnKqccmx3HGiyJ0jUA+et4XO8Xg69wCA9xVxJZQ\r\nL73z80mVfIf43HIKOxgxT2IjG7EKMOD/qx6NnMTve4BryggLtbLQUeRfhriQeY7h65tD9ierhccX\r\noXDpGnmBn9m2BQP78y+Qhc4eIsa3LcxbQJUIwvURjFp/rgMD7lhOLboa/2Y=\r\n"; c[159] = "Zs/BfFoWImYau2dZLb7JneeTQp7sQ06yonEq0Ya4BNOJGy/5dGH42ozt0PpP2IZ/S58X7esVgc6j\r\nA1y3Bcxj3MPoDjQJSZHFEtR3G31T8eF5OpPVC4dw9s9clllM05tvcemssLdcd85UP/xBaDrmpAl8\r\nZDSc73zflK3nJw8e0HQFYntNnlZPFyyyBLHnLycb6Jlvq7F2OqrZR+FXZnL3\r\n"; c[160] = "hdeDJuRnmb8q9EYec8+futT/CvqhpqoUdtmG6E31RrYJDs96M5Wfng90IEqrncZe4rVYDocRZK23\r\ndvqtJaPhTUBXXh42IyMlUnro69KI+075FvYYwgVaUd10r7ExWM5Z7DCQ2x8Tm1meK2YCTPkF1VXX\r\nexl1UjYCnRQuQxppdophMwroJK8VqlJbFFslchTSBFuI7wgcdy+f/LHMbMsusQ==\r\n"; c[161] = "ClCCOv0mD9//LR0OisHfamxcTvmlwMLgAIQt3hbOjRPkXwEgaDzP0u6LN8BNwdOVw+LhrbzMI8zQ\r\nzHvo7mGPkQICeeim/x+xmGPQtmWnXxCWiL1uf/8eR5Wuy9Er8skTB8rG4/ubb2ssvCkubObPAkMS\r\nOgFnX9UtxnCN4+nMNV2vvn4xMTSvvQyYWewfnlNkflTyva1epE9RVW2RqRtJikY=\r\n"; c[162] = "Fs+AmFCnUr/imw8D0GpNidIP9qwW8yRAzmtqPS+vT6n5U4YFQcpgbznrYO4TPqkVF2oz1mpgLYIg\r\nx/u2XsrtljGX46LfY8OyUPaw4/da38QGngoIlS2cN01cgN3efSjMlnZFo1x8T9p0Nn1IgRgevOd5\r\nezVUL7WdY7eeiE1pXXcGBgDYn7NDQph0dC6HDlBiS95bDFcZ+6FYigE4WybpsOHL\r\n"; c[163] = "wgO4DdGZy9g13IuOhkJGJcToyLuCBVm9T/c8qY4NOheVU1NW2g8sPIo+RiEsSST8sx6+Jh/A/kaC\r\nxYvJ9CsgnBjZMMWRsd383HZAoJtkxwKvyoeXzzD+puFvqKQBEKrlBEwffXhLDoFQAW2ycYtBGztl\r\n0GsUtoOob2nv7ienx1xD6KNZNaxYx2ObRAYS/e8LS3pg5dku9MPBp1X12m8ZIXRAaw==\r\n"; c[164] = "EkXt02SaRUIjFmoLxyO6N+giL4iA4fY0Exao+mjgEfZ+Wv6w95GXHBI1xlYMVLkOcnu9nescvcXQ\r\nH0OrqL9uforEUTGTSg2ci67m4GrwAryMy+5eUo77Q5GpWKfsg8nDbD8a3gUI/9EE0sCNp7tMaKwo\r\nJ56cxhbG3TJYpqWTpq3/S3q76x+3ETL+zxh6EMh8MJPfWcIxlDS7evKqdPgS00KgUtk=\r\n"; c[165] = "OuBqx5LFJroRbDn41+4azFHlKgw6bMgbsRGaK9UnPvi5xfmV4SLQ2YzIhopGi1F57L6vKukaW0Xl\r\nFk/Ff5Td5IMC7U+kvXKlf8fGIIQ8FaHI0vbIX89OJlBqlICqftSNiVRxtaE+aCh0rBoDfgPwuC8q\r\nBC20I1O3ZLuKfeUVGkMOLEWeZLS6mmcn3cSERj9o/dEl8QYwQvhH+VG6YWF//yki1Vu8\r\n"; c[166] = "SO/vDsqZDdImOdH19sZI7FUVhlx1EI0XRr8ArTuAG5F8LDK76Bct2C7fXTUowilXnJWhQxvbGiul\r\nkUGSuVjVP12zac9bShRpr1L3ucde7n1f9y/NcHJCwdqTLq7RYygItQ4ppQGiP9jXf2Dn/qmVZZTh\r\n+SY3AZCIS+OVo2LAiYJHWnzzoX8Zt+dOYiOA/ZQKZieVJlc8ks+2xqYPD55eH0btZn5hzA==\r\n"; c[167] = "tZL/qACMO9SzmgJhWQMsbKgE5lPAEbxn3NR7504ilgArR8j7uv1KF46uQyjrkEnyBormYB/6nLGl\r\nHht62IQftMYf5gHpHFfTvukRKF8728yIYAAYHPQ/WjHzHdVSqUJqF2a8RE6SvvY+KSKWLMU3hjn1\r\nf6dqX599hYD7AnbPGTpFKDU5sLFOXbuynU1sPUhP+a4Hev9yNU6atLDo4CkX/Yq3FbpWVuQ=\r\n"; c[168] = "GRe7uF1wH5/71B3vmGF+pN3H9PKO1tLwsnb0D4/Pm7Pu5KAe4OfelkfFIBgyjuoZrpeEkGZnb+qf\r\n+Kn7Kt1hDwYr/Mb9ewuwOXsbIpLQMgfh0I5XsPrWocduVzn+u/cm3cr0Z11zsx0AZjTqvslACkDq\r\niquY41JhtGdc22RCvIYom2l+zzMIMyCPsHeCSB1MBu8EWK3iP7SD3dWttwzMg0xanoPDgk0U\r\n"; c[169] = "8BDFu+29lptlGSjcZe7ghWaUgIzbuUpM5XDFbtJVQPEd3bAE0cGRlQE9EhKXi5J/IskYNrQ357tB\r\nhA+UNDNXCibT2AZGpzWAcwE6dP+14FuRL5Gxqh/teuPYKr5IIn7M3SbgOychZzLI7HGCvVhBUiJB\r\nu8orI3WmAIVcUhAsMGHsFveck/ZCXQA+Uq/WVnW1VNs6hSmIhsAFc51qsmsQK07z2Wptx4rRjw==\r\n"; c[170] = "siPSXD4u36WYtTvvDzRlFPiuZMnRczrL3eA15955JDCc6/V2Cvu6m/HPO6JxogxO0aYTZ5tejYDO\r\nIZgBy40DgUZMqPJ2IpYjsmUbjjJU8u/OpwhMon525m3v0EYlvyj2Qp3pwFKDkvncK3aNjN3KaaX6\r\nHuIy6kyqsDl0BTEnB5iJyHLRBCkeznTK019u48Yfsrz2oGuZcWzNj5/vKMdxQPiyJ9EHyox8Ark=\r\n"; c[171] = "+/14PnFQVZ7BTHKUvkTtRrYS7WnPND5gZ5byMhUrDLkJa6UPBV7z0nrDMifEo/dQfUq3EjCiG6xG\r\nVhrUvAzgxqOQZTW1Y9p9M0KWW+E0XvCQppHFpuMqF1vYsF0OD6AMiE9JtGnWs3JcaWP/XBF/CvhQ\r\nlFGbHi3fbrD/haTEBnmpJWBgMdKribdbXHtBSFZ2MzCX2eDtxoDdRdEVGs4v/q8gVBS+WsnZ3TTF\r\n"; c[172] = "31I1ja+B+aopKkztGzJYvJEWAshyoAAV5yve4LnP0kdImUQaVETSuo5CDIYr7zM8MCD1eYPpLicm\r\nGnA+C927o9QGAVL3ctO/DCWhNinW7NmeYIM+o4diKBkDPjHmSWa+nq4nr+gOap4CtwL2wW2B5Yqt\r\n26pKgN9uAU5CmTL26hYFgMEOZfrkQ7XdYGy2CN8RJLmjeSFVVNBG/FTaK7tpuy0LQSkko6wczBYG\r\neg==\r\n"; c[173] = "XbRfDqGe3eeI1tHx8UnPneDB57N8VeSSzXzVCNSgxOEfd6d/un5CDxHG+m4w3tIbtSky4R2+zMF+\r\nS5cRvTOwZ/veegYtLKTxA0mVedWLFkfh/v4NgPJ+NEU+cylbSSZLAeBofDvoJwnYKujN2KFa8PGA\r\nxr3Y8ry3qdkS8Ob1ZiHYAmLvKS9sGb/vjTvRy+a4Q7kOepsm7PYisinKelBAvDnjli6/lOutGren\r\njX4=\r\n"; c[174] = "jGEj/AaBefac9uOcmGuO9nH+N+zMsC4qAe6ZUEMMIXdTGnSWl7Xt0/nKqyOj3ZH249HwkJ8bn5C+\r\n0bzOpQ1eA3PxEq6RfKMrjHJPJmTZXrSESTjfj3oNLU/CqqDOqd8znTgN6nvnUdCeStLMh9bmWF1+\r\n0G11nDwg6GQWWQ0zjVDTq5j7ocXcFOyUcu0cyl5YDcUP0i2mA2JullInU2uBte7nToeSGB3FJxKu\r\neBbv\r\n"; c[175] = "RAzNCxlP2S/8LfbGtlSDShox8cSgmJMOc2xPFs8egZVJiwlmnS3aBWKPRbbxkZiVVYlu4GNJNwbo\r\ncc6dgrl28HXAsYikE5wwoQ1MeOJWU3zzFiYENh7SLBQfjVPQHucctr8P6Rl7YL5wHc+aC+m92R3b\r\nnzm5rp1PeHm7uzy2iUUN0cgfbwJ4FrpXhVMTsAUpTbg1+037EWcGOuxir4dG2xBfgOwa+ejFHkw7\r\ny0LWRw==\r\n"; c[176] = "08hmZptBGKKqR6Qz9GNc2Wk1etgU/KogbiPQmAh5IXlTBc97DuEToL4Bb889nfObVQ/WelmiCS8w\r\nEjSBdmnlkkU7/b5UT3P4k1pB6ZxPH9Qldj5aazkA/yCb0kzDfJlcdFOh1eAcu5LvwTXOizmPwsDv\r\nJEnOkaDZrKESZshsHU2A6Mx6awk9/orf6iBlJHQIIH3l4o3b1gx2TNb/hUgdAlwtQDhvKO3skB0P\r\nS+rcWAw=\r\n"; c[177] = "0GhrgbSSHPLWtyS2mnSxrNAj/dyrFQcxIgPjT7+78SZ1ZTGc03vsmlZ4Z/bOO84E9yKblaI5dSHV\r\nXrx57L0kikL8tgKCsAkUNO3l/4zv5FfCrRTgGx4sFTFB1NNcLcwagkvFzde764DjYmj4YZhYsXSZ\r\nCVKi0uu5M8fpgGDZ9UMSFR008cbhaIoFLWSANqiNJYSvTQZhGWfLtIPGLN+gIOMcaKhx1b5vg6OY\r\nSz6ScAM/\r\n"; c[178] = "2VGiMV/f2hNZAjw3fdeHx/wRIVzeP018lZynzwSySG/zQBxyRmi3YmKVZmh3aJunuiqmvdt0kJ6l\r\nX7M8BajYHPCBkqJOx8oPJ/K1oADxVgnavZ69dKYrSy9/Pm6sHxjFrdSz9TelUK9sgoFTWS6GxgzW\r\nEqXRBDDpGUnsNbSEcWLPKVLNNoYAcltY98JZaNSZBXcpa9FeSN7sVU43q2IEcDx3ZkJzRJpl/lb7\r\nn+ivMwX/OQ==\r\n"; c[179] = "iMSCh1m5vct3C7LEn5wKRYtalzvG6pKahG19rTb6Z9q7+buDsML5yM6NqDvoVxt3Dv7KRwdS3xG/\r\nPyb7bJGvQ2a4FhRnTa4HvPvl3cpJdMgCCvsXeXXoML4pHzFlpP0bNsMoupmhQ0khAW51PAr4B165\r\nu1y5ULpruxE+dGx/HJUQyMfGhOSZ5jDKKxD5TNYQkDEY28Xqln6Fj8duzQLzMIgSoD8KGZKD8jm6\r\n/f8Vwvf43NE=\r\n"; c[180] = "hN4+x/sK9FRZn5llaw7/XDGwht3BcIxAFP4JoGqVQCw8c5IOlSqKEOViYss1mnvko6kVrc2iMEA8\r\nh8RssJ4dJBpFDZ/bkehCyhQmWpspZtAvRN59mj6nx0SBglYGccPyrn3e0uvvGJ5nYmjTA7gqB0Y+\r\nFFGAYwgAO345ipxTrMFsnJ8a913GzpobJdcHiw5hfqYK2iqo8STzVljaGMc5WSzP69vFDTHSS39Y\r\nSfbE890TPBgm\r\n"; } /* Here are the randomly generated byte[] arrays we generated to exercise commons-codec-1.3.jar */ private static void initBYTES() { byte[][] b = BYTES; b[0] = new byte[]{}; b[1] = new byte[]{-72}; b[2] = new byte[]{-49, -36}; b[3] = new byte[]{77, 15, -103}; b[4] = new byte[]{110, 24, -44, 96}; b[5] = new byte[]{-43, -61, -67, -75, -33}; b[6] = new byte[]{-80, -52, 71, -96, -105, -7}; b[7] = new byte[]{-115, 7, 15, -108, 59, 25, -49}; b[8] = new byte[]{76, 6, -113, -99, -11, -65, 9, -123}; b[9] = new byte[]{113, 116, -39, -69, 12, -41, 60, -29, 82}; b[10] = new byte[]{46, -39, -1, 101, 53, 120, 34, 52, -6, 56}; b[11] = new byte[]{-23, -8, 126, -115, -43, 55, -43, 35, -90, 90, -73}; b[12] = new byte[]{19, -2, 76, -96, 62, 42, 10, -16, -18, 77, -63, 64}; b[13] = new byte[]{-38, 127, 88, -55, -16, -116, -56, -59, -34, -103, -69, 108, -79}; b[14] = new byte[]{-88, 25, 26, -36, 26, -70, 87, 125, 71, -103, -55, -121, -114, 70}; b[15] = new byte[]{90, -4, -103, 123, -87, 16, -14, -100, -69, -101, 110, 110, 113, -84, 9}; b[16] = new byte[]{-95, -118, 113, 51, 46, -127, 74, -106, 87, -123, 90, 78, 71, -89, 87, -104}; b[63] = new byte[]{-55, -20, 69, 104, -46, -102, 63, -27, 100, 87, 1, 20, -65, 20, 23, 108, 45, 7, 72, 40, -65, -78, -77, -104, -19, -51, 55, -22, 84, -10, -27, -6, -20, -29, 24, -56, -66, -99, -75, -32, -111, -62, -125, -77, -117, -3, 118, 86, -36, -125, 30, -24, 32, -32, 72, -64, -102, 104, -113, 117, 121, 24, 12}; b[64] = new byte[]{-66, 74, -96, -98, -30, 119, -90, 92, 77, -74, -117, -34, -120, -62, 110, 96, -77, 122, -63, -108, 11, -91, -67, -59, -125, -113, 63, -52, 121, 29, 22, -32, -18, 114, -29, 10, 89, 84, 78, -2, 120, -123, 70, 2, -84, 22, -89, 49, -85, -91, 96, 11, 28, 16, 109, -29, -30, 63, -37, 17, -97, 28, -5, -62}; b[65] = new byte[]{96, 121, 44, -36, 96, -101, -38, -27, 69, -29, -74, 54, -76, 40, -98, -120, 49, -119, -13, -65, 81, -101, -105, 65, -123, 8, 80, -117, 54, 33, 125, 99, -88, -8, 26, -63, -37, -14, -66, 19, -68, 25, 89, 56, -99, -41, -119, 76, -92, -50, -76, -5, -112, -76, 55, -46, 77, 40, 7, 1, 17, 39, -86, 101, -110}; b[66] = new byte[]{-49, -50, 121, -42, 57, -112, -89, -12, 44, -9, -101, 112, -37, 110, -66, 28, 33, -42, -82, -30, -79, -4, -101, -33, 4, 39, -48, -26, -99, 31, 23, -66, -26, -111, 42, 105, -21, -95, 57, -25, 104, -92, -38, 12, -100, -84, 16, 108, 48, 47, -51, 111, 57, -64, -127, 54, 104, 51, 54, 113, 122, 23, -55, -62, -18, 61}; b[67] = new byte[]{86, -60, 118, -62, 26, -86, -2, -92, 38, -33, -115, -66, 76, -36, -11, -106, 3, -103, 50, -123, -101, -92, 44, -2, -110, 61, -77, 126, 90, -76, -97, 30, -46, -3, 23, -124, 84, -11, 9, 114, -88, 12, -75, 92, -21, -81, 97, 85, 64, -9, -63, 0, 126, 85, 70, 52, 126, -122, 76, 112, -65, -122, -20, -79, 9, -84, -15}; b[68] = new byte[]{-25, 25, -120, -89, -57, 84, 37, -100, -28, -118, -62, 36, -72, 67, -20, -100, -11, -17, -52, 55, -116, -93, -113, 42, 88, 87, -57, 34, 125, -102, -65, 120, -21, -26, -86, 25, 28, 43, 52, 45, -13, 68, -55, -22, 66, -34, -3, -84, 107, 73, -62, 83, 65, 101, -86, -55, -125, -55, 50, 57, -1, 104, -19, -25, 59, 11, -75, 93}; b[69] = new byte[]{-76, 97, 32, 94, 56, 37, 80, 31, 77, 108, 43, 98, 75, -49, 0, 122, -46, -19, 70, -88, 66, 2, 120, 115, 57, 66, -107, -126, -10, -55, 100, 122, -114, 3, -84, 124, -72, -22, 43, 3, 91, 119, 53, -58, -120, 3, 77, 25, -87, -77, -40, 0, -69, -72, 47, 50, 38, -30, 46, 37, 0, -65, 80, -126, 33, -1, 38, 14, -37}; b[70] = new byte[]{-128, 91, 113, 18, 22, 9, 106, 16, -26, 83, -105, 105, -71, -42, 44, -23, -108, -20, -88, 12, 126, -77, 104, -2, -45, -96, 52, -51, -20, -101, -35, 78, -25, -123, -111, 108, 110, 64, -125, -107, -37, 52, 17, -123, 40, -87, -22, -39, -87, -109, -26, -20, 94, -126, 12, -29, -125, -35, -43, 59, -99, -119, -98, -108, 77, 3, -57, 35, 14, -12}; b[71] = new byte[]{-113, -8, 127, -44, -100, -96, 96, 14, 91, -114, -37, 113, -51, 12, 107, -26, 0, 109, -126, 31, -128, 97, 90, 51, -124, 94, 22, -126, -9, 20, -2, 14, 61, -65, 72, 84, -53, -95, 93, -123, -10, 94, -64, 98, -66, 62, 27, 115, -113, -76, 90, 108, -114, 105, -37, 53, -14, -50, -7, 38, 45, 7, 69, -123, -46, 57, 82, 110, 14, -26, -52}; b[72] = new byte[]{-101, -23, 24, 84, 106, 35, 33, 30, 105, -127, -68, -5, -92, 98, 102, -38, 15, -73, -86, -87, 59, 126, 25, 119, 114, -116, 26, -39, -27, 107, -122, 72, -69, 90, -121, -14, -53, 9, -47, 123, 58, -109, -60, -23, 1, -127, 81, 115, -22, 114, -84, -14, -84, 105, 109, -74, -13, 0, -73, 45, 112, -9, -116, -78, -97, 93, -91, 117, 31, -71, 66, 107}; b[73] = new byte[]{-92, -10, -122, -100, -54, -12, 81, -119, -91, 118, 114, 85, -109, -15, 126, -35, 96, -119, 39, 90, -10, -94, -37, -61, -28, -94, 93, -73, 107, -75, 70, 116, -70, 47, 8, 71, -121, 2, -62, -87, -11, -68, 59, -12, 4, -125, -115, -42, 119, 18, -88, -104, 98, -1, 36, -51, -9, -74, 127, -63, -10, -109, 15, -96, -123, 52, 65, 49, -93, -85, 97, -111, -93}; b[74] = new byte[]{-104, -20, 115, 27, 44, -90, -23, 63, -63, -60, 37, 121, -99, 40, -120, 96, -55, 95, 1, 73, -126, 55, -72, 45, -17, -26, 83, 50, 13, 100, 119, -61, -19, -118, -71, 62, 36, 94, 93, -109, -59, 18, 109, 96, 110, -1, -42, 111, 54, 14, 89, -70, 34, 66, 120, 108, 31, 105, 90, 106, -91, -99, -54, -9, 36, -123, -20, 47, 59, 38, -5, -75, 69, 65}; b[75] = new byte[]{85, -126, -50, 32, 78, 3, -98, 28, 73, -97, 113, 74, 75, -3, -111, 28, 113, -40, 46, 86, 98, 25, 87, 85, -2, 78, 46, 5, -69, 64, 96, 117, 18, 78, -108, 115, 105, -90, 15, 24, -48, 21, -115, -45, 112, 109, 49, -56, -118, 25, -98, -70, 79, -7, 97, 5, 50, -16, -47, 108, -60, -118, 38, -8, -72, -69, 110, 117, -94, 6, -127, -54, 4, -13, -5}; b[76] = new byte[]{-19, -6, 12, -92, -99, 19, -110, 112, -102, -74, 53, 34, 75, 27, 103, -72, -92, -94, -49, -124, 47, -105, -8, -99, 89, -113, 84, 42, 36, -27, -114, -124, 7, 103, -32, -68, 109, -59, 44, 114, 114, 63, 109, -102, -11, -35, -18, -128, -65, 37, 33, -29, -77, 37, -91, -47, -81, -52, -119, -76, -26, -91, 29, 49, 101, -117, -95, -110, 78, 104, 102, 47, 14, 107, -21, 89}; b[77] = new byte[]{-113, 20, 18, 26, 33, 108, -7, -67, 83, 124, 78, 37, 13, 64, 15, 80, -14, 116, 73, 103, -108, -126, 93, 55, -84, -82, -102, -70, 39, -106, 37, -58, -85, 12, -127, -52, -9, -72, 6, 56, 115, 38, -56, 123, -99, 68, -54, -92, 102, 98, 36, -59, -124, 96, 98, 0, -126, 82, 15, -55, 121, 79, 117, 57, -112, -9, -76, -66, 20, -5, 3, 97, 74, 28, -80, 123, -49}; b[78] = new byte[]{80, 105, -121, -2, 9, 123, -73, 112, -28, -13, 77, 111, 70, 20, 67, 17, -72, 44, 125, 40, 109, 29, -99, 96, 101, 9, -8, 40, -42, 121, 66, -52, 55, 90, 33, -93, 91, 66, 38, 34, 117, 71, 107, -30, -46, 28, 28, -53, 82, 60, 2, -47, -99, -25, 92, -18, 34, -29, -32, -94, 41, -118, -128, -78, -109, -107, -120, 78, -106, -87, 85, 24, -15, -108, -107, -48, -24, 56}; b[79] = new byte[]{-63, -47, 40, 98, 98, 110, 70, 120, 54, -49, 98, 36, 2, 36, -96, 39, 80, -106, -39, 81, 59, 31, -70, 23, -91, -123, -124, 20, 83, -68, -100, 109, 27, 102, 126, -49, 30, 20, -4, 43, 40, 90, 59, 106, -30, 118, 95, 30, 80, 76, -84, -115, -83, 21, 92, 80, -14, 66, -92, -96, 102, 123, -35, 80, -86, -62, 25, -22, 86, 25, -106, -16, -45, -3, 27, 15, 11, 55, 2}; b[80] = new byte[]{-26, 70, 106, -126, -75, 27, -73, -22, -51, -28, 21, -128, 117, -41, -108, -74, 111, 83, 25, 62, 55, -67, -118, 65, -24, -9, -78, 67, 4, -14, -53, -43, 91, -81, 79, -108, -1, -124, 51, -53, 66, 48, -33, -76, 90, -37, -35, -57, -102, 73, -87, -127, 12, -18, 73, -59, 105, 112, -120, -123, 25, 115, -64, 21, 108, 19, -95, 31, -101, -94, -4, 46, -19, -91, -29, -117, -15, 103, 51, 9}; b[81] = new byte[]{19, -114, -69, 48, -55, -119, 110, 108, 47, -16, -23, -100, -39, 55, 92, -56, -54, -1, -33, 64, 124, -117, 53, -101, 127, -32, -128, -72, -101, 112, -21, -74, -11, -125, -37, 107, -124, 46, -89, -32, 102, 39, 94, 55, -106, -12, 54, 47, -103, 106, 8, 36, -4, 116, -50, -11, 63, 67, -24, 42, -65, 71, 45, 122, 13, -101, -57, -45, -10, -102, -72, 12, 12, 4, 91, -23, -24, 40, -62, -88, -15}; b[82] = new byte[]{86, -101, 124, -123, -122, -8, -113, 29, 69, -5, -76, 68, 95, -78, -70, -26, -2, -98, 59, -111, 117, 24, 56, 63, 43, -60, -107, 45, 96, -46, -89, 75, 43, -70, -106, 4, 66, 64, 85, 71, 25, -63, -11, -39, -95, 74, -113, 87, 30, -100, -8, 11, -54, 81, -105, -54, -4, -39, -4, 87, 102, -23, -90, 17, -2, 20, -40, -24, 116, 14, 42, 121, -82, 115, 109, 12, -65, -120, 38, -14, -4, -107}; b[121] = new byte[]{-123, -2, -67, -58, -65, 102, -76, 87, -8, 55, 120, -10, -72, 15, 76, -128, -78, -7, 103, 47, 120, 30, 59, -2, 85, 8, -67, -29, -30, -46, -13, -34, -10, 36, -104, 3, 28, 36, 14, -64, -2, 112, -123, -44, 36, 87, -28, -119, -91, 121, 34, -56, 113, -102, 74, -60, 56, 126, 23, -87, 63, 12, -18, 101, -63, 41, 96, 68, 126, 109, -23, -14, -42, 63, -116, -48, 116, -103, 123, 126, -116, 117, 18, 33, -107, 58, -89, -93, -18, 42, -79, 119, 36, 47, 64, -93, 94, -58, 36, 36, -109, 52, 52, 7, -50, 98, 49, -64, -70, -50, 70, -43, -72, 34, -11, 88, 102, -120, -57, -64, 48}; b[122] = new byte[]{-56, -84, -45, -121, -104, 79, -89, -33, -49, 5, -26, 109, -83, -107, -20, 20, 112, 17, -9, 44, 14, 51, 120, 81, 104, 16, -28, -128, 111, 68, -45, -36, 5, 91, -61, 25, 15, 76, 76, 25, -24, 28, -89, 68, 43, 76, -105, 15, -15, 6, 14, 105, -120, 83, 13, 88, -90, 62, -85, 13, 77, 83, -90, -115, -40, -28, -67, 47, -74, 90, 24, -55, 91, -119, -107, 57, 116, 60, 40, -128, -3, -41, 38, -127, -76, -6, 62, 13, 43, 75, -28, 99, 32, 114, -41, 15, -28, -54, 21, 127, 85, 105, -13, 15, -26, 98, -38, 31, -87, -71, 101, 124, 57, -71, 53, -10, 51, -121, 96, 59, -118, 54}; b[123] = new byte[]{114, -63, 102, -62, -16, -13, -96, -18, 8, 59, -84, -110, 12, 14, 1, -39, 94, -34, -104, 71, -83, 3, 0, -96, 59, -82, -77, -50, 87, -42, 111, 114, -125, -84, -9, -59, 101, -51, -55, -126, -66, 62, 118, 86, -108, -112, 66, 3, 29, -121, -117, 28, 68, -35, 78, -53, 22, 58, 93, -118, -84, -15, -63, 18, -59, 11, -92, 52, -47, -5, 115, -95, -70, -75, -37, -43, 10, -10, 54, -15, -30, 28, 91, -86, 79, 113, -98, 111, -95, 24, -61, 102, -91, 109, -12, -26, 95, 23, 33, -13, 102, -101, -106, -34, 22, 42, 94, 42, 61, -60, -98, -53, -98, 47, -22, -37, 2, -71, 75, -103, -50, -71, 45}; b[124] = new byte[]{-28, -119, -15, -68, -84, 41, -96, 37, 123, 16, -82, -4, 59, 53, 63, -76, -65, 127, 54, 98, -75, -32, -6, -16, -10, -45, -126, 3, 34, -66, -58, -107, 13, 45, -102, -30, -71, 81, 21, 118, 10, 104, 103, 78, 107, -106, 43, -97, 105, 64, -58, 28, 127, 29, 60, 7, -90, -16, 111, 67, 55, -11, 78, 62, 75, 65, -22, -11, -54, -75, -51, -92, 49, 72, 39, 49, 56, -103, -62, -1, -44, 85, -33, -79, -54, -87, -45, -16, -14, -60, 116, -44, 60, -84, 37, -79, -54, 32, -100, 45, -43, -59, 127, 79, -79, 112, 78, -22, 9, -52, 51, 11, -32, -5, -7, -60, 86, -6, 46, -99, -98, -106, 100, -53}; b[125] = new byte[]{112, 76, 123, -95, 59, 18, 29, 101, 5, 62, 63, 118, 114, -53, 93, -53, -100, 6, 109, 23, 49, 31, -27, 81, 88, -33, 36, 104, -44, -45, 8, -11, -86, 73, -55, 50, 83, -43, -28, -2, 56, -7, -2, 8, -3, 12, 92, 35, 126, -64, -110, -89, -83, 49, -70, -41, -8, -2, -79, 90, -98, 59, 112, -86, -44, 96, -23, -46, 75, 63, -126, 64, -126, -109, -118, -77, 0, -27, 30, 46, -107, -73, -68, -59, -1, 14, -57, -119, -45, 31, -38, -57, 109, -106, -54, -77, 107, 38, 102, 79, 97, -25, -18, 35, -88, -36, 33, 49, -50, -66, 89, -28, -105, -26, 48, 80, 23, -15, 31, 105, 121, 67, 120, -73, -107}; b[126] = new byte[]{1, -27, -34, -75, 86, -29, -5, -71, -90, 26, 32, -84, -36, 17, -108, 73, -112, -53, -106, -83, -88, 116, -53, 13, -16, -112, 7, 64, -50, -72, 10, 92, -68, -53, -104, -16, -17, -109, -23, 33, 42, 28, 89, 17, 69, 66, 105, -105, 96, -2, -36, -112, -87, -83, -70, 18, 47, 15, -81, 71, -75, -100, 70, -124, -44, 108, -105, 89, 117, -127, 124, -54, 22, 27, 22, -54, 71, 17, -76, 111, 59, 23, -53, 18, -43, 75, -1, -117, -92, 47, 26, 36, 72, 13, 81, 6, 24, -116, -42, -81, 52, 72, 33, 41, 1, 111, -36, 2, -60, -99, -121, 17, 39, -27, 121, 108, 43, -49, -15, -86, -81, 40, -24, 55, 110, -127}; b[127] = new byte[]{106, 61, 127, -13, -1, -108, -15, 83, -73, 15, 104, -128, -62, -12, 23, 103, -127, -12, 43, 11, 110, -52, 57, -72, 36, 32, -68, -5, 109, -100, 114, -87, 62, 83, 50, -81, -86, 49, -84, -13, -75, -25, -125, 7, -20, 49, -12, -92, 120, 101, 64, -117, -91, 65, -22, -41, -51, 37, 56, -40, 114, -42, -93, -19, 31, 29, -62, 29, -113, 33, -14, -46, -82, -10, -87, -121, 14, 48, 52, 29, -111, 18, 58, 101, -100, -6, 35, -96, -26, -3, 108, -43, 13, -75, 75, -35, 43, 118, -11, 108, 10, -50, 90, -24, 8, 68, -107, -117, -100, -55, 123, -37, 33, 7, 21, -67, 98, 5, -16, 102, -97, -69, -120, 107, -78, -109, -39}; b[128] = new byte[]{-110, 35, 46, 23, -3, 66, 49, 25, 96, -95, 47, -18, 44, -87, -11, -104, -42, 69, 100, -47, -55, 54, 68, 80, -98, 43, -50, -81, 56, -4, 29, 0, 26, -125, 12, -17, 77, 123, -20, 26, 2, 61, -123, 117, -9, -87, -89, -103, 47, -33, -15, -4, -22, -66, 99, -111, 122, 14, 31, -80, 94, -113, -76, -110, -98, -119, 106, 1, 99, -67, -76, -55, 113, 4, -88, -64, 92, -56, -62, 14, -1, 87, -37, 26, -98, -51, 13, 19, 65, 35, -93, 14, 65, 125, -110, -81, -118, 17, 72, -29, -85, 7, -120, 2, -27, -42, -84, -24, 94, -94, -48, -85, -18, 95, 100, 98, 5, 71, 44, -104, -13, 1, 86, -42, -24, -115, -69, -39}; b[129] = new byte[]{97, 121, -126, 90, 24, -115, -49, -113, -56, -121, 44, 80, 33, -120, -32, 54, -8, -41, -7, 124, 3, -120, -12, -46, 4, -58, -123, 16, -71, -71, 95, -58, 56, -110, 113, -111, -98, 65, 120, -1, 56, -79, -14, 95, 112, 28, 22, -2, -20, 40, 31, -82, -66, 58, -84, 94, -34, -120, -116, -38, 0, 82, -29, 46, 56, -34, -61, 46, -73, 118, -32, 73, -119, 86, -60, 90, 58, -123, 59, 71, -18, -23, 63, 98, 34, 59, -124, 104, 93, -84, 78, -102, 111, -71, -109, 79, 31, 31, 52, -68, -33, -121, 44, 9, -64, 86, 104, 5, 17, 44, 57, 0, -11, -42, -97, 94, 93, -117, 59, -18, 81, -11, 71, 119, -104, -84, 10, -90, -64}; b[130] = new byte[]{24, -105, -44, -96, 24, -81, 91, -101, -86, 14, -107, 49, 77, 23, -29, 25, 99, 88, 124, -35, -1, 117, 49, 109, 117, 26, -126, 32, 126, 75, -39, -51, 103, 89, 125, 29, -127, -115, -37, 107, 95, -97, 91, -10, 23, -44, -24, 121, 107, 14, 37, 11, -96, 72, -118, 36, -31, -116, -102, 21, -43, 90, -51, -98, 85, -13, 109, -59, 28, 51, 47, -122, -80, 53, 20, 7, -60, 30, -14, 80, 111, 125, -17, -19, -31, 25, -115, 60, 29, 33, 86, 10, -46, -13, -39, -19, 110, -27, 52, 74, -64, -90, 91, 15, -67, 14, -93, 55, -98, 39, 79, 121, -80, 13, 40, 68, 98, -125, 92, -39, 76, 16, 74, -126, -107, 95, -20, 115, -59, 8}; b[131] = new byte[]{121, 55, -85, 54, -50, -35, 58, -94, 64, -60, 12, 92, 49, 4, 103, 80, 55, 54, 112, 24, -10, -57, 72, -44, -42, 13, 67, -36, 111, -101, -37, 105, 3, -49, -78, 65, -52, -20, -65, -101, 24, 70, 92, 4, 55, -41, 125, 37, 106, -11, -116, -124, -119, -110, 6, 68, 94, 83, -20, -12, 3, 93, -60, 97, 83, 20, -65, -45, -59, -52, 62, -8, -20, -96, -81, -98, -49, -110, 10, -114, 118, 96, -47, -63, -45, -49, 122, 111, -119, 120, -18, -81, 33, -69, -56, -20, 15, 94, -45, 103, 107, -106, 88, -104, 82, -31, -61, 103, 72, 77, 99, 120, -50, -115, -95, 113, -118, -67, -1, 116, -53, 23, -13, -62, -25, 13, 97, -50, 17, 117, -92}; b[132] = new byte[]{-107, -70, -58, -78, 54, -13, 19, -99, -75, -85, -53, 115, 84, 117, 123, -67, -60, -49, 114, 21, 39, -52, -113, -44, 125, -28, 118, 71, -25, 38, 57, -83, -67, 98, 88, -49, 88, -72, 109, -11, 108, 118, 38, -72, -30, 42, -2, 14, 127, -103, -41, 123, -71, 47, -122, 47, -117, 97, 75, -123, 86, -88, 26, -88, -127, 97, 11, -13, -53, 110, -93, -123, -119, 61, -107, 101, -59, -24, -83, 58, 26, 69, 63, 66, 46, 42, -107, -27, -66, -89, 28, -33, -45, -57, 62, -110, 35, -77, 34, 15, 120, 103, -109, -70, 108, 13, -72, 37, 60, -22, 62, -54, -38, -100, -10, -63, 71, -113, -75, 36, 71, 86, 92, -75, 8, -16, 21, -116, 9, -114, 92, 95}; b[133] = new byte[]{-103, 12, 0, 63, 54, 51, 127, 28, -3, 21, 113, 34, 103, -93, 60, -69, 90, 13, -36, 66, 91, 21, -119, -115, 85, -6, 102, -6, 61, 3, -86, 5, 62, 56, -14, 56, 81, 17, -63, 34, -79, 120, -58, -9, 76, -68, 3, -25, -47, 107, -102, -83, -76, 50, -3, -107, 77, -47, -30, -117, -19, 46, 10, -36, -53, -38, -97, 71, -27, 3, 6, -103, 116, -113, -98, -28, 122, 100, 127, 19, -88, 25, 58, 124, 14, 78, 68, 21, 53, -29, -103, -97, -20, -8, 106, 39, 120, -15, 16, 16, 99, 85, 60, -67, 86, 98, -128, -6, -59, 122, -128, 2, -13, 11, 42, -36, -85, 21, -54, 104, -120, 100, -67, 120, 48, 101, -79, -112, -48, -52, -4, -13, -2}; b[134] = new byte[]{-36, 110, -99, -41, 101, 24, -30, 94, 86, -20, -39, -16, -48, 18, -12, 30, 117, 98, 86, 15, 82, 116, 75, -117, 50, -89, -103, -61, 45, 17, -108, -108, 127, 98, -41, 32, 119, -7, -120, -60, -117, -105, 92, 9, 70, -122, -8, 104, 95, -91, -36, -40, 17, -108, -19, 26, 83, -117, 88, -40, 43, 48, 60, -21, 43, -91, -46, 63, 122, 117, -73, 4, -32, -21, 107, 63, -39, 84, 4, -103, 92, 99, -41, -106, -49, -97, 93, -68, -70, -118, -57, 11, 119, 112, 67, -127, -62, -77, -33, -21, -45, 7, -72, -122, -74, -25, -89, -84, -36, 3, -126, -95, -73, -62, -15, 20, 18, 113, 109, 15, 67, 68, 20, 107, 85, 71, 7, -9, -105, 74, -59, 83, 73, 104}; b[135] = new byte[]{3, 24, 43, 100, -92, -59, -109, -110, 111, 44, 45, -61, 4, 0, -121, -62, -99, -70, -24, 92, 74, 35, -4, -89, -12, 95, -75, -75, -119, 51, 47, -98, -47, 86, -50, 71, 8, -106, 18, -29, -75, 110, 27, 68, -12, 19, 108, 42, -52, 122, -100, 44, -93, -48, 49, -107, -108, -18, -10, -47, -93, 35, 6, 52, -67, -39, -75, -95, -24, 102, -92, -22, 114, -81, 74, 90, -45, -125, 11, -29, -89, 18, -12, -110, -17, -19, 79, -31, 41, -112, 14, -20, -117, -40, -62, 127, 120, -112, 1, 36, -93, 92, -69, 82, -65, 46, 77, 27, -72, 6, -114, -48, 91, -41, -24, -31, -127, 112, -4, -18, -41, -25, 111, -3, -103, 48, -72, -28, 74, -45, -70, -111, -97, 26, -112}; b[136] = new byte[]{106, -39, 6, -14, 93, -108, -4, -39, -26, -5, 50, -18, -17, 56, -34, -98, -73, -36, 1, 84, 9, 49, 74, -121, -118, 97, 89, -35, -60, 31, 105, 74, 120, -85, 42, -59, -97, 85, 34, -63, -99, -9, -113, -82, -107, -73, -83, -34, 85, -92, -1, 21, 124, 126, 46, 81, 39, -80, 121, -6, 1, 51, -63, 50, -99, -30, 17, -118, 1, 37, -116, -115, -90, 60, -1, -51, 19, -95, 5, -73, 51, -99, 0, 12, 117, 101, 19, 115, 34, -120, -98, -7, -58, -33, 30, -124, -58, 0, 87, -89, 42, -97, -57, 26, 127, 62, 111, 27, -53, -78, -27, 73, 68, -7, 48, -95, -35, 114, -17, -109, 17, -11, 23, 70, -119, 2, -81, 104, -113, -98, -34, -51, 98, -61, 67, 124}; b[137] = new byte[]{117, -56, -108, -42, 100, -121, 25, -64, 113, 56, 5, 65, -128, -100, 123, -28, -98, -125, 105, 7, 65, 101, -12, -56, -51, 13, 56, 90, 25, 36, 117, 19, 46, -92, -26, 86, 74, 123, -11, -9, 24, 115, -14, 24, -114, -7, -103, -37, 6, -48, -55, -72, -18, 107, 30, -59, 6, -52, 127, -29, 97, -89, 31, 103, 32, -112, -9, 110, 43, -95, 27, -28, -121, 116, -11, -53, 27, 11, -85, 118, -101, 100, -107, 2, 15, -47, -40, -100, -12, -60, 45, 88, 111, -41, -25, 4, 23, -122, -88, 59, 123, -58, 58, -19, -123, -91, -14, -44, -97, -108, 19, 119, 67, -24, -50, -62, 42, 114, -90, 85, 7, 101, 121, -20, 30, -61, -115, -8, -77, 81, -19, -61, -15, -121, -7, 85, -54}; b[138] = new byte[]{118, 4, 117, 60, -10, -100, 6, -5, 72, 44, 25, -96, -33, 123, 61, 41, 107, 110, 115, -82, -25, 118, 29, -21, 8, 118, 127, -108, -125, 123, -80, 67, 96, 108, 90, -119, 67, 46, 67, 11, 117, -56, 120, 116, -43, -18, -123, -99, -6, -46, 80, 105, 124, 104, 11, -67, 127, 73, 78, -47, -49, -93, -126, -108, 3, 10, 92, -74, -52, -49, -59, 58, 68, -8, -86, -97, 115, 59, 49, 16, -112, 112, 55, -51, -116, 14, 92, 8, -39, 39, 93, 63, 68, -121, 63, -56, 100, 95, -5, -107, -59, -85, -61, 16, 74, 98, 110, 1, -9, -55, 79, -110, -106, 109, 71, 100, 7, -99, -40, -112, -34, -9, -89, -51, 106, -49, -48, -2, 114, -37, -71, -111, 121, -95, 110, 104, -97, -66}; b[139] = new byte[]{-43, 15, 43, 126, -99, 71, -72, 107, 49, -70, -76, -32, 24, -58, -92, -58, 62, 82, -64, -47, 123, 18, 44, 87, -59, 83, -25, 124, 96, 3, 88, 55, 50, -126, 30, 66, -44, 19, 23, -86, 34, -11, 2, -27, 87, 57, 81, 78, -79, -84, -99, 124, -75, -122, 11, -62, -101, -121, -14, 98, 47, -95, -2, -41, 105, 88, -84, -47, -108, 79, -36, -119, 68, -116, -47, 14, 46, 23, -54, 83, 39, -83, -116, 1, -73, 0, -119, -114, -127, -46, -117, -121, -79, -49, -110, -74, -118, 30, 120, -70, -43, 64, -69, 53, -39, -125, -87, -89, 115, -40, -98, 119, -7, -115, 70, 56, -3, 119, 97, -59, 15, -103, -81, -45, 15, -22, 76, -33, -42, 23, 17, 38, -74, -26, 76, -2, 115, 12, 106}; b[140] = new byte[]{-61, 77, 83, -100, -13, -1, 23, 117, 103, -117, 119, -63, 117, 93, -10, 6, 118, -37, -32, -99, 69, 113, -74, -124, -7, 121, -8, -30, 122, 57, -70, 14, -5, 83, -63, 82, -42, 4, -90, -36, -70, -119, -13, 36, -14, 93, -37, -77, -105, -101, -10, 119, 0, 68, 127, 56, -124, 125, 59, -78, -86, 7, -117, 46, -64, -104, 76, 24, -41, -103, -125, -120, 29, 10, 44, 18, 94, -125, -56, 9, 39, -69, -123, -54, -25, 103, -112, 91, -31, 94, -77, -41, -110, -77, 99, 106, -8, 110, 26, 105, 30, 50, -30, 87, -98, 20, -39, -126, -95, -97, 65, 66, 96, 0, 102, -67, 11, 22, 74, -89, -66, -90, -118, -104, 21, 96, 114, 12, 79, -77, -65, -4, 73, 1, -25, -90, -85, -38, 83, -90}; b[141] = new byte[]{57, -4, -56, 23, 127, 19, -89, -104, 53, 91, -105, -107, 110, -71, 43, 49, -19, 12, -101, -73, -76, -64, 22, 32, -26, 21, 111, 46, -103, -1, -28, -59, -71, 56, 87, 38, 68, 59, -127, -89, 94, 90, -55, 16, 103, 39, 91, 1, 35, -35, -2, 8, -39, 116, 47, 3, -4, 67, 76, -3, 33, 113, 99, 76, 68, 121, -128, 118, 117, 41, -15, -68, 53, 95, -88, 105, -62, -115, 27, -74, -104, -83, -75, 31, -74, 68, -117, -2, -125, -33, 68, -45, -34, -49, -91, 52, 22, -27, -96, -67, 90, -41, 80, 30, -100, -64, -92, -42, -65, 6, -3, 42, -128, -5, -77, -96, 6, 97, 23, 71, -25, 70, 96, 37, -48, 103, -120, 80, -5, 116, -86, 14, 66, 114, 127, 16, 43, -109, 81, 114, 62}; b[142] = new byte[]{-30, 26, 23, -46, -56, -22, -106, 68, -119, 61, 74, -70, -37, -72, -119, -112, -42, 17, 110, -48, -2, 87, 106, -124, -84, 43, -109, -118, 70, -98, 68, 49, 25, -67, 81, -42, -65, 55, 111, -62, 62, 22, -41, 28, 73, -113, 63, -78, 28, 3, 122, -49, 97, 35, 9, 104, -99, 113, 43, 21, -127, 55, -93, 67, 86, -57, -14, -28, -13, 38, 8, 127, -50, -83, -14, 25, 68, -84, 38, -126, 86, -83, -25, 42, -58, -56, 30, -15, -79, 1, -114, 73, -66, -87, 67, -68, 27, 121, 0, -100, 46, -123, 50, 50, 118, 53, -124, 30, 93, -2, -114, 43, -93, -96, -78, -84, -119, -62, 81, -49, 79, 32, 38, -77, 111, -56, -95, -124, -63, -30, 33, 42, -128, -127, 70, -1, 103, -51, 16, -111, 8, 106}; b[143] = new byte[]{51, -9, 114, -41, -116, 77, 109, -109, 17, 124, 120, -118, 40, 87, 102, 15, -13, -85, 16, 31, -68, 49, -20, 107, 68, -17, 38, 50, 29, 34, -28, -70, -51, 3, -107, -108, -76, -75, -35, -63, 71, -64, -54, -58, 38, 106, 95, 120, 49, 42, 13, 37, -8, 38, -64, 96, -88, -88, -36, 37, 89, -112, 86, -42, 74, 80, 104, -9, 106, -78, -71, -10, 114, -9, 58, 37, -58, 86, -12, 89, 78, -57, 78, -61, 17, 18, 70, 109, -98, -91, -22, -121, -37, -51, -107, -96, 23, -20, -97, -6, 27, -45, -22, 57, -55, -67, 112, 85, 9, 52, -9, -107, -13, -73, -86, -114, 37, 120, -37, -124, 39, 11, 46, 83, -89, -85, 92, 96, -73, 10, 30, 119, -72, -5, 70, 34, -73, 67, 82, -105, 23, -21, -11}; b[144] = new byte[]{26, 2, -21, -38, 23, 119, -100, -82, -72, 33, -101, -12, 38, 75, 10, 1, 63, -14, 36, -44, 55, -15, -84, -82, 91, 32, 103, 88, -72, -41, 108, 73, -109, -45, -113, 20, 14, -102, 108, -82, -71, -49, -22, 24, -92, 70, -114, 111, -39, 57, 71, 26, 16, -10, 117, -52, 6, -12, -46, -54, -36, -8, 124, 34, -126, 40, -11, 103, -10, -67, -107, -127, 7, -28, -116, 35, -47, 105, -127, -100, 65, 88, -79, 35, -64, 118, -50, 90, -63, -38, 17, 3, 21, -79, 7, -28, -33, -63, 22, 64, -3, 5, -81, -91, 114, 48, -87, 68, 65, -6, 108, 70, 75, -126, -90, -99, 74, -58, -57, 26, -60, -82, -32, -28, 24, 23, 82, 86, -12, 107, 108, 116, 23, -32, -67, -124, 64, 116, 57, 83, -20, -113, -126, 77}; b[145] = new byte[]{91, -39, 74, 112, -80, -22, 52, 100, 0, 27, -5, 10, 64, -42, -111, -103, -29, -108, -104, -78, 123, 25, -61, 13, -88, 22, -122, 103, -82, 125, 70, 120, -21, -23, 20, -21, 126, 121, -92, -89, -106, 125, -103, -32, 11, -97, 5, -24, 30, 51, -29, -51, 36, 3, 38, 117, 88, -79, -113, -79, -56, -55, -18, 62, 9, 122, -128, -59, 64, -124, 9, -66, 94, -102, -40, 86, -101, 39, 123, -117, -19, -5, -70, 35, 82, -90, -81, 84, -16, 106, 47, 46, 93, -74, 120, 105, -42, -89, -36, -100, 8, -107, -27, -58, 97, 29, 117, -5, 53, -68, 100, 80, -20, -23, -74, 49, 6, 9, 8, -25, -123, 33, -8, -84, -10, -39, -74, 10, 8, 88, 79, 25, -23, -70, 5, -34, 95, -19, -124, -71, -59, 95, -32, 34, -119}; b[146] = new byte[]{-119, -126, -25, -26, 31, 101, 34, 16, -1, -57, -39, -88, 104, -12, 103, 77, 126, -90, 36, 66, 74, 78, 24, 56, 89, 124, 82, -20, -118, -47, -37, 54, -27, 31, 110, -82, 58, 66, 13, -49, 71, 73, 53, 50, 85, 122, -37, 52, 100, -42, 3, -98, -55, -45, -20, -99, -94, 35, 118, 58, -123, 53, 86, 60, 106, 24, 83, -113, 73, -36, 29, -117, -124, 36, 68, -77, 64, -39, 67, 112, -69, -45, -51, 5, -74, 35, -100, 124, 118, -33, 4, -77, 103, -48, 60, -126, 43, 82, -34, 0, 46, -40, 7, -10, -51, 118, 44, -95, 46, -95, -4, 124, -87, 126, -45, -30, -95, -120, -16, -56, 80, 18, 88, -39, -18, -56, 109, -108, 127, -10, -35, 44, -60, -106, -56, 95, 30, -100, 70, -14, 57, 1, 119, -79, -41, 106}; b[147] = new byte[]{74, 84, 73, 17, -50, -25, -91, 53, 47, 66, -81, 18, -128, 22, 10, -103, 86, 63, -33, 1, -40, -89, 104, 44, 15, 22, -97, 55, -14, 75, 82, -31, 42, 18, 57, -106, 50, -43, -69, 127, 16, 18, -117, -25, -113, 95, -120, 38, 36, -102, -117, -124, 62, 109, -8, 6, 113, -120, 44, 24, 43, 114, -9, 113, -21, -119, -57, -124, -30, -87, 88, 9, -49, -57, 122, -79, -50, -33, -127, 101, -27, -70, 29, 74, -8, 23, 6, 61, -74, 123, -8, 42, -72, 86, -56, 26, -20, -111, 1, 85, -23, 47, -120, 70, 121, 2, 30, 26, -92, -38, -4, 70, 64, 123, -96, -61, -108, 84, -15, -79, 69, -52, -78, 105, 81, 56, -52, 21, -66, -79, -64, 58, 115, 92, -94, -4, 116, 23, 117, -44, 61, -83, 108, -117, 82, -59, 104}; b[148] = new byte[]{0, 9, 91, 25, 30, -98, -112, -77, -77, -57, -120, 105, -87, -108, -44, -87, 85, 16, -48, 82, -10, 8, 90, 96, 8, -61, -87, -24, 43, -82, 83, 57, 18, -99, 101, -23, 82, 59, -50, -119, 32, -28, 52, -8, 40, 76, -8, 41, -126, 104, 55, -71, -117, -52, -79, 126, 55, -102, 67, -58, 80, 96, -67, 107, 0, -45, -123, 124, -122, 66, 30, -82, -35, 103, -42, -74, 104, 98, 61, 26, -105, -98, 49, 94, -109, -31, 15, 119, 66, -40, 94, -101, 59, -42, 122, 39, -24, 47, 102, -18, 117, 37, 96, -43, -77, 4, -99, 88, -50, -68, -42, -114, 80, 121, 44, -77, -63, 55, -58, -20, 100, 110, -111, 109, -42, 100, 96, -52, 73, -12, -98, 109, 107, -9, 55, -46, 111, 48, 12, 51, 110, 78, 109, 39, 16, 77, 25, 85}; b[149] = new byte[]{-99, 101, -101, 6, 28, -50, 110, -84, 4, 22, 31, -45, -120, -92, 68, 114, -54, -117, 97, -76, 99, 33, -58, 95, -108, -102, 104, -105, 94, -116, -117, -122, 3, 47, -95, 25, -82, 45, -74, -87, 25, -45, -126, -80, 109, 33, -113, -121, -119, -28, -40, 90, -30, -38, 9, 41, 63, 7, -43, -100, 98, -24, -24, 75, -94, 91, -27, -36, -96, -36, 84, 58, 92, 95, 91, 97, -93, 80, 27, 29, -80, -16, 49, -32, -57, 73, 54, -98, -95, -1, -47, 77, 108, 1, 77, 36, 126, -35, -10, 104, 61, -88, -82, -96, -116, 34, -102, -37, 59, 85, -119, 34, -35, -102, -71, 25, -17, 112, -28, -59, -96, -26, -79, -9, 110, -89, 2, 76, 111, 71, 121, -21, 21, 80, -34, -68, 88, -61, 110, -24, 41, 88, 121, 6, -62, 39, 58, 27, -70}; b[150] = new byte[]{88, -39, 53, 70, 125, -86, -76, 111, -96, -109, 64, 4, 123, 10, -32, -93, -26, -111, 108, -38, -58, -32, 40, 16, -92, -28, 124, 82, -114, -36, -38, 109, -105, 65, -113, 12, 84, 59, -72, -71, 16, 58, -81, 54, 6, 25, -40, 42, 77, -62, 2, 42, 76, -67, 50, -15, -34, 37, -29, 86, 84, 5, -50, -58, 96, 56, 17, -43, -48, -37, 18, 45, 20, -105, 80, -73, 16, 109, -25, -89, 26, 119, -47, 65, 93, 123, 51, -37, 92, -107, -80, -6, -7, 119, -114, 119, 105, -72, -69, 79, 117, -33, 29, 84, -45, -95, -23, 34, 58, 92, 64, 38, -49, -101, -91, -85, 125, 112, 84, 91, 33, -47, -32, -124, -17, 112, 115, -5, -100, -96, 10, -45, -25, 123, -23, 98, -55, -14, 121, 89, -26, 100, 109, -113, 95, -113, 37, 94, -109, 82}; b[151] = new byte[]{-63, 89, -94, 59, -87, -99, 127, 102, -102, -122, -78, 101, 114, 105, -63, 15, 68, 26, -25, -52, -68, 2, -4, -41, -76, -98, 120, 34, 108, 96, 60, -77, -25, -48, -48, -112, 34, -71, -108, -57, 51, 89, 53, 51, -125, 19, 117, -114, -22, 70, 76, 16, 38, -109, -3, 17, 42, 79, 115, -24, 56, 26, 125, -78, -48, -121, 8, 83, 87, 56, -50, -3, -17, -46, 120, -32, 45, 89, 69, 77, 50, 60, 40, 90, -45, 73, 16, 100, 17, 121, 18, 103, 11, -118, -43, 66, -49, 93, 45, 63, -56, 6, -43, -8, -120, -68, -56, -16, -91, -35, -103, 76, -26, -104, -29, -8, 56, 53, -30, 71, 46, 50, 79, -106, 93, 28, -26, 118, -57, -18, 126, 47, -5, 82, 62, -60, 110, -1, -18, 78, -58, -24, -33, 44, -89, 109, 105, 110, 10, 83, 96}; b[152] = new byte[]{58, -120, -107, 102, -117, 8, -8, -95, -76, 17, -108, -18, -7, 106, 71, -18, 66, -120, 75, 25, -114, -41, 52, 88, 105, 35, -52, 4, -59, -76, 3, 36, 98, 11, 104, -103, 84, 73, 14, 50, 34, -89, -41, 101, -49, -88, -128, -46, 91, -7, 21, 3, -97, 28, -66, -1, -14, -79, 48, 51, 40, -76, -18, -17, -59, 40, -6, -59, 92, 37, -19, -64, -76, -73, 96, 120, 15, 111, 57, 17, 68, 45, 51, -8, -65, -48, -48, -2, 96, 38, 122, 23, -73, 55, -52, 100, -7, 84, -53, 99, -84, 71, 90, 46, -97, -30, 63, 92, 76, 53, -65, 4, 60, -119, 72, 52, 88, -45, 74, 24, -96, 121, 111, -98, 56, 7, -93, -128, -121, 6, -115, 44, 48, 104, 23, -36, 44, 28, -100, -83, -95, -92, -63, 85, -76, 31, -9, -88, -7, 122, -65, 108}; b[153] = new byte[]{-9, -74, 85, -79, 54, 48, 15, -59, 107, -128, -35, 69, 56, -124, 89, -14, 57, -68, 56, -56, 43, -60, 109, -24, -43, -94, 104, 98, -45, -43, 89, 122, 125, 114, 56, -27, -127, 122, -109, 49, -107, 108, -95, 106, -9, -90, -66, -23, -71, -36, 62, 45, -118, 53, 18, 60, -9, 38, -104, -108, 60, 122, -106, 113, -99, -113, 90, -75, -84, -20, -12, 117, 106, 70, 6, -69, 7, 66, 4, 118, 47, 8, 100, -36, 101, -127, 94, -1, 43, -75, 0, 31, 48, -25, 54, 44, -105, 87, -119, 71, -114, 96, -46, -19, 67, -107, 119, -15, -28, 21, 0, 83, 55, 56, -56, -112, -29, 115, -113, 11, -77, -83, -101, -97, -53, 116, 16, -98, -2, -33, 75, 22, -62, 39, -22, 42, -20, -10, 16, 122, 108, -86, -99, 99, -2, 35, 37, -61, 50, -119, 26, 49, -124}; b[154] = new byte[]{-48, -44, -104, 41, 59, -63, 40, -94, 39, -64, -65, 79, 39, -6, 86, 81, 101, 87, -30, 8, -59, -34, 40, 44, 3, 106, -86, 64, -53, 17, 123, 13, 37, 35, 82, -36, 8, 29, 124, 120, 96, -104, -109, 64, 39, -55, 64, -98, -9, -36, 57, -107, 97, -58, 21, 67, 12, 120, 126, -125, 101, -56, -128, -54, 85, -122, 120, 57, -11, -12, -105, 115, 84, -28, -34, -68, 21, -92, -36, -78, 46, -116, -115, 70, -66, -63, 1, -34, -123, 106, 127, 102, 101, -12, -122, 94, 12, 96, -109, -29, -26, -48, 40, 21, -81, -127, -59, -57, -113, 43, 25, 126, 121, -1, -25, 63, 87, -49, 78, -86, -84, -6, -102, 115, -110, -33, 75, 126, -97, 13, -52, 39, -110, -75, 24, 65, 96, -20, 47, 98, 36, 123, 125, -128, 46, 99, -89, -111, -64, -29, 54, -83, 65, -96}; b[155] = new byte[]{-26, -119, 62, -83, -126, 56, 44, 40, 6, 107, 106, 108, 25, 67, 127, 125, -39, 19, -38, 4, 4, 78, -128, 125, 29, 24, -123, 93, 10, 94, -39, -121, 16, -68, 67, 118, -49, -74, 37, 36, 33, 19, -57, -120, -46, 91, 13, 58, -89, -106, 60, -75, -105, 41, -45, -55, -88, 40, -42, 48, 80, -98, 52, 14, -13, -23, 26, 80, -58, -5, 5, 41, 22, 16, -72, -110, 71, -24, -22, -8, -6, 78, -80, -93, -25, 42, 22, 38, 46, 67, -6, -89, 96, 31, 100, -12, 37, -27, -116, -13, 71, 24, 55, 70, -20, 58, -57, -83, 117, -86, -115, -124, 51, -115, -107, -123, -39, -38, 85, 88, -109, 37, 82, -1, 12, -16, -16, -82, 113, 95, -50, -60, 90, 75, 112, 59, 1, 106, -1, 38, 33, -71, 96, -104, 39, -47, -103, 47, -76, 46, 14, 42, 73, -116, 65}; b[156] = new byte[]{40, 124, -45, 106, 85, 61, -64, -12, -89, 34, 56, 121, -125, 71, -121, -117, 81, -44, 104, 91, -97, -60, -102, 87, -90, 48, -34, -48, -35, -16, 16, -94, 13, -87, -72, 51, -123, -72, -9, 41, -2, 42, 90, 54, -10, 119, 80, 62, -48, -55, 110, -10, -42, 5, -2, 64, 61, 56, -40, -35, 107, -104, -40, 125, 24, 2, 30, 110, 102, 82, -72, -44, -47, 48, 50, 79, -79, 16, 21, -99, -82, -23, 97, 74, -2, -63, 71, 63, -17, -78, 112, -108, 36, -14, 78, -54, 44, -11, 22, 3, -109, -106, 73, -52, -75, 16, -17, -99, 96, 94, 29, -46, -66, -118, -28, -17, -69, 31, -6, -23, -110, 124, 77, -24, -49, 69, -108, -1, 44, 31, -51, -61, 92, -83, 82, 119, -27, 23, 47, 125, -125, -5, -121, -27, 23, -97, 52, 21, -90, 121, 7, 116, -28, -57, 119, 71}; b[157] = new byte[]{70, -78, 85, -60, -126, -88, 13, 123, 66, -66, 37, -116, -65, -12, -105, 48, -18, 54, 14, 126, -108, 88, -30, -125, -53, 104, 97, -40, 4, -105, -78, -60, -12, 123, -31, -70, -101, -79, 117, -37, 125, 34, 37, 105, 68, 55, 76, 1, 71, -54, 126, 6, 84, -35, 6, 20, 43, -97, 110, 116, -9, -61, -9, 43, 94, -85, 6, 102, 105, -49, 15, -7, 118, 103, -84, 32, -100, 97, 96, -10, -116, -32, 104, -102, 58, 12, -19, 22, 59, -110, 113, 56, 36, -103, 93, 9, -105, -5, -39, -11, -32, -105, 116, 69, 77, 33, 39, -105, -112, -120, -79, 51, -118, 108, -79, 49, 110, 81, 94, -49, 99, -11, 41, -51, -40, -7, -26, -80, -54, 24, -70, -11, 121, 62, -64, 21, 84, -115, 63, 125, 15, -124, -65, 51, 102, -49, 12, 0, -38, -118, 5, -30, -127, 4, 59, -19, -61}; b[158] = new byte[]{-77, 46, 45, -26, -79, 64, -17, -111, -111, 4, 79, -125, -87, -81, 108, 67, 24, -49, -106, -30, -83, -4, -103, -60, 99, -98, 32, -72, 121, -54, -87, -57, 38, -57, 113, -58, -117, 34, 116, -115, 64, 62, 122, -34, 23, 59, -59, -32, -21, -36, 2, 3, -36, 85, -60, -106, 80, 47, -67, -13, -13, 73, -107, 124, -121, -8, -36, 114, 10, 59, 24, 49, 79, 98, 35, 27, -79, 10, 48, -32, -1, -85, 30, -115, -100, -60, -17, 123, -128, 107, -54, 8, 11, -75, -78, -48, 81, -28, 95, -122, -72, -112, 121, -114, -31, -21, -101, 67, -10, 39, -85, -123, -57, 23, -95, 112, -23, 26, 121, -127, -97, -39, -74, 5, 3, -5, -13, 47, -112, -123, -50, 30, 34, -58, -73, 45, -52, 91, 64, -107, 8, -62, -11, 17, -116, 90, 127, -82, 3, 3, -18, 88, 78, 45, -70, 26, -1, 102}; b[159] = new byte[]{102, -49, -63, 124, 90, 22, 34, 102, 26, -69, 103, 89, 45, -66, -55, -99, -25, -109, 66, -98, -20, 67, 78, -78, -94, 113, 42, -47, -122, -72, 4, -45, -119, 27, 47, -7, 116, 97, -8, -38, -116, -19, -48, -6, 79, -40, -122, 127, 75, -97, 23, -19, -21, 21, -127, -50, -93, 3, 92, -73, 5, -52, 99, -36, -61, -24, 14, 52, 9, 73, -111, -59, 18, -44, 119, 27, 125, 83, -15, -31, 121, 58, -109, -43, 11, -121, 112, -10, -49, 92, -106, 89, 76, -45, -101, 111, 113, -23, -84, -80, -73, 92, 119, -50, 84, 63, -4, 65, 104, 58, -26, -92, 9, 124, 100, 52, -100, -17, 124, -33, -108, -83, -25, 39, 15, 30, -48, 116, 5, 98, 123, 77, -98, 86, 79, 23, 44, -78, 4, -79, -25, 47, 39, 27, -24, -103, 111, -85, -79, 118, 58, -86, -39, 71, -31, 87, 102, 114, -9}; b[160] = new byte[]{-123, -41, -125, 38, -28, 103, -103, -65, 42, -12, 70, 30, 115, -49, -97, -70, -44, -1, 10, -6, -95, -90, -86, 20, 118, -39, -122, -24, 77, -11, 70, -74, 9, 14, -49, 122, 51, -107, -97, -98, 15, 116, 32, 74, -85, -99, -58, 94, -30, -75, 88, 14, -121, 17, 100, -83, -73, 118, -6, -83, 37, -93, -31, 77, 64, 87, 94, 30, 54, 35, 35, 37, 82, 122, -24, -21, -46, -120, -5, 78, -7, 22, -10, 24, -62, 5, 90, 81, -35, 116, -81, -79, 49, 88, -50, 89, -20, 48, -112, -37, 31, 19, -101, 89, -98, 43, 102, 2, 76, -7, 5, -43, 85, -41, 123, 25, 117, 82, 54, 2, -99, 20, 46, 67, 26, 105, 118, -118, 97, 51, 10, -24, 36, -81, 21, -86, 82, 91, 20, 91, 37, 114, 20, -46, 4, 91, -120, -17, 8, 28, 119, 47, -97, -4, -79, -52, 108, -53, 46, -79}; b[161] = new byte[]{10, 80, -126, 58, -3, 38, 15, -33, -1, 45, 29, 14, -118, -63, -33, 106, 108, 92, 78, -7, -91, -64, -62, -32, 0, -124, 45, -34, 22, -50, -115, 19, -28, 95, 1, 32, 104, 60, -49, -46, -18, -117, 55, -64, 77, -63, -45, -107, -61, -30, -31, -83, -68, -52, 35, -52, -48, -52, 123, -24, -18, 97, -113, -111, 2, 2, 121, -24, -90, -1, 31, -79, -104, 99, -48, -74, 101, -89, 95, 16, -106, -120, -67, 110, 127, -1, 30, 71, -107, -82, -53, -47, 43, -14, -55, 19, 7, -54, -58, -29, -5, -101, 111, 107, 44, -68, 41, 46, 108, -26, -49, 2, 67, 18, 58, 1, 103, 95, -43, 45, -58, 112, -115, -29, -23, -52, 53, 93, -81, -66, 126, 49, 49, 52, -81, -67, 12, -104, 89, -20, 31, -98, 83, 100, 126, 84, -14, -67, -83, 94, -92, 79, 81, 85, 109, -111, -87, 27, 73, -118, 70}; b[162] = new byte[]{22, -49, -128, -104, 80, -89, 82, -65, -30, -101, 15, 3, -48, 106, 77, -119, -46, 15, -10, -84, 22, -13, 36, 64, -50, 107, 106, 61, 47, -81, 79, -87, -7, 83, -122, 5, 65, -54, 96, 111, 57, -21, 96, -18, 19, 62, -87, 21, 23, 106, 51, -42, 106, 96, 45, -126, 32, -57, -5, -74, 94, -54, -19, -106, 49, -105, -29, -94, -33, 99, -61, -78, 80, -10, -80, -29, -9, 90, -33, -60, 6, -98, 10, 8, -107, 45, -100, 55, 77, 92, -128, -35, -34, 125, 40, -52, -106, 118, 69, -93, 92, 124, 79, -38, 116, 54, 125, 72, -127, 24, 30, -68, -25, 121, 123, 53, 84, 47, -75, -99, 99, -73, -98, -120, 77, 105, 93, 119, 6, 6, 0, -40, -97, -77, 67, 66, -104, 116, 116, 46, -121, 14, 80, 98, 75, -34, 91, 12, 87, 25, -5, -95, 88, -118, 1, 56, 91, 38, -23, -80, -31, -53}; b[163] = new byte[]{-62, 3, -72, 13, -47, -103, -53, -40, 53, -36, -117, -114, -122, 66, 70, 37, -60, -24, -56, -69, -126, 5, 89, -67, 79, -9, 60, -87, -114, 13, 58, 23, -107, 83, 83, 86, -38, 15, 44, 60, -118, 62, 70, 33, 44, 73, 36, -4, -77, 30, -66, 38, 31, -64, -2, 70, -126, -59, -117, -55, -12, 43, 32, -100, 24, -39, 48, -59, -111, -79, -35, -4, -36, 118, 64, -96, -101, 100, -57, 2, -81, -54, -121, -105, -49, 48, -2, -90, -31, 111, -88, -92, 1, 16, -86, -27, 4, 76, 31, 125, 120, 75, 14, -127, 80, 1, 109, -78, 113, -117, 65, 27, 59, 101, -48, 107, 20, -74, -125, -88, 111, 105, -17, -18, 39, -89, -57, 92, 67, -24, -93, 89, 53, -84, 88, -57, 99, -101, 68, 6, 18, -3, -17, 11, 75, 122, 96, -27, -39, 46, -12, -61, -63, -89, 85, -11, -38, 111, 25, 33, 116, 64, 107}; b[164] = new byte[]{18, 69, -19, -45, 100, -102, 69, 66, 35, 22, 106, 11, -57, 35, -70, 55, -24, 34, 47, -120, -128, -31, -10, 52, 19, 22, -88, -6, 104, -32, 17, -10, 126, 90, -2, -80, -9, -111, -105, 28, 18, 53, -58, 86, 12, 84, -71, 14, 114, 123, -67, -99, -21, 28, -67, -59, -48, 31, 67, -85, -88, -65, 110, 126, -118, -60, 81, 49, -109, 74, 13, -100, -117, -82, -26, -32, 106, -16, 2, -68, -116, -53, -18, 94, 82, -114, -5, 67, -111, -87, 88, -89, -20, -125, -55, -61, 108, 63, 26, -34, 5, 8, -1, -47, 4, -46, -64, -115, -89, -69, 76, 104, -84, 40, 39, -98, -100, -58, 22, -58, -35, 50, 88, -90, -91, -109, -90, -83, -1, 75, 122, -69, -21, 31, -73, 17, 50, -2, -49, 24, 122, 16, -56, 124, 48, -109, -33, 89, -62, 49, -108, 52, -69, 122, -14, -86, 116, -8, 18, -45, 66, -96, 82, -39}; b[165] = new byte[]{58, -32, 106, -57, -110, -59, 38, -70, 17, 108, 57, -8, -41, -18, 26, -52, 81, -27, 42, 12, 58, 108, -56, 27, -79, 17, -102, 43, -43, 39, 62, -8, -71, -59, -7, -107, -31, 34, -48, -39, -116, -56, -122, -118, 70, -117, 81, 121, -20, -66, -81, 42, -23, 26, 91, 69, -27, 22, 79, -59, 127, -108, -35, -28, -125, 2, -19, 79, -92, -67, 114, -91, 127, -57, -58, 32, -124, 60, 21, -95, -56, -46, -10, -56, 95, -49, 78, 38, 80, 106, -108, -128, -86, 126, -44, -115, -119, 84, 113, -75, -95, 62, 104, 40, 116, -84, 26, 3, 126, 3, -16, -72, 47, 42, 4, 45, -76, 35, 83, -73, 100, -69, -118, 125, -27, 21, 26, 67, 14, 44, 69, -98, 100, -76, -70, -102, 103, 39, -35, -60, -124, 70, 63, 104, -3, -47, 37, -15, 6, 48, 66, -8, 71, -7, 81, -70, 97, 97, 127, -1, 41, 34, -43, 91, -68}; b[166] = new byte[]{72, -17, -17, 14, -54, -103, 13, -46, 38, 57, -47, -11, -10, -58, 72, -20, 85, 21, -122, 92, 117, 16, -115, 23, 70, -65, 0, -83, 59, -128, 27, -111, 124, 44, 50, -69, -24, 23, 45, -40, 46, -33, 93, 53, 40, -62, 41, 87, -100, -107, -95, 67, 27, -37, 26, 43, -91, -111, 65, -110, -71, 88, -43, 63, 93, -77, 105, -49, 91, 74, 20, 105, -81, 82, -9, -71, -57, 94, -18, 125, 95, -9, 47, -51, 112, 114, 66, -63, -38, -109, 46, -82, -47, 99, 40, 8, -75, 14, 41, -91, 1, -94, 63, -40, -41, 127, 96, -25, -2, -87, -107, 101, -108, -31, -7, 38, 55, 1, -112, -120, 75, -29, -107, -93, 98, -64, -119, -126, 71, 90, 124, -13, -95, 127, 25, -73, -25, 78, 98, 35, -128, -3, -108, 10, 102, 39, -107, 38, 87, 60, -110, -49, -74, -58, -90, 15, 15, -98, 94, 31, 70, -19, 102, 126, 97, -52}; b[167] = new byte[]{-75, -110, -1, -88, 0, -116, 59, -44, -77, -102, 2, 97, 89, 3, 44, 108, -88, 4, -26, 83, -64, 17, -68, 103, -36, -44, 123, -25, 78, 34, -106, 0, 43, 71, -56, -5, -70, -3, 74, 23, -114, -82, 67, 40, -21, -112, 73, -14, 6, -118, -26, 96, 31, -6, -100, -79, -91, 30, 27, 122, -40, -124, 31, -76, -58, 31, -26, 1, -23, 28, 87, -45, -66, -23, 17, 40, 95, 59, -37, -52, -120, 96, 0, 24, 28, -12, 63, 90, 49, -13, 29, -43, 82, -87, 66, 106, 23, 102, -68, 68, 78, -110, -66, -10, 62, 41, 34, -106, 44, -59, 55, -122, 57, -11, 127, -89, 106, 95, -97, 125, -123, -128, -5, 2, 118, -49, 25, 58, 69, 40, 53, 57, -80, -79, 78, 93, -69, -78, -99, 77, 108, 61, 72, 79, -7, -82, 7, 122, -1, 114, 53, 78, -102, -76, -80, -24, -32, 41, 23, -3, -118, -73, 21, -70, 86, 86, -28}; b[168] = new byte[]{25, 23, -69, -72, 93, 112, 31, -97, -5, -44, 29, -17, -104, 97, 126, -92, -35, -57, -12, -14, -114, -42, -46, -16, -78, 118, -12, 15, -113, -49, -101, -77, -18, -28, -96, 30, -32, -25, -34, -106, 71, -59, 32, 24, 50, -114, -22, 25, -82, -105, -124, -112, 102, 103, 111, -22, -97, -8, -87, -5, 42, -35, 97, 15, 6, 43, -4, -58, -3, 123, 11, -80, 57, 123, 27, 34, -110, -48, 50, 7, -31, -48, -114, 87, -80, -6, -42, -95, -57, 110, 87, 57, -2, -69, -9, 38, -35, -54, -12, 103, 93, 115, -77, 29, 0, 102, 52, -22, -66, -55, 64, 10, 64, -22, -118, -85, -104, -29, 82, 97, -76, 103, 92, -37, 100, 66, -68, -122, 40, -101, 105, 126, -49, 51, 8, 51, 32, -113, -80, 119, -126, 72, 29, 76, 6, -17, 4, 88, -83, -30, 63, -76, -125, -35, -43, -83, -73, 12, -52, -125, 76, 90, -98, -125, -61, -126, 77, 20}; b[169] = new byte[]{-16, 16, -59, -69, -19, -67, -106, -101, 101, 25, 40, -36, 101, -18, -32, -123, 102, -108, -128, -116, -37, -71, 74, 76, -27, 112, -59, 110, -46, 85, 64, -15, 29, -35, -80, 4, -47, -63, -111, -107, 1, 61, 18, 18, -105, -117, -110, 127, 34, -55, 24, 54, -76, 55, -25, -69, 65, -124, 15, -108, 52, 51, 87, 10, 38, -45, -40, 6, 70, -89, 53, -128, 115, 1, 58, 116, -1, -75, -32, 91, -111, 47, -111, -79, -86, 31, -19, 122, -29, -40, 42, -66, 72, 34, 126, -52, -35, 38, -32, 59, 39, 33, 103, 50, -56, -20, 113, -126, -67, 88, 65, 82, 34, 65, -69, -54, 43, 35, 117, -90, 0, -123, 92, 82, 16, 44, 48, 97, -20, 22, -9, -100, -109, -10, 66, 93, 0, 62, 82, -81, -42, 86, 117, -75, 84, -37, 58, -123, 41, -120, -122, -64, 5, 115, -99, 106, -78, 107, 16, 43, 78, -13, -39, 106, 109, -57, -118, -47, -113}; b[170] = new byte[]{-78, 35, -46, 92, 62, 46, -33, -91, -104, -75, 59, -17, 15, 52, 101, 20, -8, -82, 100, -55, -47, 115, 58, -53, -35, -32, 53, -25, -34, 121, 36, 48, -100, -21, -11, 118, 10, -5, -70, -101, -15, -49, 59, -94, 113, -94, 12, 78, -47, -90, 19, 103, -101, 94, -115, -128, -50, 33, -104, 1, -53, -115, 3, -127, 70, 76, -88, -14, 118, 34, -106, 35, -78, 101, 27, -114, 50, 84, -14, -17, -50, -89, 8, 76, -94, 126, 118, -26, 109, -17, -48, 70, 37, -65, 40, -10, 66, -99, -23, -64, 82, -125, -110, -7, -36, 43, 118, -115, -116, -35, -54, 105, -91, -6, 30, -30, 50, -22, 76, -86, -80, 57, 116, 5, 49, 39, 7, -104, -119, -56, 114, -47, 4, 41, 30, -50, 116, -54, -45, 95, 110, -29, -58, 31, -78, -68, -10, -96, 107, -103, 113, 108, -51, -113, -97, -17, 40, -57, 113, 64, -8, -78, 39, -47, 7, -54, -116, 124, 2, -71}; b[171] = new byte[]{-5, -3, 120, 62, 113, 80, 85, -98, -63, 76, 114, -108, -66, 68, -19, 70, -74, 18, -19, 105, -49, 52, 62, 96, 103, -106, -14, 50, 21, 43, 12, -71, 9, 107, -91, 15, 5, 94, -13, -46, 122, -61, 50, 39, -60, -93, -9, 80, 125, 74, -73, 18, 48, -94, 27, -84, 70, 86, 26, -44, -68, 12, -32, -58, -93, -112, 101, 53, -75, 99, -38, 125, 51, 66, -106, 91, -31, 52, 94, -16, -112, -90, -111, -59, -90, -29, 42, 23, 91, -40, -80, 93, 14, 15, -96, 12, -120, 79, 73, -76, 105, -42, -77, 114, 92, 105, 99, -1, 92, 17, 127, 10, -8, 80, -108, 81, -101, 30, 45, -33, 110, -80, -1, -123, -92, -60, 6, 121, -87, 37, 96, 96, 49, -46, -85, -119, -73, 91, 92, 123, 65, 72, 86, 118, 51, 48, -105, -39, -32, -19, -58, -128, -35, 69, -47, 21, 26, -50, 47, -2, -81, 32, 84, 20, -66, 90, -55, -39, -35, 52, -59}; b[172] = new byte[]{-33, 82, 53, -115, -81, -127, -7, -86, 41, 42, 76, -19, 27, 50, 88, -68, -111, 22, 2, -56, 114, -96, 0, 21, -25, 43, -34, -32, -71, -49, -46, 71, 72, -103, 68, 26, 84, 68, -46, -70, -114, 66, 12, -122, 43, -17, 51, 60, 48, 32, -11, 121, -125, -23, 46, 39, 38, 26, 112, 62, 11, -35, -69, -93, -44, 6, 1, 82, -9, 114, -45, -65, 12, 37, -95, 54, 41, -42, -20, -39, -98, 96, -125, 62, -93, -121, 98, 40, 25, 3, 62, 49, -26, 73, 102, -66, -98, -82, 39, -81, -24, 14, 106, -98, 2, -73, 2, -10, -63, 109, -127, -27, -118, -83, -37, -86, 74, -128, -33, 110, 1, 78, 66, -103, 50, -10, -22, 22, 5, -128, -63, 14, 101, -6, -28, 67, -75, -35, 96, 108, -74, 8, -33, 17, 36, -71, -93, 121, 33, 85, 84, -48, 70, -4, 84, -38, 43, -69, 105, -69, 45, 11, 65, 41, 36, -93, -84, 28, -52, 22, 6, 122}; b[173] = new byte[]{93, -76, 95, 14, -95, -98, -35, -25, -120, -42, -47, -15, -15, 73, -49, -99, -32, -63, -25, -77, 124, 85, -28, -110, -51, 124, -43, 8, -44, -96, -60, -31, 31, 119, -89, 127, -70, 126, 66, 15, 17, -58, -6, 110, 48, -34, -46, 27, -75, 41, 50, -31, 29, -66, -52, -63, 126, 75, -105, 17, -67, 51, -80, 103, -5, -34, 122, 6, 45, 44, -92, -15, 3, 73, -107, 121, -43, -117, 22, 71, -31, -2, -2, 13, -128, -14, 126, 52, 69, 62, 115, 41, 91, 73, 38, 75, 1, -32, 104, 124, 59, -24, 39, 9, -40, 42, -24, -51, -40, -95, 90, -16, -15, -128, -58, -67, -40, -14, -68, -73, -87, -39, 18, -16, -26, -11, 102, 33, -40, 2, 98, -17, 41, 47, 108, 25, -65, -17, -115, 59, -47, -53, -26, -72, 67, -71, 14, 122, -101, 38, -20, -10, 34, -78, 41, -54, 122, 80, 64, -68, 57, -29, -106, 46, -65, -108, -21, -83, 26, -73, -89, -115, 126}; b[174] = new byte[]{-116, 97, 35, -4, 6, -127, 121, -10, -100, -10, -29, -100, -104, 107, -114, -10, 113, -2, 55, -20, -52, -80, 46, 42, 1, -18, -103, 80, 67, 12, 33, 119, 83, 26, 116, -106, -105, -75, -19, -45, -7, -54, -85, 35, -93, -35, -111, -10, -29, -47, -16, -112, -97, 27, -97, -112, -66, -47, -68, -50, -91, 13, 94, 3, 115, -15, 18, -82, -111, 124, -93, 43, -116, 114, 79, 38, 100, -39, 94, -76, -124, 73, 56, -33, -113, 122, 13, 45, 79, -62, -86, -96, -50, -87, -33, 51, -99, 56, 13, -22, 123, -25, 81, -48, -98, 74, -46, -52, -121, -42, -26, 88, 93, 126, -48, 109, 117, -100, 60, 32, -24, 100, 22, 89, 13, 51, -115, 80, -45, -85, -104, -5, -95, -59, -36, 20, -20, -108, 114, -19, 28, -54, 94, 88, 13, -59, 15, -46, 45, -90, 3, 98, 110, -106, 82, 39, 83, 107, -127, -75, -18, -25, 78, -121, -110, 24, 29, -59, 39, 18, -82, 120, 22, -17}; b[175] = new byte[]{68, 12, -51, 11, 25, 79, -39, 47, -4, 45, -10, -58, -74, 84, -125, 74, 26, 49, -15, -60, -96, -104, -109, 14, 115, 108, 79, 22, -49, 30, -127, -107, 73, -117, 9, 102, -99, 45, -38, 5, 98, -113, 69, -74, -15, -111, -104, -107, 85, -119, 110, -32, 99, 73, 55, 6, -24, 113, -50, -99, -126, -71, 118, -16, 117, -64, -79, -120, -92, 19, -100, 48, -95, 13, 76, 120, -30, 86, 83, 124, -13, 22, 38, 4, 54, 30, -46, 44, 20, 31, -115, 83, -48, 30, -25, 28, -74, -65, 15, -23, 25, 123, 96, -66, 112, 29, -49, -102, 11, -23, -67, -39, 29, -37, -97, 57, -71, -82, -99, 79, 120, 121, -69, -69, 60, -74, -119, 69, 13, -47, -56, 31, 111, 2, 120, 22, -70, 87, -123, 83, 19, -80, 5, 41, 77, -72, 53, -5, 77, -5, 17, 103, 6, 58, -20, 98, -81, -121, 70, -37, 16, 95, -128, -20, 26, -7, -24, -59, 30, 76, 59, -53, 66, -42, 71}; b[176] = new byte[]{-45, -56, 102, 102, -101, 65, 24, -94, -86, 71, -92, 51, -12, 99, 92, -39, 105, 53, 122, -40, 20, -4, -86, 32, 110, 35, -48, -104, 8, 121, 33, 121, 83, 5, -49, 123, 14, -31, 19, -96, -66, 1, 111, -49, 61, -99, -13, -101, 85, 15, -42, 122, 89, -94, 9, 47, 48, 18, 52, -127, 118, 105, -27, -110, 69, 59, -3, -66, 84, 79, 115, -8, -109, 90, 65, -23, -100, 79, 31, -44, 37, 118, 62, 90, 107, 57, 0, -1, 32, -101, -46, 76, -61, 124, -103, 92, 116, 83, -95, -43, -32, 28, -69, -110, -17, -63, 53, -50, -117, 57, -113, -62, -64, -17, 36, 73, -50, -111, -96, -39, -84, -95, 18, 102, -56, 108, 29, 77, -128, -24, -52, 122, 107, 9, 61, -2, -118, -33, -22, 32, 101, 36, 116, 8, 32, 125, -27, -30, -115, -37, -42, 12, 118, 76, -42, -1, -123, 72, 29, 2, 92, 45, 64, 56, 111, 40, -19, -20, -112, 29, 15, 75, -22, -36, 88, 12}; b[177] = new byte[]{-48, 104, 107, -127, -76, -110, 28, -14, -42, -73, 36, -74, -102, 116, -79, -84, -48, 35, -3, -36, -85, 21, 7, 49, 34, 3, -29, 79, -65, -69, -15, 38, 117, 101, 49, -100, -45, 123, -20, -102, 86, 120, 103, -10, -50, 59, -50, 4, -9, 34, -101, -107, -94, 57, 117, 33, -43, 94, -68, 121, -20, -67, 36, -118, 66, -4, -74, 2, -126, -80, 9, 20, 52, -19, -27, -1, -116, -17, -28, 87, -62, -83, 20, -32, 27, 30, 44, 21, 49, 65, -44, -45, 92, 45, -52, 26, -126, 75, -59, -51, -41, -69, -21, -128, -29, 98, 104, -8, 97, -104, 88, -79, 116, -103, 9, 82, -94, -46, -21, -71, 51, -57, -23, -128, 96, -39, -11, 67, 18, 21, 29, 52, -15, -58, -31, 104, -118, 5, 45, 100, -128, 54, -88, -115, 37, -124, -81, 77, 6, 97, 25, 103, -53, -76, -125, -58, 44, -33, -96, 32, -29, 28, 104, -88, 113, -43, -66, 111, -125, -93, -104, 75, 62, -110, 112, 3, 63}; b[178] = new byte[]{-39, 81, -94, 49, 95, -33, -38, 19, 89, 2, 60, 55, 125, -41, -121, -57, -4, 17, 33, 92, -34, 63, 77, 124, -107, -100, -89, -49, 4, -78, 72, 111, -13, 64, 28, 114, 70, 104, -73, 98, 98, -107, 102, 104, 119, 104, -101, -89, -70, 42, -90, -67, -37, 116, -112, -98, -91, 95, -77, 60, 5, -88, -40, 28, -16, -127, -110, -94, 78, -57, -54, 15, 39, -14, -75, -96, 0, -15, 86, 9, -38, -67, -98, -67, 116, -90, 43, 75, 47, 127, 62, 110, -84, 31, 24, -59, -83, -44, -77, -11, 55, -91, 80, -81, 108, -126, -127, 83, 89, 46, -122, -58, 12, -42, 18, -91, -47, 4, 48, -23, 25, 73, -20, 53, -76, -124, 113, 98, -49, 41, 82, -51, 54, -122, 0, 114, 91, 88, -9, -62, 89, 104, -44, -103, 5, 119, 41, 107, -47, 94, 72, -34, -20, 85, 78, 55, -85, 98, 4, 112, 60, 119, 102, 66, 115, 68, -102, 101, -2, 86, -5, -97, -24, -81, 51, 5, -1, 57}; b[179] = new byte[]{-120, -60, -126, -121, 89, -71, -67, -53, 119, 11, -78, -60, -97, -100, 10, 69, -117, 90, -105, 59, -58, -22, -110, -102, -124, 109, 125, -83, 54, -6, 103, -38, -69, -7, -69, -125, -80, -62, -7, -56, -50, -115, -88, 59, -24, 87, 27, 119, 14, -2, -54, 71, 7, 82, -33, 17, -65, 63, 38, -5, 108, -111, -81, 67, 102, -72, 22, 20, 103, 77, -82, 7, -68, -5, -27, -35, -54, 73, 116, -56, 2, 10, -5, 23, 121, 117, -24, 48, -66, 41, 31, 49, 101, -92, -3, 27, 54, -61, 40, -70, -103, -95, 67, 73, 33, 1, 110, 117, 60, 10, -8, 7, 94, -71, -69, 92, -71, 80, -70, 107, -69, 17, 62, 116, 108, 127, 28, -107, 16, -56, -57, -58, -124, -28, -103, -26, 48, -54, 43, 16, -7, 76, -42, 16, -112, 49, 24, -37, -59, -22, -106, 126, -123, -113, -57, 110, -51, 2, -13, 48, -120, 18, -96, 63, 10, 25, -110, -125, -14, 57, -70, -3, -1, 21, -62, -9, -8, -36, -47}; b[180] = new byte[]{-124, -34, 62, -57, -5, 10, -12, 84, 89, -97, -103, 101, 107, 14, -1, 92, 49, -80, -122, -35, -63, 112, -116, 64, 20, -2, 9, -96, 106, -107, 64, 44, 60, 115, -110, 14, -107, 42, -118, 16, -27, 98, 98, -53, 53, -102, 123, -28, -93, -87, 21, -83, -51, -94, 48, 64, 60, -121, -60, 108, -80, -98, 29, 36, 26, 69, 13, -97, -37, -111, -24, 66, -54, 20, 38, 90, -101, 41, 102, -48, 47, 68, -34, 125, -102, 62, -89, -57, 68, -127, -126, 86, 6, 113, -61, -14, -82, 125, -34, -46, -21, -17, 24, -98, 103, 98, 104, -45, 3, -72, 42, 7, 70, 62, 20, 81, -128, 99, 8, 0, 59, 126, 57, -118, -100, 83, -84, -63, 108, -100, -97, 26, -9, 93, -58, -50, -102, 27, 37, -41, 7, -117, 14, 97, 126, -90, 10, -38, 42, -88, -15, 36, -13, 86, 88, -38, 24, -57, 57, 89, 44, -49, -21, -37, -59, 13, 49, -46, 75, 127, 88, 73, -10, -60, -13, -35, 19, 60, 24, 38}; } /** * Tests to make sure Base64's implementation of the org.apache.commons.codec.Encoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */ public void testEncoder() throws EncoderException { Encoder enc = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64, (byte[]) enc.encode(binary)); assertTrue("Encoder test-" + i, b); } } } /** * Tests to make sure Base64's implementation of the org.apache.commons.codec.Decoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws DecoderException problem */ public void testDecoder() throws DecoderException { Decoder dec = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(binary, (byte[]) dec.decode(base64)); assertTrue("Decoder test-" + i, b); } } } /** * Tests to make sure Base64's implementation of the org.apache.commons.codec.BinaryEncoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */ public void testBinaryEncoder() throws EncoderException { BinaryEncoder enc = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64, enc.encode(binary)); assertTrue("BinaryEncoder test-" + i, b); } } } /** * Tests to make sure Base64's implementation of the org.apache.commons.codec.BinaryDecoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws DecoderException problem */ public void testBinaryDecoder() throws DecoderException { BinaryDecoder dec = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(binary, dec.decode(base64)); assertTrue("BinaryDecoder test-" + i, b); } } } /** * Tests to make sure Base64's implementation of Base64.encodeBase64() * static method is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */ public void testStaticEncode() throws EncoderException { for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64, Base64.encodeBase64(binary)); assertTrue("static Base64.encodeBase64() test-" + i, b); } } } /** * Tests to make sure Base64's implementation of Base64.decodeBase64() * static method is behaving identical to commons-codec-1.3.jar. * * @throws DecoderException problem */ public void testStaticDecode() throws DecoderException { for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(binary, Base64.decodeBase64(base64)); assertTrue("static Base64.decodeBase64() test-" + i, b); } } } /** * Tests to make sure Base64's implementation of Base64.encodeBase64Chunked() * static method is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */ public void testStaticEncodeChunked() throws EncoderException { for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64Chunked = utf8(CHUNKED_STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64Chunked, Base64.encodeBase64Chunked(binary)); assertTrue("static Base64.encodeBase64Chunked() test-" + i, b); } } } /** * Tests to make sure Base64's implementation of Base64.decodeBase64() * static method is behaving identical to commons-codec-1.3.jar when * supplied with chunked input. * * @throws DecoderException problem */ public void testStaticDecodeChunked() throws DecoderException { for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64Chunked = utf8(CHUNKED_STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(binary, Base64.decodeBase64(base64Chunked)); assertTrue("static Base64.decodeBase64Chunked() test-" + i, b); } } } private static byte[] utf8(String s) { // We would use commons-codec-1.4.jar own utility method for this, but we // need this class to be able to run against commons-codec-1.3.jar, hence the // duplication here. try { return s != null ? s.getBytes("UTF-8") : null; } catch (UnsupportedEncodingException uee) { throw new IllegalStateException(uee.toString()); } } /** * This main() method can be run with just commons-codec-1.3.jar and junit-3.8.1.jar * on the classpath to make sure these tests truly capture the behaviour of * commons-codec-1.3.jar. * * @param args command-line args */ public static void main(String[] args) { TestSuite suite = new TestSuite(Base64Codec13Test.class); TestResult r = new TestResult(); suite.run(r); int runCount = r.runCount(); int failureCount = r.failureCount(); System.out.println((runCount - failureCount) + "/" + runCount + " tests succeeded!"); if (!r.wasSuccessful()) { Enumeration en = r.errors(); while (en.hasMoreElements()) { TestFailure tf = (TestFailure) en.nextElement(); System.out.println(tf.toString()); } en = r.failures(); while (en.hasMoreElements()) { TestFailure tf = (TestFailure) en.nextElement(); System.out.println(tf.toString()); } } } }
// You are a professional Java test case writer, please create a test case named `testEncoder` for the issue `Codec-CODEC-89`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Codec-CODEC-89 // // ## Issue-Title: // new Base64().encode() appends a CRLF, and chunks results into 76 character lines // // ## Issue-Description: // // The instance encode() method (e.g. new Base64().encode()) appends a CRLF. Actually it's fully chunking the output into 76 character lines. Commons-Codec-1.3 did not do this. The static Base64.encodeBase64() method behaves the same in both 1.3 and 1.4, so this problem only affects the instance encode() method. // // // // // ``` // import org.apache.commons.codec.binary.*; // // public class B64 { // // public static void main(String[] args) throws Exception { // Base64 b64 = new Base64(); // // String s1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // String s2 = "aaaaaaaaaa"; // String s3 = "a"; // // byte[] b1 = s1.getBytes("UTF-8"); // byte[] b2 = s2.getBytes("UTF-8"); // byte[] b3 = s3.getBytes("UTF-8"); // // byte[] result; // result = Base64.encodeBase64(b1); // System.out.println("[" + new String(result, "UTF-8") + "]"); // result = b64.encode(b1); // System.out.println("[" + new String(result, "UTF-8") + "]"); // // result = Base64.encodeBase64(b2); // System.out.println("[" + new String(result, "UTF-8") + "]"); // result = b64.encode(b2); // System.out.println("[" + new String(result, "UTF-8") + "]"); // // result = Base64.encodeBase64(b3); // System.out.println("[" + new String(result, "UTF-8") + "]"); // result = b64.encode(b3); // System.out.println("[" + new String(result, "UTF-8") + "]"); // // } // } // // ``` // // // Here's my output: // // // // // ``` // $ java -cp commons-codec-1.3.jar:. B64 // [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] // [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] // [YWFhYWFhYWFhYQ==] // [YWFhYWFhYWFhYQ==] // [YQ==] // [YQ==] // // // $ java -cp commons-codec-1.4.jar:. B64 // [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] // [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh // YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ== // ] // [YWF public void testEncoder() throws EncoderException {
380
/** * Tests to make sure Base64's implementation of the org.apache.commons.codec.Encoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */
4
370
src/test/org/apache/commons/codec/binary/Base64Codec13Test.java
src/test
```markdown ## Issue-ID: Codec-CODEC-89 ## Issue-Title: new Base64().encode() appends a CRLF, and chunks results into 76 character lines ## Issue-Description: The instance encode() method (e.g. new Base64().encode()) appends a CRLF. Actually it's fully chunking the output into 76 character lines. Commons-Codec-1.3 did not do this. The static Base64.encodeBase64() method behaves the same in both 1.3 and 1.4, so this problem only affects the instance encode() method. ``` import org.apache.commons.codec.binary.*; public class B64 { public static void main(String[] args) throws Exception { Base64 b64 = new Base64(); String s1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; String s2 = "aaaaaaaaaa"; String s3 = "a"; byte[] b1 = s1.getBytes("UTF-8"); byte[] b2 = s2.getBytes("UTF-8"); byte[] b3 = s3.getBytes("UTF-8"); byte[] result; result = Base64.encodeBase64(b1); System.out.println("[" + new String(result, "UTF-8") + "]"); result = b64.encode(b1); System.out.println("[" + new String(result, "UTF-8") + "]"); result = Base64.encodeBase64(b2); System.out.println("[" + new String(result, "UTF-8") + "]"); result = b64.encode(b2); System.out.println("[" + new String(result, "UTF-8") + "]"); result = Base64.encodeBase64(b3); System.out.println("[" + new String(result, "UTF-8") + "]"); result = b64.encode(b3); System.out.println("[" + new String(result, "UTF-8") + "]"); } } ``` Here's my output: ``` $ java -cp commons-codec-1.3.jar:. B64 [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] [YWFhYWFhYWFhYQ==] [YWFhYWFhYWFhYQ==] [YQ==] [YQ==] $ java -cp commons-codec-1.4.jar:. B64 [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ== ] [YWF ``` You are a professional Java test case writer, please create a test case named `testEncoder` for the issue `Codec-CODEC-89`, utilizing the provided issue report information and the following function signature. ```java public void testEncoder() throws EncoderException { ```
370
[ "org.apache.commons.codec.binary.Base64" ]
0b3bc7e2a53390a7136932f4a52cf0474b8e7aee8becedf935d9469cdddca796
public void testEncoder() throws EncoderException
// You are a professional Java test case writer, please create a test case named `testEncoder` for the issue `Codec-CODEC-89`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Codec-CODEC-89 // // ## Issue-Title: // new Base64().encode() appends a CRLF, and chunks results into 76 character lines // // ## Issue-Description: // // The instance encode() method (e.g. new Base64().encode()) appends a CRLF. Actually it's fully chunking the output into 76 character lines. Commons-Codec-1.3 did not do this. The static Base64.encodeBase64() method behaves the same in both 1.3 and 1.4, so this problem only affects the instance encode() method. // // // // // ``` // import org.apache.commons.codec.binary.*; // // public class B64 { // // public static void main(String[] args) throws Exception { // Base64 b64 = new Base64(); // // String s1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // String s2 = "aaaaaaaaaa"; // String s3 = "a"; // // byte[] b1 = s1.getBytes("UTF-8"); // byte[] b2 = s2.getBytes("UTF-8"); // byte[] b3 = s3.getBytes("UTF-8"); // // byte[] result; // result = Base64.encodeBase64(b1); // System.out.println("[" + new String(result, "UTF-8") + "]"); // result = b64.encode(b1); // System.out.println("[" + new String(result, "UTF-8") + "]"); // // result = Base64.encodeBase64(b2); // System.out.println("[" + new String(result, "UTF-8") + "]"); // result = b64.encode(b2); // System.out.println("[" + new String(result, "UTF-8") + "]"); // // result = Base64.encodeBase64(b3); // System.out.println("[" + new String(result, "UTF-8") + "]"); // result = b64.encode(b3); // System.out.println("[" + new String(result, "UTF-8") + "]"); // // } // } // // ``` // // // Here's my output: // // // // // ``` // $ java -cp commons-codec-1.3.jar:. B64 // [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] // [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] // [YWFhYWFhYWFhYQ==] // [YWFhYWFhYWFhYQ==] // [YQ==] // [YQ==] // // // $ java -cp commons-codec-1.4.jar:. B64 // [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==] // [YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh // YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ== // ] // [YWF
Codec
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.binary; import junit.framework.TestCase; import junit.framework.TestFailure; import junit.framework.TestResult; import junit.framework.TestSuite; import org.apache.commons.codec.BinaryDecoder; import org.apache.commons.codec.BinaryEncoder; import org.apache.commons.codec.Decoder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.Encoder; import org.apache.commons.codec.EncoderException; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Enumeration; /** * Tests to make sure future versions of commons-codec.jar have identical Base64 * behavior as commons-codec-1.3.jar. * * @author Julius Davies * @since Mar 25, 2010 */ public class Base64Codec13Test extends TestCase { public Base64Codec13Test(String name) { super(name); } private final static String[] STRINGS = new String[181]; private final static String[] CHUNKED_STRINGS = new String[STRINGS.length]; private final static byte[][] BYTES = new byte[STRINGS.length][]; static { initSTRINGS(); initCHUNKED_STRINGS(); initBYTES(); } /* These strings were generated from random byte[] arrays fed into commons-codec-1.3.jar */ private static void initSTRINGS() { String[] s = STRINGS; s[0] = ""; s[1] = "uA=="; s[2] = "z9w="; s[3] = "TQ+Z"; s[4] = "bhjUYA=="; s[5] = "1cO9td8="; s[6] = "sMxHoJf5"; s[7] = "jQcPlDsZzw=="; s[8] = "TAaPnfW/CYU="; s[9] = "cXTZuwzXPONS"; s[10] = "Ltn/ZTV4IjT6OA=="; s[11] = "6fh+jdU31SOmWrc="; s[12] = "E/5MoD4qCvDuTcFA"; s[13] = "2n9YyfCMyMXembtssQ=="; s[14] = "qBka3Bq6V31HmcmHjkY="; s[15] = "WvyZe6kQ8py7m25ucawJ"; s[16] = "oYpxMy6BSpZXhVpOR6dXmA=="; s[63] = "yexFaNKaP+VkVwEUvxQXbC0HSCi/srOY7c036lT25frs4xjIvp214JHCg7OL/XZW3IMe6CDgSMCaaI91eRgM"; s[64] = "vkqgnuJ3plxNtoveiMJuYLN6wZQLpb3Fg48/zHkdFuDucuMKWVRO/niFRgKsFqcxq6VgCxwQbePiP9sRnxz7wg=="; s[65] = "YHks3GCb2uVF47Y2tCieiDGJ879Rm5dBhQhQizYhfWOo+BrB2/K+E7wZWTid14lMpM60+5C0N9JNKAcBESeqZZI="; s[66] = "z8551jmQp/Qs95tw226+HCHWruKx/JvfBCfQ5p0fF77mkSpp66E552ik2gycrBBsMC/NbznAgTZoMzZxehfJwu49"; s[67] = "VsR2whqq/qQm342+TNz1lgOZMoWbpCz+kj2zflq0nx7S/ReEVPUJcqgMtVzrr2FVQPfBAH5VRjR+hkxwv4bssQms8Q=="; s[68] = "5xmIp8dUJZzkisIkuEPsnPXvzDeMo48qWFfHIn2av3jr5qoZHCs0LfNEyepC3v2sa0nCU0FlqsmDyTI5/2jt5zsLtV0="; s[69] = "tGEgXjglUB9NbCtiS88AetLtRqhCAnhzOUKVgvbJZHqOA6x8uOorA1t3NcaIA00ZqbPYALu4LzIm4i4lAL9QgiH/Jg7b"; s[70] = "gFtxEhYJahDmU5dpudYs6ZTsqAx+s2j+06A0zeyb3U7nhZFsbkCDlds0EYUoqerZqZPm7F6CDOOD3dU7nYmelE0DxyMO9A=="; s[71] = "j/h/1JygYA5bjttxzQxr5gBtgh+AYVozhF4WgvcU/g49v0hUy6FdhfZewGK+Phtzj7RabI5p2zXyzvkmLQdFhdI5Um4O5sw="; s[72] = "m+kYVGojIR5pgbz7pGJm2g+3qqk7fhl3cowa2eVrhki7WofyywnRezqTxOkBgVFz6nKs8qxpbbbzALctcPeMsp9dpXUfuUJr"; s[73] = "pPaGnMr0UYmldnJVk/F+3WCJJ1r2otvD5KJdt2u1RnS6LwhHhwLCqfW8O/QEg43WdxKomGL/JM33tn/B9pMPoIU0QTGjq2GRow=="; s[74] = "mOxzGyym6T/BxCV5nSiIYMlfAUmCN7gt7+ZTMg1kd8Ptirk+JF5dk8USbWBu/9ZvNg5ZuiJCeGwfaVpqpZ3K9ySF7C87Jvu1RUE="; s[75] = "VYLOIE4DnhxJn3FKS/2RHHHYLlZiGVdV/k4uBbtAYHUSTpRzaaYPGNAVjdNwbTHIihmeuk/5YQUy8NFsxIom+Li7bnWiBoHKBPP7"; s[76] = "7foMpJ0TknCatjUiSxtnuKSiz4Qvl/idWY9UKiTljoQHZ+C8bcUscnI/bZr13e6AvyUh47MlpdGvzIm05qUdMWWLoZJOaGYvDmvrWQ=="; s[77] = "jxQSGiFs+b1TfE4lDUAPUPJ0SWeUgl03rK6auieWJcarDIHM97gGOHMmyHudRMqkZmIkxYRgYgCCUg/JeU91OZD3tL4U+wNhShywe88="; s[78] = "UGmH/gl7t3Dk801vRhRDEbgsfShtHZ1gZQn4KNZ5Qsw3WiGjW0ImInVHa+LSHBzLUjwC0Z3nXO4i4+CiKYqAspOViE6WqVUY8ZSV0Og4"; s[79] = "wdEoYmJuRng2z2IkAiSgJ1CW2VE7H7oXpYWEFFO8nG0bZn7PHhT8KyhaO2ridl8eUEysja0VXFDyQqSgZnvdUKrCGepWGZbw0/0bDws3Ag=="; s[80] = "5kZqgrUbt+rN5BWAddeUtm9TGT43vYpB6PeyQwTyy9Vbr0+U/4Qzy0Iw37Ra293HmkmpgQzuScVpcIiFGXPAFWwToR+bovwu7aXji/FnMwk="; s[81] = "E467MMmJbmwv8Omc2TdcyMr/30B8izWbf+CAuJtw67b1g9trhC6n4GYnXjeW9DYvmWoIJPx0zvU/Q+gqv0cteg2bx9P2mrgMDARb6egowqjx"; s[82] = "Vpt8hYb4jx1F+7REX7K65v6eO5F1GDg/K8SVLWDSp0srupYEQkBVRxnB9dmhSo9XHpz4C8pRl8r82fxXZummEf4U2Oh0Dip5rnNtDL+IJvL8lQ=="; s[121] = "hf69xr9mtFf4N3j2uA9MgLL5Zy94Hjv+VQi94+LS8972JJgDHCQOwP5whdQkV+SJpXkiyHGaSsQ4fhepPwzuZcEpYER+beny1j+M0HSZe36MdRIhlTqno+4qsXckL0CjXsYkJJM0NAfOYjHAus5G1bgi9VhmiMfAMA=="; s[122] = "yKzTh5hPp9/PBeZtrZXsFHAR9ywOM3hRaBDkgG9E09wFW8MZD0xMGegcp0QrTJcP8QYOaYhTDVimPqsNTVOmjdjkvS+2WhjJW4mVOXQ8KID91yaBtPo+DStL5GMgctcP5MoVf1Vp8w/mYtofqbllfDm5NfYzh2A7ijY="; s[123] = "csFmwvDzoO4IO6ySDA4B2V7emEetAwCgO66zzlfWb3KDrPfFZc3Jgr4+dlaUkEIDHYeLHETdTssWOl2KrPHBEsULpDTR+3OhurXb1Qr2NvHiHFuqT3Geb6EYw2albfTmXxch82ablt4WKl4qPcSey54v6tsCuUuZzrkt"; s[124] = "5InxvKwpoCV7EK78OzU/tL9/NmK14Prw9tOCAyK+xpUNLZriuVEVdgpoZ05rliufaUDGHH8dPAem8G9DN/VOPktB6vXKtc2kMUgnMTiZwv/UVd+xyqnT8PLEdNQ8rCWxyiCcLdXFf0+xcE7qCcwzC+D7+cRW+i6dnpZkyw=="; s[125] = "cEx7oTsSHWUFPj92cstdy5wGbRcxH+VRWN8kaNTTCPWqSckyU9Xk/jj5/gj9DFwjfsCSp60xutf4/rFanjtwqtRg6dJLP4JAgpOKswDlHi6Vt7zF/w7HidMf2sdtlsqzayZmT2Hn7iOo3CExzr5Z5JfmMFAX8R9peUN4t5U="; s[126] = "AeXetVbj+7mmGiCs3BGUSZDLlq2odMsN8JAHQM64Cly8y5jw75PpISocWRFFQmmXYP7ckKmtuhIvD69HtZxGhNRsl1l1gXzKFhsWykcRtG87F8sS1Uv/i6QvGiRIDVEGGIzWrzRIISkBb9wCxJ2HESfleWwrz/GqryjoN26B"; s[127] = "aj1/8/+U8VO3D2iAwvQXZ4H0KwtuzDm4JCC8+22ccqk+UzKvqjGs87XngwfsMfSkeGVAi6VB6tfNJTjYctaj7R8dwh2PIfLSrvaphw4wNB2REjplnPojoOb9bNUNtUvdK3b1bArOWugIRJWLnMl72yEHFb1iBfBmn7uIa7KT2Q=="; s[128] = "kiMuF/1CMRlgoS/uLKn1mNZFZNHJNkRQnivOrzj8HQAagwzvTXvsGgI9hXX3qaeZL9/x/Oq+Y5F6Dh+wXo+0kp6JagFjvbTJcQSowFzIwg7/V9sans0NE0Ejow5BfZKvihFI46sHiALl1qzoXqLQq+5fZGIFRyyY8wFW1uiNu9k="; s[129] = "YXmCWhiNz4/IhyxQIYjgNvjX+XwDiPTSBMaFELm5X8Y4knGRnkF4/zix8l9wHBb+7Cgfrr46rF7eiIzaAFLjLjjewy63duBJiVbEWjqFO0fu6T9iIjuEaF2sTppvuZNPHx80vN+HLAnAVmgFESw5APXWn15dizvuUfVHd5isCqbA"; s[130] = "GJfUoBivW5uqDpUxTRfjGWNYfN3/dTFtdRqCIH5L2c1nWX0dgY3ba1+fW/YX1Oh5aw4lC6BIiiThjJoV1VrNnlXzbcUcMy+GsDUUB8Qe8lBvfe/t4RmNPB0hVgrS89ntbuU0SsCmWw+9DqM3nidPebANKERig1zZTBBKgpVf7HPFCA=="; s[131] = "eTerNs7dOqJAxAxcMQRnUDc2cBj2x0jU1g1D3G+b22kDz7JBzOy/mxhGXAQ3130lavWMhImSBkReU+z0A13EYVMUv9PFzD747KCvns+SCo52YNHB0896b4l47q8hu8jsD17TZ2uWWJhS4cNnSE1jeM6NoXGKvf90yxfzwucNYc4RdaQ="; s[132] = "lbrGsjbzE521q8tzVHV7vcTPchUnzI/UfeR2R+cmOa29YljPWLht9Wx2JrjiKv4Of5nXe7kvhi+LYUuFVqgaqIFhC/PLbqOFiT2VZcXorToaRT9CLiqV5b6nHN/Txz6SI7MiD3hnk7psDbglPOo+ytqc9sFHj7UkR1ZctQjwFYwJjlxf"; s[133] = "mQwAPzYzfxz9FXEiZ6M8u1oN3EJbFYmNVfpm+j0DqgU+OPI4URHBIrF4xvdMvAPn0WuarbQy/ZVN0eKL7S4K3Mvan0flAwaZdI+e5HpkfxOoGTp8Dk5EFTXjmZ/s+GonePEQEGNVPL1WYoD6xXqAAvMLKtyrFcpoiGS9eDBlsZDQzPzz/g=="; s[134] = "3G6d12UY4l5W7Nnw0BL0HnViVg9SdEuLMqeZwy0RlJR/Ytcgd/mIxIuXXAlGhvhoX6Xc2BGU7RpTi1jYKzA86yul0j96dbcE4OtrP9lUBJlcY9eWz59dvLqKxwt3cEOBwrPf69MHuIa256es3AOCobfC8RQScW0PQ0QUa1VHB/eXSsVTSWg="; s[135] = "AxgrZKTFk5JvLC3DBACHwp266FxKI/yn9F+1tYkzL57RVs5HCJYS47VuG0T0E2wqzHqcLKPQMZWU7vbRoyMGNL3ZtaHoZqTqcq9KWtODC+OnEvSS7+1P4SmQDuyL2MJ/eJABJKNcu1K/Lk0buAaO0FvX6OGBcPzu1+dv/ZkwuORK07qRnxqQ"; s[136] = "atkG8l2U/Nnm+zLu7zjenrfcAVQJMUqHimFZ3cQfaUp4qyrFn1UiwZ33j66Vt63eVaT/FXx+LlEnsHn6ATPBMp3iEYoBJYyNpjz/zROhBbcznQAMdWUTcyKInvnG3x6ExgBXpyqfxxp/Pm8by7LlSUT5MKHdcu+TEfUXRokCr2iPnt7NYsNDfA=="; s[137] = "dciU1mSHGcBxOAVBgJx75J6DaQdBZfTIzQ04WhkkdRMupOZWSnv19xhz8hiO+ZnbBtDJuO5rHsUGzH/jYacfZyCQ924roRvkh3T1yxsLq3abZJUCD9HYnPTELVhv1+cEF4aoO3vGOu2FpfLUn5QTd0PozsIqcqZVB2V57B7DjfizUe3D8Yf5Vco="; s[138] = "dgR1PPacBvtILBmg33s9KWtuc67ndh3rCHZ/lIN7sENgbFqJQy5DC3XIeHTV7oWd+tJQaXxoC71/SU7Rz6OClAMKXLbMz8U6RPiqn3M7MRCQcDfNjA5cCNknXT9Ehz/IZF/7lcWrwxBKYm4B98lPkpZtR2QHndiQ3venzWrP0P5y27mReaFuaJ++"; s[139] = "1Q8rfp1HuGsxurTgGMakxj5SwNF7EixXxVPnfGADWDcygh5C1BMXqiL1AuVXOVFOsaydfLWGC8Kbh/JiL6H+12lYrNGUT9yJRIzRDi4XylMnrYwBtwCJjoHSi4exz5K2ih54utVAuzXZg6mnc9ied/mNRjj9d2HFD5mv0w/qTN/WFxEmtuZM/nMMag=="; s[140] = "w01TnPP/F3Vni3fBdV32Bnbb4J1FcbaE+Xn44no5ug77U8FS1gSm3LqJ8yTyXduzl5v2dwBEfziEfTuyqgeLLsCYTBjXmYOIHQosEl6DyAknu4XK52eQW+Fes9eSs2Nq+G4aaR4y4leeFNmCoZ9BQmAAZr0LFkqnvqaKmBVgcgxPs7/8SQHnpqvaU6Y="; s[141] = "OfzIF38Tp5g1W5eVbrkrMe0Mm7e0wBYg5hVvLpn/5MW5OFcmRDuBp15ayRBnJ1sBI93+CNl0LwP8Q0z9IXFjTER5gHZ1KfG8NV+oacKNG7aYrbUftkSL/oPfRNPez6U0FuWgvVrXUB6cwKTWvwb9KoD7s6AGYRdH50ZgJdBniFD7dKoOQnJ/ECuTUXI+"; s[142] = "4hoX0sjqlkSJPUq627iJkNYRbtD+V2qErCuTikaeRDEZvVHWvzdvwj4W1xxJjz+yHAN6z2EjCWidcSsVgTejQ1bH8uTzJgh/zq3yGUSsJoJWrecqxsge8bEBjkm+qUO8G3kAnC6FMjJ2NYQeXf6OK6OgsqyJwlHPTyAms2/IoYTB4iEqgIFG/2fNEJEIag=="; s[143] = "M/dy14xNbZMRfHiKKFdmD/OrEB+8MexrRO8mMh0i5LrNA5WUtLXdwUfAysYmal94MSoNJfgmwGCoqNwlWZBW1kpQaPdqsrn2cvc6JcZW9FlOx07DERJGbZ6l6ofbzZWgF+yf+hvT6jnJvXBVCTT3lfO3qo4leNuEJwsuU6erXGC3Ch53uPtGIrdDUpcX6/U="; s[144] = "GgLr2hd3nK64IZv0JksKAT/yJNQ38ayuWyBnWLjXbEmT048UDppsrrnP6hikRo5v2TlHGhD2dcwG9NLK3Ph8IoIo9Wf2vZWBB+SMI9FpgZxBWLEjwHbOWsHaEQMVsQfk38EWQP0Fr6VyMKlEQfpsRkuCpp1KxscaxK7g5BgXUlb0a2x0F+C9hEB0OVPsj4JN"; s[145] = "W9lKcLDqNGQAG/sKQNaRmeOUmLJ7GcMNqBaGZ659Rnjr6RTrfnmkp5Z9meALnwXoHjPjzSQDJnVYsY+xyMnuPgl6gMVAhAm+XprYVpsne4vt+7ojUqavVPBqLy5dtnhp1qfcnAiV5cZhHXX7NbxkUOzptjEGCQjnhSH4rPbZtgoIWE8Z6boF3l/thLnFX+AiiQ=="; s[146] = "iYLn5h9lIhD/x9moaPRnTX6mJEJKThg4WXxS7IrR2zblH26uOkINz0dJNTJVets0ZNYDnsnT7J2iI3Y6hTVWPGoYU49J3B2LhCREs0DZQ3C7080FtiOcfHbfBLNn0DyCK1LeAC7YB/bNdiyhLqH8fKl+0+KhiPDIUBJY2e7IbZR/9t0sxJbIXx6cRvI5AXex12o="; s[147] = "SlRJEc7npTUvQq8SgBYKmVY/3wHYp2gsDxafN/JLUuEqEjmWMtW7fxASi+ePX4gmJJqLhD5t+AZxiCwYK3L3ceuJx4TiqVgJz8d6sc7fgWXluh1K+BcGPbZ7+Cq4Vsga7JEBVekviEZ5Ah4apNr8RkB7oMOUVPGxRcyyaVE4zBW+scA6c1yi/HQXddQ9rWyLUsVo"; s[148] = "AAlbGR6ekLOzx4hpqZTUqVUQ0FL2CFpgCMOp6CuuUzkSnWXpUjvOiSDkNPgoTPgpgmg3uYvMsX43mkPGUGC9awDThXyGQh6u3WfWtmhiPRqXnjFek+EPd0LYXps71non6C9m7nUlYNWzBJ1YzrzWjlB5LLPBN8bsZG6RbdZkYMxJ9J5ta/c30m8wDDNuTm0nEE0ZVQ=="; s[149] = "nWWbBhzObqwEFh/TiKREcsqLYbRjIcZflJpol16Mi4YDL6EZri22qRnTgrBtIY+HieTYWuLaCSk/B9WcYujoS6Jb5dyg3FQ6XF9bYaNQGx2w8DHgx0k2nqH/0U1sAU0kft32aD2orqCMIprbO1WJIt2auRnvcOTFoOax926nAkxvR3nrFVDevFjDbugpWHkGwic6G7o="; s[150] = "WNk1Rn2qtG+gk0AEewrgo+aRbNrG4CgQpOR8Uo7c2m2XQY8MVDu4uRA6rzYGGdgqTcICKky9MvHeJeNWVAXOxmA4EdXQ2xItFJdQtxBt56cad9FBXXsz21yVsPr5d453abi7T3XfHVTToekiOlxAJs+bpat9cFRbIdHghO9wc/ucoArT53vpYsnyeVnmZG2PX48lXpNS"; s[151] = "wVmiO6mdf2aahrJlcmnBD0Qa58y8AvzXtJ54ImxgPLPn0NCQIrmUxzNZNTODE3WO6kZMECaT/REqT3PoOBp9stCHCFNXOM7979J44C1ZRU0yPCha00kQZBF5EmcLitVCz10tP8gG1fiIvMjwpd2ZTOaY4/g4NeJHLjJPll0c5nbH7n4v+1I+xG7/7k7G6N8sp21pbgpTYA=="; s[152] = "OoiVZosI+KG0EZTu+WpH7kKISxmO1zRYaSPMBMW0AyRiC2iZVEkOMiKn12XPqIDSW/kVA58cvv/ysTAzKLTu78Uo+sVcJe3AtLdgeA9vORFELTP4v9DQ/mAmehe3N8xk+VTLY6xHWi6f4j9cTDW/BDyJSDRY00oYoHlvnjgHo4CHBo0sMGgX3CwcnK2hpMFVtB/3qPl6v2w="; s[153] = "97ZVsTYwD8VrgN1FOIRZ8jm8OMgrxG3o1aJoYtPVWXp9cjjlgXqTMZVsoWr3pr7pudw+LYo1Ejz3JpiUPHqWcZ2PWrWs7PR1akYGuwdCBHYvCGTcZYFe/yu1AB8w5zYsl1eJR45g0u1DlXfx5BUAUzc4yJDjc48Ls62bn8t0EJ7+30sWwifqKuz2EHpsqp1j/iMlwzKJGjGE"; s[154] = "0NSYKTvBKKInwL9PJ/pWUWVX4gjF3igsA2qqQMsRew0lI1LcCB18eGCYk0AnyUCe99w5lWHGFUMMeH6DZciAylWGeDn19JdzVOTevBWk3LIujI1GvsEB3oVqf2Zl9IZeDGCT4+bQKBWvgcXHjysZfnn/5z9Xz06qrPqac5LfS36fDcwnkrUYQWDsL2Ike32ALmOnkcDjNq1BoA=="; s[155] = "5ok+rYI4LCgGa2psGUN/fdkT2gQEToB9HRiFXQpe2YcQvEN2z7YlJCETx4jSWw06p5Y8tZcp08moKNYwUJ40DvPpGlDG+wUpFhC4kkfo6vj6TrCj5yoWJi5D+qdgH2T0JeWM80cYN0bsOsetdaqNhDONlYXZ2lVYkyVS/wzw8K5xX87EWktwOwFq/yYhuWCYJ9GZL7QuDipJjEE="; s[156] = "KHzTalU9wPSnIjh5g0eHi1HUaFufxJpXpjDe0N3wEKINqbgzhbj3Kf4qWjb2d1A+0Mlu9tYF/kA9ONjda5jYfRgCHm5mUrjU0TAyT7EQFZ2u6WFK/sFHP++ycJQk8k7KLPUWA5OWScy1EO+dYF4d0r6K5O+7H/rpknxN6M9FlP8sH83DXK1Sd+UXL32D+4flF580FaZ5B3Tkx3dH"; s[157] = "RrJVxIKoDXtCviWMv/SXMO42Dn6UWOKDy2hh2ASXssT0e+G6m7F1230iJWlEN0wBR8p+BlTdBhQrn25098P3K16rBmZpzw/5dmesIJxhYPaM4GiaOgztFjuScTgkmV0Jl/vZ9eCXdEVNISeXkIixM4pssTFuUV7PY/Upzdj55rDKGLr1eT7AFVSNP30PhL8zZs8MANqKBeKBBDvtww=="; s[158] = "sy4t5rFA75GRBE+Dqa9sQxjPluKt/JnEY54guHnKqccmx3HGiyJ0jUA+et4XO8Xg69wCA9xVxJZQL73z80mVfIf43HIKOxgxT2IjG7EKMOD/qx6NnMTve4BryggLtbLQUeRfhriQeY7h65tD9ierhccXoXDpGnmBn9m2BQP78y+Qhc4eIsa3LcxbQJUIwvURjFp/rgMD7lhOLboa/2Y="; s[159] = "Zs/BfFoWImYau2dZLb7JneeTQp7sQ06yonEq0Ya4BNOJGy/5dGH42ozt0PpP2IZ/S58X7esVgc6jA1y3Bcxj3MPoDjQJSZHFEtR3G31T8eF5OpPVC4dw9s9clllM05tvcemssLdcd85UP/xBaDrmpAl8ZDSc73zflK3nJw8e0HQFYntNnlZPFyyyBLHnLycb6Jlvq7F2OqrZR+FXZnL3"; s[160] = "hdeDJuRnmb8q9EYec8+futT/CvqhpqoUdtmG6E31RrYJDs96M5Wfng90IEqrncZe4rVYDocRZK23dvqtJaPhTUBXXh42IyMlUnro69KI+075FvYYwgVaUd10r7ExWM5Z7DCQ2x8Tm1meK2YCTPkF1VXXexl1UjYCnRQuQxppdophMwroJK8VqlJbFFslchTSBFuI7wgcdy+f/LHMbMsusQ=="; s[161] = "ClCCOv0mD9//LR0OisHfamxcTvmlwMLgAIQt3hbOjRPkXwEgaDzP0u6LN8BNwdOVw+LhrbzMI8zQzHvo7mGPkQICeeim/x+xmGPQtmWnXxCWiL1uf/8eR5Wuy9Er8skTB8rG4/ubb2ssvCkubObPAkMSOgFnX9UtxnCN4+nMNV2vvn4xMTSvvQyYWewfnlNkflTyva1epE9RVW2RqRtJikY="; s[162] = "Fs+AmFCnUr/imw8D0GpNidIP9qwW8yRAzmtqPS+vT6n5U4YFQcpgbznrYO4TPqkVF2oz1mpgLYIgx/u2XsrtljGX46LfY8OyUPaw4/da38QGngoIlS2cN01cgN3efSjMlnZFo1x8T9p0Nn1IgRgevOd5ezVUL7WdY7eeiE1pXXcGBgDYn7NDQph0dC6HDlBiS95bDFcZ+6FYigE4WybpsOHL"; s[163] = "wgO4DdGZy9g13IuOhkJGJcToyLuCBVm9T/c8qY4NOheVU1NW2g8sPIo+RiEsSST8sx6+Jh/A/kaCxYvJ9CsgnBjZMMWRsd383HZAoJtkxwKvyoeXzzD+puFvqKQBEKrlBEwffXhLDoFQAW2ycYtBGztl0GsUtoOob2nv7ienx1xD6KNZNaxYx2ObRAYS/e8LS3pg5dku9MPBp1X12m8ZIXRAaw=="; s[164] = "EkXt02SaRUIjFmoLxyO6N+giL4iA4fY0Exao+mjgEfZ+Wv6w95GXHBI1xlYMVLkOcnu9nescvcXQH0OrqL9uforEUTGTSg2ci67m4GrwAryMy+5eUo77Q5GpWKfsg8nDbD8a3gUI/9EE0sCNp7tMaKwoJ56cxhbG3TJYpqWTpq3/S3q76x+3ETL+zxh6EMh8MJPfWcIxlDS7evKqdPgS00KgUtk="; s[165] = "OuBqx5LFJroRbDn41+4azFHlKgw6bMgbsRGaK9UnPvi5xfmV4SLQ2YzIhopGi1F57L6vKukaW0XlFk/Ff5Td5IMC7U+kvXKlf8fGIIQ8FaHI0vbIX89OJlBqlICqftSNiVRxtaE+aCh0rBoDfgPwuC8qBC20I1O3ZLuKfeUVGkMOLEWeZLS6mmcn3cSERj9o/dEl8QYwQvhH+VG6YWF//yki1Vu8"; s[166] = "SO/vDsqZDdImOdH19sZI7FUVhlx1EI0XRr8ArTuAG5F8LDK76Bct2C7fXTUowilXnJWhQxvbGiulkUGSuVjVP12zac9bShRpr1L3ucde7n1f9y/NcHJCwdqTLq7RYygItQ4ppQGiP9jXf2Dn/qmVZZTh+SY3AZCIS+OVo2LAiYJHWnzzoX8Zt+dOYiOA/ZQKZieVJlc8ks+2xqYPD55eH0btZn5hzA=="; s[167] = "tZL/qACMO9SzmgJhWQMsbKgE5lPAEbxn3NR7504ilgArR8j7uv1KF46uQyjrkEnyBormYB/6nLGlHht62IQftMYf5gHpHFfTvukRKF8728yIYAAYHPQ/WjHzHdVSqUJqF2a8RE6SvvY+KSKWLMU3hjn1f6dqX599hYD7AnbPGTpFKDU5sLFOXbuynU1sPUhP+a4Hev9yNU6atLDo4CkX/Yq3FbpWVuQ="; s[168] = "GRe7uF1wH5/71B3vmGF+pN3H9PKO1tLwsnb0D4/Pm7Pu5KAe4OfelkfFIBgyjuoZrpeEkGZnb+qf+Kn7Kt1hDwYr/Mb9ewuwOXsbIpLQMgfh0I5XsPrWocduVzn+u/cm3cr0Z11zsx0AZjTqvslACkDqiquY41JhtGdc22RCvIYom2l+zzMIMyCPsHeCSB1MBu8EWK3iP7SD3dWttwzMg0xanoPDgk0U"; s[169] = "8BDFu+29lptlGSjcZe7ghWaUgIzbuUpM5XDFbtJVQPEd3bAE0cGRlQE9EhKXi5J/IskYNrQ357tBhA+UNDNXCibT2AZGpzWAcwE6dP+14FuRL5Gxqh/teuPYKr5IIn7M3SbgOychZzLI7HGCvVhBUiJBu8orI3WmAIVcUhAsMGHsFveck/ZCXQA+Uq/WVnW1VNs6hSmIhsAFc51qsmsQK07z2Wptx4rRjw=="; s[170] = "siPSXD4u36WYtTvvDzRlFPiuZMnRczrL3eA15955JDCc6/V2Cvu6m/HPO6JxogxO0aYTZ5tejYDOIZgBy40DgUZMqPJ2IpYjsmUbjjJU8u/OpwhMon525m3v0EYlvyj2Qp3pwFKDkvncK3aNjN3KaaX6HuIy6kyqsDl0BTEnB5iJyHLRBCkeznTK019u48Yfsrz2oGuZcWzNj5/vKMdxQPiyJ9EHyox8Ark="; s[171] = "+/14PnFQVZ7BTHKUvkTtRrYS7WnPND5gZ5byMhUrDLkJa6UPBV7z0nrDMifEo/dQfUq3EjCiG6xGVhrUvAzgxqOQZTW1Y9p9M0KWW+E0XvCQppHFpuMqF1vYsF0OD6AMiE9JtGnWs3JcaWP/XBF/CvhQlFGbHi3fbrD/haTEBnmpJWBgMdKribdbXHtBSFZ2MzCX2eDtxoDdRdEVGs4v/q8gVBS+WsnZ3TTF"; s[172] = "31I1ja+B+aopKkztGzJYvJEWAshyoAAV5yve4LnP0kdImUQaVETSuo5CDIYr7zM8MCD1eYPpLicmGnA+C927o9QGAVL3ctO/DCWhNinW7NmeYIM+o4diKBkDPjHmSWa+nq4nr+gOap4CtwL2wW2B5Yqt26pKgN9uAU5CmTL26hYFgMEOZfrkQ7XdYGy2CN8RJLmjeSFVVNBG/FTaK7tpuy0LQSkko6wczBYGeg=="; s[173] = "XbRfDqGe3eeI1tHx8UnPneDB57N8VeSSzXzVCNSgxOEfd6d/un5CDxHG+m4w3tIbtSky4R2+zMF+S5cRvTOwZ/veegYtLKTxA0mVedWLFkfh/v4NgPJ+NEU+cylbSSZLAeBofDvoJwnYKujN2KFa8PGAxr3Y8ry3qdkS8Ob1ZiHYAmLvKS9sGb/vjTvRy+a4Q7kOepsm7PYisinKelBAvDnjli6/lOutGrenjX4="; s[174] = "jGEj/AaBefac9uOcmGuO9nH+N+zMsC4qAe6ZUEMMIXdTGnSWl7Xt0/nKqyOj3ZH249HwkJ8bn5C+0bzOpQ1eA3PxEq6RfKMrjHJPJmTZXrSESTjfj3oNLU/CqqDOqd8znTgN6nvnUdCeStLMh9bmWF1+0G11nDwg6GQWWQ0zjVDTq5j7ocXcFOyUcu0cyl5YDcUP0i2mA2JullInU2uBte7nToeSGB3FJxKueBbv"; s[175] = "RAzNCxlP2S/8LfbGtlSDShox8cSgmJMOc2xPFs8egZVJiwlmnS3aBWKPRbbxkZiVVYlu4GNJNwbocc6dgrl28HXAsYikE5wwoQ1MeOJWU3zzFiYENh7SLBQfjVPQHucctr8P6Rl7YL5wHc+aC+m92R3bnzm5rp1PeHm7uzy2iUUN0cgfbwJ4FrpXhVMTsAUpTbg1+037EWcGOuxir4dG2xBfgOwa+ejFHkw7y0LWRw=="; s[176] = "08hmZptBGKKqR6Qz9GNc2Wk1etgU/KogbiPQmAh5IXlTBc97DuEToL4Bb889nfObVQ/WelmiCS8wEjSBdmnlkkU7/b5UT3P4k1pB6ZxPH9Qldj5aazkA/yCb0kzDfJlcdFOh1eAcu5LvwTXOizmPwsDvJEnOkaDZrKESZshsHU2A6Mx6awk9/orf6iBlJHQIIH3l4o3b1gx2TNb/hUgdAlwtQDhvKO3skB0PS+rcWAw="; s[177] = "0GhrgbSSHPLWtyS2mnSxrNAj/dyrFQcxIgPjT7+78SZ1ZTGc03vsmlZ4Z/bOO84E9yKblaI5dSHVXrx57L0kikL8tgKCsAkUNO3l/4zv5FfCrRTgGx4sFTFB1NNcLcwagkvFzde764DjYmj4YZhYsXSZCVKi0uu5M8fpgGDZ9UMSFR008cbhaIoFLWSANqiNJYSvTQZhGWfLtIPGLN+gIOMcaKhx1b5vg6OYSz6ScAM/"; s[178] = "2VGiMV/f2hNZAjw3fdeHx/wRIVzeP018lZynzwSySG/zQBxyRmi3YmKVZmh3aJunuiqmvdt0kJ6lX7M8BajYHPCBkqJOx8oPJ/K1oADxVgnavZ69dKYrSy9/Pm6sHxjFrdSz9TelUK9sgoFTWS6GxgzWEqXRBDDpGUnsNbSEcWLPKVLNNoYAcltY98JZaNSZBXcpa9FeSN7sVU43q2IEcDx3ZkJzRJpl/lb7n+ivMwX/OQ=="; s[179] = "iMSCh1m5vct3C7LEn5wKRYtalzvG6pKahG19rTb6Z9q7+buDsML5yM6NqDvoVxt3Dv7KRwdS3xG/Pyb7bJGvQ2a4FhRnTa4HvPvl3cpJdMgCCvsXeXXoML4pHzFlpP0bNsMoupmhQ0khAW51PAr4B165u1y5ULpruxE+dGx/HJUQyMfGhOSZ5jDKKxD5TNYQkDEY28Xqln6Fj8duzQLzMIgSoD8KGZKD8jm6/f8Vwvf43NE="; s[180] = "hN4+x/sK9FRZn5llaw7/XDGwht3BcIxAFP4JoGqVQCw8c5IOlSqKEOViYss1mnvko6kVrc2iMEA8h8RssJ4dJBpFDZ/bkehCyhQmWpspZtAvRN59mj6nx0SBglYGccPyrn3e0uvvGJ5nYmjTA7gqB0Y+FFGAYwgAO345ipxTrMFsnJ8a913GzpobJdcHiw5hfqYK2iqo8STzVljaGMc5WSzP69vFDTHSS39YSfbE890TPBgm"; } /* These are chunked versions of the strings above (chunked by commons-codec-1.3.jar) */ private static void initCHUNKED_STRINGS() { String[] c = CHUNKED_STRINGS; c[0] = ""; c[1] = "uA==\r\n"; c[2] = "z9w=\r\n"; c[3] = "TQ+Z\r\n"; c[4] = "bhjUYA==\r\n"; c[5] = "1cO9td8=\r\n"; c[6] = "sMxHoJf5\r\n"; c[7] = "jQcPlDsZzw==\r\n"; c[8] = "TAaPnfW/CYU=\r\n"; c[9] = "cXTZuwzXPONS\r\n"; c[10] = "Ltn/ZTV4IjT6OA==\r\n"; c[11] = "6fh+jdU31SOmWrc=\r\n"; c[12] = "E/5MoD4qCvDuTcFA\r\n"; c[13] = "2n9YyfCMyMXembtssQ==\r\n"; c[14] = "qBka3Bq6V31HmcmHjkY=\r\n"; c[15] = "WvyZe6kQ8py7m25ucawJ\r\n"; c[16] = "oYpxMy6BSpZXhVpOR6dXmA==\r\n"; c[63] = "yexFaNKaP+VkVwEUvxQXbC0HSCi/srOY7c036lT25frs4xjIvp214JHCg7OL/XZW3IMe6CDgSMCa\r\naI91eRgM\r\n"; c[64] = "vkqgnuJ3plxNtoveiMJuYLN6wZQLpb3Fg48/zHkdFuDucuMKWVRO/niFRgKsFqcxq6VgCxwQbePi\r\nP9sRnxz7wg==\r\n"; c[65] = "YHks3GCb2uVF47Y2tCieiDGJ879Rm5dBhQhQizYhfWOo+BrB2/K+E7wZWTid14lMpM60+5C0N9JN\r\nKAcBESeqZZI=\r\n"; c[66] = "z8551jmQp/Qs95tw226+HCHWruKx/JvfBCfQ5p0fF77mkSpp66E552ik2gycrBBsMC/NbznAgTZo\r\nMzZxehfJwu49\r\n"; c[67] = "VsR2whqq/qQm342+TNz1lgOZMoWbpCz+kj2zflq0nx7S/ReEVPUJcqgMtVzrr2FVQPfBAH5VRjR+\r\nhkxwv4bssQms8Q==\r\n"; c[68] = "5xmIp8dUJZzkisIkuEPsnPXvzDeMo48qWFfHIn2av3jr5qoZHCs0LfNEyepC3v2sa0nCU0FlqsmD\r\nyTI5/2jt5zsLtV0=\r\n"; c[69] = "tGEgXjglUB9NbCtiS88AetLtRqhCAnhzOUKVgvbJZHqOA6x8uOorA1t3NcaIA00ZqbPYALu4LzIm\r\n4i4lAL9QgiH/Jg7b\r\n"; c[70] = "gFtxEhYJahDmU5dpudYs6ZTsqAx+s2j+06A0zeyb3U7nhZFsbkCDlds0EYUoqerZqZPm7F6CDOOD\r\n3dU7nYmelE0DxyMO9A==\r\n"; c[71] = "j/h/1JygYA5bjttxzQxr5gBtgh+AYVozhF4WgvcU/g49v0hUy6FdhfZewGK+Phtzj7RabI5p2zXy\r\nzvkmLQdFhdI5Um4O5sw=\r\n"; c[72] = "m+kYVGojIR5pgbz7pGJm2g+3qqk7fhl3cowa2eVrhki7WofyywnRezqTxOkBgVFz6nKs8qxpbbbz\r\nALctcPeMsp9dpXUfuUJr\r\n"; c[73] = "pPaGnMr0UYmldnJVk/F+3WCJJ1r2otvD5KJdt2u1RnS6LwhHhwLCqfW8O/QEg43WdxKomGL/JM33\r\ntn/B9pMPoIU0QTGjq2GRow==\r\n"; c[74] = "mOxzGyym6T/BxCV5nSiIYMlfAUmCN7gt7+ZTMg1kd8Ptirk+JF5dk8USbWBu/9ZvNg5ZuiJCeGwf\r\naVpqpZ3K9ySF7C87Jvu1RUE=\r\n"; c[75] = "VYLOIE4DnhxJn3FKS/2RHHHYLlZiGVdV/k4uBbtAYHUSTpRzaaYPGNAVjdNwbTHIihmeuk/5YQUy\r\n8NFsxIom+Li7bnWiBoHKBPP7\r\n"; c[76] = "7foMpJ0TknCatjUiSxtnuKSiz4Qvl/idWY9UKiTljoQHZ+C8bcUscnI/bZr13e6AvyUh47MlpdGv\r\nzIm05qUdMWWLoZJOaGYvDmvrWQ==\r\n"; c[77] = "jxQSGiFs+b1TfE4lDUAPUPJ0SWeUgl03rK6auieWJcarDIHM97gGOHMmyHudRMqkZmIkxYRgYgCC\r\nUg/JeU91OZD3tL4U+wNhShywe88=\r\n"; c[78] = "UGmH/gl7t3Dk801vRhRDEbgsfShtHZ1gZQn4KNZ5Qsw3WiGjW0ImInVHa+LSHBzLUjwC0Z3nXO4i\r\n4+CiKYqAspOViE6WqVUY8ZSV0Og4\r\n"; c[79] = "wdEoYmJuRng2z2IkAiSgJ1CW2VE7H7oXpYWEFFO8nG0bZn7PHhT8KyhaO2ridl8eUEysja0VXFDy\r\nQqSgZnvdUKrCGepWGZbw0/0bDws3Ag==\r\n"; c[80] = "5kZqgrUbt+rN5BWAddeUtm9TGT43vYpB6PeyQwTyy9Vbr0+U/4Qzy0Iw37Ra293HmkmpgQzuScVp\r\ncIiFGXPAFWwToR+bovwu7aXji/FnMwk=\r\n"; c[81] = "E467MMmJbmwv8Omc2TdcyMr/30B8izWbf+CAuJtw67b1g9trhC6n4GYnXjeW9DYvmWoIJPx0zvU/\r\nQ+gqv0cteg2bx9P2mrgMDARb6egowqjx\r\n"; c[82] = "Vpt8hYb4jx1F+7REX7K65v6eO5F1GDg/K8SVLWDSp0srupYEQkBVRxnB9dmhSo9XHpz4C8pRl8r8\r\n2fxXZummEf4U2Oh0Dip5rnNtDL+IJvL8lQ==\r\n"; c[121] = "hf69xr9mtFf4N3j2uA9MgLL5Zy94Hjv+VQi94+LS8972JJgDHCQOwP5whdQkV+SJpXkiyHGaSsQ4\r\nfhepPwzuZcEpYER+beny1j+M0HSZe36MdRIhlTqno+4qsXckL0CjXsYkJJM0NAfOYjHAus5G1bgi\r\n9VhmiMfAMA==\r\n"; c[122] = "yKzTh5hPp9/PBeZtrZXsFHAR9ywOM3hRaBDkgG9E09wFW8MZD0xMGegcp0QrTJcP8QYOaYhTDVim\r\nPqsNTVOmjdjkvS+2WhjJW4mVOXQ8KID91yaBtPo+DStL5GMgctcP5MoVf1Vp8w/mYtofqbllfDm5\r\nNfYzh2A7ijY=\r\n"; c[123] = "csFmwvDzoO4IO6ySDA4B2V7emEetAwCgO66zzlfWb3KDrPfFZc3Jgr4+dlaUkEIDHYeLHETdTssW\r\nOl2KrPHBEsULpDTR+3OhurXb1Qr2NvHiHFuqT3Geb6EYw2albfTmXxch82ablt4WKl4qPcSey54v\r\n6tsCuUuZzrkt\r\n"; c[124] = "5InxvKwpoCV7EK78OzU/tL9/NmK14Prw9tOCAyK+xpUNLZriuVEVdgpoZ05rliufaUDGHH8dPAem\r\n8G9DN/VOPktB6vXKtc2kMUgnMTiZwv/UVd+xyqnT8PLEdNQ8rCWxyiCcLdXFf0+xcE7qCcwzC+D7\r\n+cRW+i6dnpZkyw==\r\n"; c[125] = "cEx7oTsSHWUFPj92cstdy5wGbRcxH+VRWN8kaNTTCPWqSckyU9Xk/jj5/gj9DFwjfsCSp60xutf4\r\n/rFanjtwqtRg6dJLP4JAgpOKswDlHi6Vt7zF/w7HidMf2sdtlsqzayZmT2Hn7iOo3CExzr5Z5Jfm\r\nMFAX8R9peUN4t5U=\r\n"; c[126] = "AeXetVbj+7mmGiCs3BGUSZDLlq2odMsN8JAHQM64Cly8y5jw75PpISocWRFFQmmXYP7ckKmtuhIv\r\nD69HtZxGhNRsl1l1gXzKFhsWykcRtG87F8sS1Uv/i6QvGiRIDVEGGIzWrzRIISkBb9wCxJ2HESfl\r\neWwrz/GqryjoN26B\r\n"; c[127] = "aj1/8/+U8VO3D2iAwvQXZ4H0KwtuzDm4JCC8+22ccqk+UzKvqjGs87XngwfsMfSkeGVAi6VB6tfN\r\nJTjYctaj7R8dwh2PIfLSrvaphw4wNB2REjplnPojoOb9bNUNtUvdK3b1bArOWugIRJWLnMl72yEH\r\nFb1iBfBmn7uIa7KT2Q==\r\n"; c[128] = "kiMuF/1CMRlgoS/uLKn1mNZFZNHJNkRQnivOrzj8HQAagwzvTXvsGgI9hXX3qaeZL9/x/Oq+Y5F6\r\nDh+wXo+0kp6JagFjvbTJcQSowFzIwg7/V9sans0NE0Ejow5BfZKvihFI46sHiALl1qzoXqLQq+5f\r\nZGIFRyyY8wFW1uiNu9k=\r\n"; c[129] = "YXmCWhiNz4/IhyxQIYjgNvjX+XwDiPTSBMaFELm5X8Y4knGRnkF4/zix8l9wHBb+7Cgfrr46rF7e\r\niIzaAFLjLjjewy63duBJiVbEWjqFO0fu6T9iIjuEaF2sTppvuZNPHx80vN+HLAnAVmgFESw5APXW\r\nn15dizvuUfVHd5isCqbA\r\n"; c[130] = "GJfUoBivW5uqDpUxTRfjGWNYfN3/dTFtdRqCIH5L2c1nWX0dgY3ba1+fW/YX1Oh5aw4lC6BIiiTh\r\njJoV1VrNnlXzbcUcMy+GsDUUB8Qe8lBvfe/t4RmNPB0hVgrS89ntbuU0SsCmWw+9DqM3nidPebAN\r\nKERig1zZTBBKgpVf7HPFCA==\r\n"; c[131] = "eTerNs7dOqJAxAxcMQRnUDc2cBj2x0jU1g1D3G+b22kDz7JBzOy/mxhGXAQ3130lavWMhImSBkRe\r\nU+z0A13EYVMUv9PFzD747KCvns+SCo52YNHB0896b4l47q8hu8jsD17TZ2uWWJhS4cNnSE1jeM6N\r\noXGKvf90yxfzwucNYc4RdaQ=\r\n"; c[132] = "lbrGsjbzE521q8tzVHV7vcTPchUnzI/UfeR2R+cmOa29YljPWLht9Wx2JrjiKv4Of5nXe7kvhi+L\r\nYUuFVqgaqIFhC/PLbqOFiT2VZcXorToaRT9CLiqV5b6nHN/Txz6SI7MiD3hnk7psDbglPOo+ytqc\r\n9sFHj7UkR1ZctQjwFYwJjlxf\r\n"; c[133] = "mQwAPzYzfxz9FXEiZ6M8u1oN3EJbFYmNVfpm+j0DqgU+OPI4URHBIrF4xvdMvAPn0WuarbQy/ZVN\r\n0eKL7S4K3Mvan0flAwaZdI+e5HpkfxOoGTp8Dk5EFTXjmZ/s+GonePEQEGNVPL1WYoD6xXqAAvML\r\nKtyrFcpoiGS9eDBlsZDQzPzz/g==\r\n"; c[134] = "3G6d12UY4l5W7Nnw0BL0HnViVg9SdEuLMqeZwy0RlJR/Ytcgd/mIxIuXXAlGhvhoX6Xc2BGU7RpT\r\ni1jYKzA86yul0j96dbcE4OtrP9lUBJlcY9eWz59dvLqKxwt3cEOBwrPf69MHuIa256es3AOCobfC\r\n8RQScW0PQ0QUa1VHB/eXSsVTSWg=\r\n"; c[135] = "AxgrZKTFk5JvLC3DBACHwp266FxKI/yn9F+1tYkzL57RVs5HCJYS47VuG0T0E2wqzHqcLKPQMZWU\r\n7vbRoyMGNL3ZtaHoZqTqcq9KWtODC+OnEvSS7+1P4SmQDuyL2MJ/eJABJKNcu1K/Lk0buAaO0FvX\r\n6OGBcPzu1+dv/ZkwuORK07qRnxqQ\r\n"; c[136] = "atkG8l2U/Nnm+zLu7zjenrfcAVQJMUqHimFZ3cQfaUp4qyrFn1UiwZ33j66Vt63eVaT/FXx+LlEn\r\nsHn6ATPBMp3iEYoBJYyNpjz/zROhBbcznQAMdWUTcyKInvnG3x6ExgBXpyqfxxp/Pm8by7LlSUT5\r\nMKHdcu+TEfUXRokCr2iPnt7NYsNDfA==\r\n"; c[137] = "dciU1mSHGcBxOAVBgJx75J6DaQdBZfTIzQ04WhkkdRMupOZWSnv19xhz8hiO+ZnbBtDJuO5rHsUG\r\nzH/jYacfZyCQ924roRvkh3T1yxsLq3abZJUCD9HYnPTELVhv1+cEF4aoO3vGOu2FpfLUn5QTd0Po\r\nzsIqcqZVB2V57B7DjfizUe3D8Yf5Vco=\r\n"; c[138] = "dgR1PPacBvtILBmg33s9KWtuc67ndh3rCHZ/lIN7sENgbFqJQy5DC3XIeHTV7oWd+tJQaXxoC71/\r\nSU7Rz6OClAMKXLbMz8U6RPiqn3M7MRCQcDfNjA5cCNknXT9Ehz/IZF/7lcWrwxBKYm4B98lPkpZt\r\nR2QHndiQ3venzWrP0P5y27mReaFuaJ++\r\n"; c[139] = "1Q8rfp1HuGsxurTgGMakxj5SwNF7EixXxVPnfGADWDcygh5C1BMXqiL1AuVXOVFOsaydfLWGC8Kb\r\nh/JiL6H+12lYrNGUT9yJRIzRDi4XylMnrYwBtwCJjoHSi4exz5K2ih54utVAuzXZg6mnc9ied/mN\r\nRjj9d2HFD5mv0w/qTN/WFxEmtuZM/nMMag==\r\n"; c[140] = "w01TnPP/F3Vni3fBdV32Bnbb4J1FcbaE+Xn44no5ug77U8FS1gSm3LqJ8yTyXduzl5v2dwBEfziE\r\nfTuyqgeLLsCYTBjXmYOIHQosEl6DyAknu4XK52eQW+Fes9eSs2Nq+G4aaR4y4leeFNmCoZ9BQmAA\r\nZr0LFkqnvqaKmBVgcgxPs7/8SQHnpqvaU6Y=\r\n"; c[141] = "OfzIF38Tp5g1W5eVbrkrMe0Mm7e0wBYg5hVvLpn/5MW5OFcmRDuBp15ayRBnJ1sBI93+CNl0LwP8\r\nQ0z9IXFjTER5gHZ1KfG8NV+oacKNG7aYrbUftkSL/oPfRNPez6U0FuWgvVrXUB6cwKTWvwb9KoD7\r\ns6AGYRdH50ZgJdBniFD7dKoOQnJ/ECuTUXI+\r\n"; c[142] = "4hoX0sjqlkSJPUq627iJkNYRbtD+V2qErCuTikaeRDEZvVHWvzdvwj4W1xxJjz+yHAN6z2EjCWid\r\ncSsVgTejQ1bH8uTzJgh/zq3yGUSsJoJWrecqxsge8bEBjkm+qUO8G3kAnC6FMjJ2NYQeXf6OK6Og\r\nsqyJwlHPTyAms2/IoYTB4iEqgIFG/2fNEJEIag==\r\n"; c[143] = "M/dy14xNbZMRfHiKKFdmD/OrEB+8MexrRO8mMh0i5LrNA5WUtLXdwUfAysYmal94MSoNJfgmwGCo\r\nqNwlWZBW1kpQaPdqsrn2cvc6JcZW9FlOx07DERJGbZ6l6ofbzZWgF+yf+hvT6jnJvXBVCTT3lfO3\r\nqo4leNuEJwsuU6erXGC3Ch53uPtGIrdDUpcX6/U=\r\n"; c[144] = "GgLr2hd3nK64IZv0JksKAT/yJNQ38ayuWyBnWLjXbEmT048UDppsrrnP6hikRo5v2TlHGhD2dcwG\r\n9NLK3Ph8IoIo9Wf2vZWBB+SMI9FpgZxBWLEjwHbOWsHaEQMVsQfk38EWQP0Fr6VyMKlEQfpsRkuC\r\npp1KxscaxK7g5BgXUlb0a2x0F+C9hEB0OVPsj4JN\r\n"; c[145] = "W9lKcLDqNGQAG/sKQNaRmeOUmLJ7GcMNqBaGZ659Rnjr6RTrfnmkp5Z9meALnwXoHjPjzSQDJnVY\r\nsY+xyMnuPgl6gMVAhAm+XprYVpsne4vt+7ojUqavVPBqLy5dtnhp1qfcnAiV5cZhHXX7NbxkUOzp\r\ntjEGCQjnhSH4rPbZtgoIWE8Z6boF3l/thLnFX+AiiQ==\r\n"; c[146] = "iYLn5h9lIhD/x9moaPRnTX6mJEJKThg4WXxS7IrR2zblH26uOkINz0dJNTJVets0ZNYDnsnT7J2i\r\nI3Y6hTVWPGoYU49J3B2LhCREs0DZQ3C7080FtiOcfHbfBLNn0DyCK1LeAC7YB/bNdiyhLqH8fKl+\r\n0+KhiPDIUBJY2e7IbZR/9t0sxJbIXx6cRvI5AXex12o=\r\n"; c[147] = "SlRJEc7npTUvQq8SgBYKmVY/3wHYp2gsDxafN/JLUuEqEjmWMtW7fxASi+ePX4gmJJqLhD5t+AZx\r\niCwYK3L3ceuJx4TiqVgJz8d6sc7fgWXluh1K+BcGPbZ7+Cq4Vsga7JEBVekviEZ5Ah4apNr8RkB7\r\noMOUVPGxRcyyaVE4zBW+scA6c1yi/HQXddQ9rWyLUsVo\r\n"; c[148] = "AAlbGR6ekLOzx4hpqZTUqVUQ0FL2CFpgCMOp6CuuUzkSnWXpUjvOiSDkNPgoTPgpgmg3uYvMsX43\r\nmkPGUGC9awDThXyGQh6u3WfWtmhiPRqXnjFek+EPd0LYXps71non6C9m7nUlYNWzBJ1YzrzWjlB5\r\nLLPBN8bsZG6RbdZkYMxJ9J5ta/c30m8wDDNuTm0nEE0ZVQ==\r\n"; c[149] = "nWWbBhzObqwEFh/TiKREcsqLYbRjIcZflJpol16Mi4YDL6EZri22qRnTgrBtIY+HieTYWuLaCSk/\r\nB9WcYujoS6Jb5dyg3FQ6XF9bYaNQGx2w8DHgx0k2nqH/0U1sAU0kft32aD2orqCMIprbO1WJIt2a\r\nuRnvcOTFoOax926nAkxvR3nrFVDevFjDbugpWHkGwic6G7o=\r\n"; c[150] = "WNk1Rn2qtG+gk0AEewrgo+aRbNrG4CgQpOR8Uo7c2m2XQY8MVDu4uRA6rzYGGdgqTcICKky9MvHe\r\nJeNWVAXOxmA4EdXQ2xItFJdQtxBt56cad9FBXXsz21yVsPr5d453abi7T3XfHVTToekiOlxAJs+b\r\npat9cFRbIdHghO9wc/ucoArT53vpYsnyeVnmZG2PX48lXpNS\r\n"; c[151] = "wVmiO6mdf2aahrJlcmnBD0Qa58y8AvzXtJ54ImxgPLPn0NCQIrmUxzNZNTODE3WO6kZMECaT/REq\r\nT3PoOBp9stCHCFNXOM7979J44C1ZRU0yPCha00kQZBF5EmcLitVCz10tP8gG1fiIvMjwpd2ZTOaY\r\n4/g4NeJHLjJPll0c5nbH7n4v+1I+xG7/7k7G6N8sp21pbgpTYA==\r\n"; c[152] = "OoiVZosI+KG0EZTu+WpH7kKISxmO1zRYaSPMBMW0AyRiC2iZVEkOMiKn12XPqIDSW/kVA58cvv/y\r\nsTAzKLTu78Uo+sVcJe3AtLdgeA9vORFELTP4v9DQ/mAmehe3N8xk+VTLY6xHWi6f4j9cTDW/BDyJ\r\nSDRY00oYoHlvnjgHo4CHBo0sMGgX3CwcnK2hpMFVtB/3qPl6v2w=\r\n"; c[153] = "97ZVsTYwD8VrgN1FOIRZ8jm8OMgrxG3o1aJoYtPVWXp9cjjlgXqTMZVsoWr3pr7pudw+LYo1Ejz3\r\nJpiUPHqWcZ2PWrWs7PR1akYGuwdCBHYvCGTcZYFe/yu1AB8w5zYsl1eJR45g0u1DlXfx5BUAUzc4\r\nyJDjc48Ls62bn8t0EJ7+30sWwifqKuz2EHpsqp1j/iMlwzKJGjGE\r\n"; c[154] = "0NSYKTvBKKInwL9PJ/pWUWVX4gjF3igsA2qqQMsRew0lI1LcCB18eGCYk0AnyUCe99w5lWHGFUMM\r\neH6DZciAylWGeDn19JdzVOTevBWk3LIujI1GvsEB3oVqf2Zl9IZeDGCT4+bQKBWvgcXHjysZfnn/\r\n5z9Xz06qrPqac5LfS36fDcwnkrUYQWDsL2Ike32ALmOnkcDjNq1BoA==\r\n"; c[155] = "5ok+rYI4LCgGa2psGUN/fdkT2gQEToB9HRiFXQpe2YcQvEN2z7YlJCETx4jSWw06p5Y8tZcp08mo\r\nKNYwUJ40DvPpGlDG+wUpFhC4kkfo6vj6TrCj5yoWJi5D+qdgH2T0JeWM80cYN0bsOsetdaqNhDON\r\nlYXZ2lVYkyVS/wzw8K5xX87EWktwOwFq/yYhuWCYJ9GZL7QuDipJjEE=\r\n"; c[156] = "KHzTalU9wPSnIjh5g0eHi1HUaFufxJpXpjDe0N3wEKINqbgzhbj3Kf4qWjb2d1A+0Mlu9tYF/kA9\r\nONjda5jYfRgCHm5mUrjU0TAyT7EQFZ2u6WFK/sFHP++ycJQk8k7KLPUWA5OWScy1EO+dYF4d0r6K\r\n5O+7H/rpknxN6M9FlP8sH83DXK1Sd+UXL32D+4flF580FaZ5B3Tkx3dH\r\n"; c[157] = "RrJVxIKoDXtCviWMv/SXMO42Dn6UWOKDy2hh2ASXssT0e+G6m7F1230iJWlEN0wBR8p+BlTdBhQr\r\nn25098P3K16rBmZpzw/5dmesIJxhYPaM4GiaOgztFjuScTgkmV0Jl/vZ9eCXdEVNISeXkIixM4ps\r\nsTFuUV7PY/Upzdj55rDKGLr1eT7AFVSNP30PhL8zZs8MANqKBeKBBDvtww==\r\n"; c[158] = "sy4t5rFA75GRBE+Dqa9sQxjPluKt/JnEY54guHnKqccmx3HGiyJ0jUA+et4XO8Xg69wCA9xVxJZQ\r\nL73z80mVfIf43HIKOxgxT2IjG7EKMOD/qx6NnMTve4BryggLtbLQUeRfhriQeY7h65tD9ierhccX\r\noXDpGnmBn9m2BQP78y+Qhc4eIsa3LcxbQJUIwvURjFp/rgMD7lhOLboa/2Y=\r\n"; c[159] = "Zs/BfFoWImYau2dZLb7JneeTQp7sQ06yonEq0Ya4BNOJGy/5dGH42ozt0PpP2IZ/S58X7esVgc6j\r\nA1y3Bcxj3MPoDjQJSZHFEtR3G31T8eF5OpPVC4dw9s9clllM05tvcemssLdcd85UP/xBaDrmpAl8\r\nZDSc73zflK3nJw8e0HQFYntNnlZPFyyyBLHnLycb6Jlvq7F2OqrZR+FXZnL3\r\n"; c[160] = "hdeDJuRnmb8q9EYec8+futT/CvqhpqoUdtmG6E31RrYJDs96M5Wfng90IEqrncZe4rVYDocRZK23\r\ndvqtJaPhTUBXXh42IyMlUnro69KI+075FvYYwgVaUd10r7ExWM5Z7DCQ2x8Tm1meK2YCTPkF1VXX\r\nexl1UjYCnRQuQxppdophMwroJK8VqlJbFFslchTSBFuI7wgcdy+f/LHMbMsusQ==\r\n"; c[161] = "ClCCOv0mD9//LR0OisHfamxcTvmlwMLgAIQt3hbOjRPkXwEgaDzP0u6LN8BNwdOVw+LhrbzMI8zQ\r\nzHvo7mGPkQICeeim/x+xmGPQtmWnXxCWiL1uf/8eR5Wuy9Er8skTB8rG4/ubb2ssvCkubObPAkMS\r\nOgFnX9UtxnCN4+nMNV2vvn4xMTSvvQyYWewfnlNkflTyva1epE9RVW2RqRtJikY=\r\n"; c[162] = "Fs+AmFCnUr/imw8D0GpNidIP9qwW8yRAzmtqPS+vT6n5U4YFQcpgbznrYO4TPqkVF2oz1mpgLYIg\r\nx/u2XsrtljGX46LfY8OyUPaw4/da38QGngoIlS2cN01cgN3efSjMlnZFo1x8T9p0Nn1IgRgevOd5\r\nezVUL7WdY7eeiE1pXXcGBgDYn7NDQph0dC6HDlBiS95bDFcZ+6FYigE4WybpsOHL\r\n"; c[163] = "wgO4DdGZy9g13IuOhkJGJcToyLuCBVm9T/c8qY4NOheVU1NW2g8sPIo+RiEsSST8sx6+Jh/A/kaC\r\nxYvJ9CsgnBjZMMWRsd383HZAoJtkxwKvyoeXzzD+puFvqKQBEKrlBEwffXhLDoFQAW2ycYtBGztl\r\n0GsUtoOob2nv7ienx1xD6KNZNaxYx2ObRAYS/e8LS3pg5dku9MPBp1X12m8ZIXRAaw==\r\n"; c[164] = "EkXt02SaRUIjFmoLxyO6N+giL4iA4fY0Exao+mjgEfZ+Wv6w95GXHBI1xlYMVLkOcnu9nescvcXQ\r\nH0OrqL9uforEUTGTSg2ci67m4GrwAryMy+5eUo77Q5GpWKfsg8nDbD8a3gUI/9EE0sCNp7tMaKwo\r\nJ56cxhbG3TJYpqWTpq3/S3q76x+3ETL+zxh6EMh8MJPfWcIxlDS7evKqdPgS00KgUtk=\r\n"; c[165] = "OuBqx5LFJroRbDn41+4azFHlKgw6bMgbsRGaK9UnPvi5xfmV4SLQ2YzIhopGi1F57L6vKukaW0Xl\r\nFk/Ff5Td5IMC7U+kvXKlf8fGIIQ8FaHI0vbIX89OJlBqlICqftSNiVRxtaE+aCh0rBoDfgPwuC8q\r\nBC20I1O3ZLuKfeUVGkMOLEWeZLS6mmcn3cSERj9o/dEl8QYwQvhH+VG6YWF//yki1Vu8\r\n"; c[166] = "SO/vDsqZDdImOdH19sZI7FUVhlx1EI0XRr8ArTuAG5F8LDK76Bct2C7fXTUowilXnJWhQxvbGiul\r\nkUGSuVjVP12zac9bShRpr1L3ucde7n1f9y/NcHJCwdqTLq7RYygItQ4ppQGiP9jXf2Dn/qmVZZTh\r\n+SY3AZCIS+OVo2LAiYJHWnzzoX8Zt+dOYiOA/ZQKZieVJlc8ks+2xqYPD55eH0btZn5hzA==\r\n"; c[167] = "tZL/qACMO9SzmgJhWQMsbKgE5lPAEbxn3NR7504ilgArR8j7uv1KF46uQyjrkEnyBormYB/6nLGl\r\nHht62IQftMYf5gHpHFfTvukRKF8728yIYAAYHPQ/WjHzHdVSqUJqF2a8RE6SvvY+KSKWLMU3hjn1\r\nf6dqX599hYD7AnbPGTpFKDU5sLFOXbuynU1sPUhP+a4Hev9yNU6atLDo4CkX/Yq3FbpWVuQ=\r\n"; c[168] = "GRe7uF1wH5/71B3vmGF+pN3H9PKO1tLwsnb0D4/Pm7Pu5KAe4OfelkfFIBgyjuoZrpeEkGZnb+qf\r\n+Kn7Kt1hDwYr/Mb9ewuwOXsbIpLQMgfh0I5XsPrWocduVzn+u/cm3cr0Z11zsx0AZjTqvslACkDq\r\niquY41JhtGdc22RCvIYom2l+zzMIMyCPsHeCSB1MBu8EWK3iP7SD3dWttwzMg0xanoPDgk0U\r\n"; c[169] = "8BDFu+29lptlGSjcZe7ghWaUgIzbuUpM5XDFbtJVQPEd3bAE0cGRlQE9EhKXi5J/IskYNrQ357tB\r\nhA+UNDNXCibT2AZGpzWAcwE6dP+14FuRL5Gxqh/teuPYKr5IIn7M3SbgOychZzLI7HGCvVhBUiJB\r\nu8orI3WmAIVcUhAsMGHsFveck/ZCXQA+Uq/WVnW1VNs6hSmIhsAFc51qsmsQK07z2Wptx4rRjw==\r\n"; c[170] = "siPSXD4u36WYtTvvDzRlFPiuZMnRczrL3eA15955JDCc6/V2Cvu6m/HPO6JxogxO0aYTZ5tejYDO\r\nIZgBy40DgUZMqPJ2IpYjsmUbjjJU8u/OpwhMon525m3v0EYlvyj2Qp3pwFKDkvncK3aNjN3KaaX6\r\nHuIy6kyqsDl0BTEnB5iJyHLRBCkeznTK019u48Yfsrz2oGuZcWzNj5/vKMdxQPiyJ9EHyox8Ark=\r\n"; c[171] = "+/14PnFQVZ7BTHKUvkTtRrYS7WnPND5gZ5byMhUrDLkJa6UPBV7z0nrDMifEo/dQfUq3EjCiG6xG\r\nVhrUvAzgxqOQZTW1Y9p9M0KWW+E0XvCQppHFpuMqF1vYsF0OD6AMiE9JtGnWs3JcaWP/XBF/CvhQ\r\nlFGbHi3fbrD/haTEBnmpJWBgMdKribdbXHtBSFZ2MzCX2eDtxoDdRdEVGs4v/q8gVBS+WsnZ3TTF\r\n"; c[172] = "31I1ja+B+aopKkztGzJYvJEWAshyoAAV5yve4LnP0kdImUQaVETSuo5CDIYr7zM8MCD1eYPpLicm\r\nGnA+C927o9QGAVL3ctO/DCWhNinW7NmeYIM+o4diKBkDPjHmSWa+nq4nr+gOap4CtwL2wW2B5Yqt\r\n26pKgN9uAU5CmTL26hYFgMEOZfrkQ7XdYGy2CN8RJLmjeSFVVNBG/FTaK7tpuy0LQSkko6wczBYG\r\neg==\r\n"; c[173] = "XbRfDqGe3eeI1tHx8UnPneDB57N8VeSSzXzVCNSgxOEfd6d/un5CDxHG+m4w3tIbtSky4R2+zMF+\r\nS5cRvTOwZ/veegYtLKTxA0mVedWLFkfh/v4NgPJ+NEU+cylbSSZLAeBofDvoJwnYKujN2KFa8PGA\r\nxr3Y8ry3qdkS8Ob1ZiHYAmLvKS9sGb/vjTvRy+a4Q7kOepsm7PYisinKelBAvDnjli6/lOutGren\r\njX4=\r\n"; c[174] = "jGEj/AaBefac9uOcmGuO9nH+N+zMsC4qAe6ZUEMMIXdTGnSWl7Xt0/nKqyOj3ZH249HwkJ8bn5C+\r\n0bzOpQ1eA3PxEq6RfKMrjHJPJmTZXrSESTjfj3oNLU/CqqDOqd8znTgN6nvnUdCeStLMh9bmWF1+\r\n0G11nDwg6GQWWQ0zjVDTq5j7ocXcFOyUcu0cyl5YDcUP0i2mA2JullInU2uBte7nToeSGB3FJxKu\r\neBbv\r\n"; c[175] = "RAzNCxlP2S/8LfbGtlSDShox8cSgmJMOc2xPFs8egZVJiwlmnS3aBWKPRbbxkZiVVYlu4GNJNwbo\r\ncc6dgrl28HXAsYikE5wwoQ1MeOJWU3zzFiYENh7SLBQfjVPQHucctr8P6Rl7YL5wHc+aC+m92R3b\r\nnzm5rp1PeHm7uzy2iUUN0cgfbwJ4FrpXhVMTsAUpTbg1+037EWcGOuxir4dG2xBfgOwa+ejFHkw7\r\ny0LWRw==\r\n"; c[176] = "08hmZptBGKKqR6Qz9GNc2Wk1etgU/KogbiPQmAh5IXlTBc97DuEToL4Bb889nfObVQ/WelmiCS8w\r\nEjSBdmnlkkU7/b5UT3P4k1pB6ZxPH9Qldj5aazkA/yCb0kzDfJlcdFOh1eAcu5LvwTXOizmPwsDv\r\nJEnOkaDZrKESZshsHU2A6Mx6awk9/orf6iBlJHQIIH3l4o3b1gx2TNb/hUgdAlwtQDhvKO3skB0P\r\nS+rcWAw=\r\n"; c[177] = "0GhrgbSSHPLWtyS2mnSxrNAj/dyrFQcxIgPjT7+78SZ1ZTGc03vsmlZ4Z/bOO84E9yKblaI5dSHV\r\nXrx57L0kikL8tgKCsAkUNO3l/4zv5FfCrRTgGx4sFTFB1NNcLcwagkvFzde764DjYmj4YZhYsXSZ\r\nCVKi0uu5M8fpgGDZ9UMSFR008cbhaIoFLWSANqiNJYSvTQZhGWfLtIPGLN+gIOMcaKhx1b5vg6OY\r\nSz6ScAM/\r\n"; c[178] = "2VGiMV/f2hNZAjw3fdeHx/wRIVzeP018lZynzwSySG/zQBxyRmi3YmKVZmh3aJunuiqmvdt0kJ6l\r\nX7M8BajYHPCBkqJOx8oPJ/K1oADxVgnavZ69dKYrSy9/Pm6sHxjFrdSz9TelUK9sgoFTWS6GxgzW\r\nEqXRBDDpGUnsNbSEcWLPKVLNNoYAcltY98JZaNSZBXcpa9FeSN7sVU43q2IEcDx3ZkJzRJpl/lb7\r\nn+ivMwX/OQ==\r\n"; c[179] = "iMSCh1m5vct3C7LEn5wKRYtalzvG6pKahG19rTb6Z9q7+buDsML5yM6NqDvoVxt3Dv7KRwdS3xG/\r\nPyb7bJGvQ2a4FhRnTa4HvPvl3cpJdMgCCvsXeXXoML4pHzFlpP0bNsMoupmhQ0khAW51PAr4B165\r\nu1y5ULpruxE+dGx/HJUQyMfGhOSZ5jDKKxD5TNYQkDEY28Xqln6Fj8duzQLzMIgSoD8KGZKD8jm6\r\n/f8Vwvf43NE=\r\n"; c[180] = "hN4+x/sK9FRZn5llaw7/XDGwht3BcIxAFP4JoGqVQCw8c5IOlSqKEOViYss1mnvko6kVrc2iMEA8\r\nh8RssJ4dJBpFDZ/bkehCyhQmWpspZtAvRN59mj6nx0SBglYGccPyrn3e0uvvGJ5nYmjTA7gqB0Y+\r\nFFGAYwgAO345ipxTrMFsnJ8a913GzpobJdcHiw5hfqYK2iqo8STzVljaGMc5WSzP69vFDTHSS39Y\r\nSfbE890TPBgm\r\n"; } /* Here are the randomly generated byte[] arrays we generated to exercise commons-codec-1.3.jar */ private static void initBYTES() { byte[][] b = BYTES; b[0] = new byte[]{}; b[1] = new byte[]{-72}; b[2] = new byte[]{-49, -36}; b[3] = new byte[]{77, 15, -103}; b[4] = new byte[]{110, 24, -44, 96}; b[5] = new byte[]{-43, -61, -67, -75, -33}; b[6] = new byte[]{-80, -52, 71, -96, -105, -7}; b[7] = new byte[]{-115, 7, 15, -108, 59, 25, -49}; b[8] = new byte[]{76, 6, -113, -99, -11, -65, 9, -123}; b[9] = new byte[]{113, 116, -39, -69, 12, -41, 60, -29, 82}; b[10] = new byte[]{46, -39, -1, 101, 53, 120, 34, 52, -6, 56}; b[11] = new byte[]{-23, -8, 126, -115, -43, 55, -43, 35, -90, 90, -73}; b[12] = new byte[]{19, -2, 76, -96, 62, 42, 10, -16, -18, 77, -63, 64}; b[13] = new byte[]{-38, 127, 88, -55, -16, -116, -56, -59, -34, -103, -69, 108, -79}; b[14] = new byte[]{-88, 25, 26, -36, 26, -70, 87, 125, 71, -103, -55, -121, -114, 70}; b[15] = new byte[]{90, -4, -103, 123, -87, 16, -14, -100, -69, -101, 110, 110, 113, -84, 9}; b[16] = new byte[]{-95, -118, 113, 51, 46, -127, 74, -106, 87, -123, 90, 78, 71, -89, 87, -104}; b[63] = new byte[]{-55, -20, 69, 104, -46, -102, 63, -27, 100, 87, 1, 20, -65, 20, 23, 108, 45, 7, 72, 40, -65, -78, -77, -104, -19, -51, 55, -22, 84, -10, -27, -6, -20, -29, 24, -56, -66, -99, -75, -32, -111, -62, -125, -77, -117, -3, 118, 86, -36, -125, 30, -24, 32, -32, 72, -64, -102, 104, -113, 117, 121, 24, 12}; b[64] = new byte[]{-66, 74, -96, -98, -30, 119, -90, 92, 77, -74, -117, -34, -120, -62, 110, 96, -77, 122, -63, -108, 11, -91, -67, -59, -125, -113, 63, -52, 121, 29, 22, -32, -18, 114, -29, 10, 89, 84, 78, -2, 120, -123, 70, 2, -84, 22, -89, 49, -85, -91, 96, 11, 28, 16, 109, -29, -30, 63, -37, 17, -97, 28, -5, -62}; b[65] = new byte[]{96, 121, 44, -36, 96, -101, -38, -27, 69, -29, -74, 54, -76, 40, -98, -120, 49, -119, -13, -65, 81, -101, -105, 65, -123, 8, 80, -117, 54, 33, 125, 99, -88, -8, 26, -63, -37, -14, -66, 19, -68, 25, 89, 56, -99, -41, -119, 76, -92, -50, -76, -5, -112, -76, 55, -46, 77, 40, 7, 1, 17, 39, -86, 101, -110}; b[66] = new byte[]{-49, -50, 121, -42, 57, -112, -89, -12, 44, -9, -101, 112, -37, 110, -66, 28, 33, -42, -82, -30, -79, -4, -101, -33, 4, 39, -48, -26, -99, 31, 23, -66, -26, -111, 42, 105, -21, -95, 57, -25, 104, -92, -38, 12, -100, -84, 16, 108, 48, 47, -51, 111, 57, -64, -127, 54, 104, 51, 54, 113, 122, 23, -55, -62, -18, 61}; b[67] = new byte[]{86, -60, 118, -62, 26, -86, -2, -92, 38, -33, -115, -66, 76, -36, -11, -106, 3, -103, 50, -123, -101, -92, 44, -2, -110, 61, -77, 126, 90, -76, -97, 30, -46, -3, 23, -124, 84, -11, 9, 114, -88, 12, -75, 92, -21, -81, 97, 85, 64, -9, -63, 0, 126, 85, 70, 52, 126, -122, 76, 112, -65, -122, -20, -79, 9, -84, -15}; b[68] = new byte[]{-25, 25, -120, -89, -57, 84, 37, -100, -28, -118, -62, 36, -72, 67, -20, -100, -11, -17, -52, 55, -116, -93, -113, 42, 88, 87, -57, 34, 125, -102, -65, 120, -21, -26, -86, 25, 28, 43, 52, 45, -13, 68, -55, -22, 66, -34, -3, -84, 107, 73, -62, 83, 65, 101, -86, -55, -125, -55, 50, 57, -1, 104, -19, -25, 59, 11, -75, 93}; b[69] = new byte[]{-76, 97, 32, 94, 56, 37, 80, 31, 77, 108, 43, 98, 75, -49, 0, 122, -46, -19, 70, -88, 66, 2, 120, 115, 57, 66, -107, -126, -10, -55, 100, 122, -114, 3, -84, 124, -72, -22, 43, 3, 91, 119, 53, -58, -120, 3, 77, 25, -87, -77, -40, 0, -69, -72, 47, 50, 38, -30, 46, 37, 0, -65, 80, -126, 33, -1, 38, 14, -37}; b[70] = new byte[]{-128, 91, 113, 18, 22, 9, 106, 16, -26, 83, -105, 105, -71, -42, 44, -23, -108, -20, -88, 12, 126, -77, 104, -2, -45, -96, 52, -51, -20, -101, -35, 78, -25, -123, -111, 108, 110, 64, -125, -107, -37, 52, 17, -123, 40, -87, -22, -39, -87, -109, -26, -20, 94, -126, 12, -29, -125, -35, -43, 59, -99, -119, -98, -108, 77, 3, -57, 35, 14, -12}; b[71] = new byte[]{-113, -8, 127, -44, -100, -96, 96, 14, 91, -114, -37, 113, -51, 12, 107, -26, 0, 109, -126, 31, -128, 97, 90, 51, -124, 94, 22, -126, -9, 20, -2, 14, 61, -65, 72, 84, -53, -95, 93, -123, -10, 94, -64, 98, -66, 62, 27, 115, -113, -76, 90, 108, -114, 105, -37, 53, -14, -50, -7, 38, 45, 7, 69, -123, -46, 57, 82, 110, 14, -26, -52}; b[72] = new byte[]{-101, -23, 24, 84, 106, 35, 33, 30, 105, -127, -68, -5, -92, 98, 102, -38, 15, -73, -86, -87, 59, 126, 25, 119, 114, -116, 26, -39, -27, 107, -122, 72, -69, 90, -121, -14, -53, 9, -47, 123, 58, -109, -60, -23, 1, -127, 81, 115, -22, 114, -84, -14, -84, 105, 109, -74, -13, 0, -73, 45, 112, -9, -116, -78, -97, 93, -91, 117, 31, -71, 66, 107}; b[73] = new byte[]{-92, -10, -122, -100, -54, -12, 81, -119, -91, 118, 114, 85, -109, -15, 126, -35, 96, -119, 39, 90, -10, -94, -37, -61, -28, -94, 93, -73, 107, -75, 70, 116, -70, 47, 8, 71, -121, 2, -62, -87, -11, -68, 59, -12, 4, -125, -115, -42, 119, 18, -88, -104, 98, -1, 36, -51, -9, -74, 127, -63, -10, -109, 15, -96, -123, 52, 65, 49, -93, -85, 97, -111, -93}; b[74] = new byte[]{-104, -20, 115, 27, 44, -90, -23, 63, -63, -60, 37, 121, -99, 40, -120, 96, -55, 95, 1, 73, -126, 55, -72, 45, -17, -26, 83, 50, 13, 100, 119, -61, -19, -118, -71, 62, 36, 94, 93, -109, -59, 18, 109, 96, 110, -1, -42, 111, 54, 14, 89, -70, 34, 66, 120, 108, 31, 105, 90, 106, -91, -99, -54, -9, 36, -123, -20, 47, 59, 38, -5, -75, 69, 65}; b[75] = new byte[]{85, -126, -50, 32, 78, 3, -98, 28, 73, -97, 113, 74, 75, -3, -111, 28, 113, -40, 46, 86, 98, 25, 87, 85, -2, 78, 46, 5, -69, 64, 96, 117, 18, 78, -108, 115, 105, -90, 15, 24, -48, 21, -115, -45, 112, 109, 49, -56, -118, 25, -98, -70, 79, -7, 97, 5, 50, -16, -47, 108, -60, -118, 38, -8, -72, -69, 110, 117, -94, 6, -127, -54, 4, -13, -5}; b[76] = new byte[]{-19, -6, 12, -92, -99, 19, -110, 112, -102, -74, 53, 34, 75, 27, 103, -72, -92, -94, -49, -124, 47, -105, -8, -99, 89, -113, 84, 42, 36, -27, -114, -124, 7, 103, -32, -68, 109, -59, 44, 114, 114, 63, 109, -102, -11, -35, -18, -128, -65, 37, 33, -29, -77, 37, -91, -47, -81, -52, -119, -76, -26, -91, 29, 49, 101, -117, -95, -110, 78, 104, 102, 47, 14, 107, -21, 89}; b[77] = new byte[]{-113, 20, 18, 26, 33, 108, -7, -67, 83, 124, 78, 37, 13, 64, 15, 80, -14, 116, 73, 103, -108, -126, 93, 55, -84, -82, -102, -70, 39, -106, 37, -58, -85, 12, -127, -52, -9, -72, 6, 56, 115, 38, -56, 123, -99, 68, -54, -92, 102, 98, 36, -59, -124, 96, 98, 0, -126, 82, 15, -55, 121, 79, 117, 57, -112, -9, -76, -66, 20, -5, 3, 97, 74, 28, -80, 123, -49}; b[78] = new byte[]{80, 105, -121, -2, 9, 123, -73, 112, -28, -13, 77, 111, 70, 20, 67, 17, -72, 44, 125, 40, 109, 29, -99, 96, 101, 9, -8, 40, -42, 121, 66, -52, 55, 90, 33, -93, 91, 66, 38, 34, 117, 71, 107, -30, -46, 28, 28, -53, 82, 60, 2, -47, -99, -25, 92, -18, 34, -29, -32, -94, 41, -118, -128, -78, -109, -107, -120, 78, -106, -87, 85, 24, -15, -108, -107, -48, -24, 56}; b[79] = new byte[]{-63, -47, 40, 98, 98, 110, 70, 120, 54, -49, 98, 36, 2, 36, -96, 39, 80, -106, -39, 81, 59, 31, -70, 23, -91, -123, -124, 20, 83, -68, -100, 109, 27, 102, 126, -49, 30, 20, -4, 43, 40, 90, 59, 106, -30, 118, 95, 30, 80, 76, -84, -115, -83, 21, 92, 80, -14, 66, -92, -96, 102, 123, -35, 80, -86, -62, 25, -22, 86, 25, -106, -16, -45, -3, 27, 15, 11, 55, 2}; b[80] = new byte[]{-26, 70, 106, -126, -75, 27, -73, -22, -51, -28, 21, -128, 117, -41, -108, -74, 111, 83, 25, 62, 55, -67, -118, 65, -24, -9, -78, 67, 4, -14, -53, -43, 91, -81, 79, -108, -1, -124, 51, -53, 66, 48, -33, -76, 90, -37, -35, -57, -102, 73, -87, -127, 12, -18, 73, -59, 105, 112, -120, -123, 25, 115, -64, 21, 108, 19, -95, 31, -101, -94, -4, 46, -19, -91, -29, -117, -15, 103, 51, 9}; b[81] = new byte[]{19, -114, -69, 48, -55, -119, 110, 108, 47, -16, -23, -100, -39, 55, 92, -56, -54, -1, -33, 64, 124, -117, 53, -101, 127, -32, -128, -72, -101, 112, -21, -74, -11, -125, -37, 107, -124, 46, -89, -32, 102, 39, 94, 55, -106, -12, 54, 47, -103, 106, 8, 36, -4, 116, -50, -11, 63, 67, -24, 42, -65, 71, 45, 122, 13, -101, -57, -45, -10, -102, -72, 12, 12, 4, 91, -23, -24, 40, -62, -88, -15}; b[82] = new byte[]{86, -101, 124, -123, -122, -8, -113, 29, 69, -5, -76, 68, 95, -78, -70, -26, -2, -98, 59, -111, 117, 24, 56, 63, 43, -60, -107, 45, 96, -46, -89, 75, 43, -70, -106, 4, 66, 64, 85, 71, 25, -63, -11, -39, -95, 74, -113, 87, 30, -100, -8, 11, -54, 81, -105, -54, -4, -39, -4, 87, 102, -23, -90, 17, -2, 20, -40, -24, 116, 14, 42, 121, -82, 115, 109, 12, -65, -120, 38, -14, -4, -107}; b[121] = new byte[]{-123, -2, -67, -58, -65, 102, -76, 87, -8, 55, 120, -10, -72, 15, 76, -128, -78, -7, 103, 47, 120, 30, 59, -2, 85, 8, -67, -29, -30, -46, -13, -34, -10, 36, -104, 3, 28, 36, 14, -64, -2, 112, -123, -44, 36, 87, -28, -119, -91, 121, 34, -56, 113, -102, 74, -60, 56, 126, 23, -87, 63, 12, -18, 101, -63, 41, 96, 68, 126, 109, -23, -14, -42, 63, -116, -48, 116, -103, 123, 126, -116, 117, 18, 33, -107, 58, -89, -93, -18, 42, -79, 119, 36, 47, 64, -93, 94, -58, 36, 36, -109, 52, 52, 7, -50, 98, 49, -64, -70, -50, 70, -43, -72, 34, -11, 88, 102, -120, -57, -64, 48}; b[122] = new byte[]{-56, -84, -45, -121, -104, 79, -89, -33, -49, 5, -26, 109, -83, -107, -20, 20, 112, 17, -9, 44, 14, 51, 120, 81, 104, 16, -28, -128, 111, 68, -45, -36, 5, 91, -61, 25, 15, 76, 76, 25, -24, 28, -89, 68, 43, 76, -105, 15, -15, 6, 14, 105, -120, 83, 13, 88, -90, 62, -85, 13, 77, 83, -90, -115, -40, -28, -67, 47, -74, 90, 24, -55, 91, -119, -107, 57, 116, 60, 40, -128, -3, -41, 38, -127, -76, -6, 62, 13, 43, 75, -28, 99, 32, 114, -41, 15, -28, -54, 21, 127, 85, 105, -13, 15, -26, 98, -38, 31, -87, -71, 101, 124, 57, -71, 53, -10, 51, -121, 96, 59, -118, 54}; b[123] = new byte[]{114, -63, 102, -62, -16, -13, -96, -18, 8, 59, -84, -110, 12, 14, 1, -39, 94, -34, -104, 71, -83, 3, 0, -96, 59, -82, -77, -50, 87, -42, 111, 114, -125, -84, -9, -59, 101, -51, -55, -126, -66, 62, 118, 86, -108, -112, 66, 3, 29, -121, -117, 28, 68, -35, 78, -53, 22, 58, 93, -118, -84, -15, -63, 18, -59, 11, -92, 52, -47, -5, 115, -95, -70, -75, -37, -43, 10, -10, 54, -15, -30, 28, 91, -86, 79, 113, -98, 111, -95, 24, -61, 102, -91, 109, -12, -26, 95, 23, 33, -13, 102, -101, -106, -34, 22, 42, 94, 42, 61, -60, -98, -53, -98, 47, -22, -37, 2, -71, 75, -103, -50, -71, 45}; b[124] = new byte[]{-28, -119, -15, -68, -84, 41, -96, 37, 123, 16, -82, -4, 59, 53, 63, -76, -65, 127, 54, 98, -75, -32, -6, -16, -10, -45, -126, 3, 34, -66, -58, -107, 13, 45, -102, -30, -71, 81, 21, 118, 10, 104, 103, 78, 107, -106, 43, -97, 105, 64, -58, 28, 127, 29, 60, 7, -90, -16, 111, 67, 55, -11, 78, 62, 75, 65, -22, -11, -54, -75, -51, -92, 49, 72, 39, 49, 56, -103, -62, -1, -44, 85, -33, -79, -54, -87, -45, -16, -14, -60, 116, -44, 60, -84, 37, -79, -54, 32, -100, 45, -43, -59, 127, 79, -79, 112, 78, -22, 9, -52, 51, 11, -32, -5, -7, -60, 86, -6, 46, -99, -98, -106, 100, -53}; b[125] = new byte[]{112, 76, 123, -95, 59, 18, 29, 101, 5, 62, 63, 118, 114, -53, 93, -53, -100, 6, 109, 23, 49, 31, -27, 81, 88, -33, 36, 104, -44, -45, 8, -11, -86, 73, -55, 50, 83, -43, -28, -2, 56, -7, -2, 8, -3, 12, 92, 35, 126, -64, -110, -89, -83, 49, -70, -41, -8, -2, -79, 90, -98, 59, 112, -86, -44, 96, -23, -46, 75, 63, -126, 64, -126, -109, -118, -77, 0, -27, 30, 46, -107, -73, -68, -59, -1, 14, -57, -119, -45, 31, -38, -57, 109, -106, -54, -77, 107, 38, 102, 79, 97, -25, -18, 35, -88, -36, 33, 49, -50, -66, 89, -28, -105, -26, 48, 80, 23, -15, 31, 105, 121, 67, 120, -73, -107}; b[126] = new byte[]{1, -27, -34, -75, 86, -29, -5, -71, -90, 26, 32, -84, -36, 17, -108, 73, -112, -53, -106, -83, -88, 116, -53, 13, -16, -112, 7, 64, -50, -72, 10, 92, -68, -53, -104, -16, -17, -109, -23, 33, 42, 28, 89, 17, 69, 66, 105, -105, 96, -2, -36, -112, -87, -83, -70, 18, 47, 15, -81, 71, -75, -100, 70, -124, -44, 108, -105, 89, 117, -127, 124, -54, 22, 27, 22, -54, 71, 17, -76, 111, 59, 23, -53, 18, -43, 75, -1, -117, -92, 47, 26, 36, 72, 13, 81, 6, 24, -116, -42, -81, 52, 72, 33, 41, 1, 111, -36, 2, -60, -99, -121, 17, 39, -27, 121, 108, 43, -49, -15, -86, -81, 40, -24, 55, 110, -127}; b[127] = new byte[]{106, 61, 127, -13, -1, -108, -15, 83, -73, 15, 104, -128, -62, -12, 23, 103, -127, -12, 43, 11, 110, -52, 57, -72, 36, 32, -68, -5, 109, -100, 114, -87, 62, 83, 50, -81, -86, 49, -84, -13, -75, -25, -125, 7, -20, 49, -12, -92, 120, 101, 64, -117, -91, 65, -22, -41, -51, 37, 56, -40, 114, -42, -93, -19, 31, 29, -62, 29, -113, 33, -14, -46, -82, -10, -87, -121, 14, 48, 52, 29, -111, 18, 58, 101, -100, -6, 35, -96, -26, -3, 108, -43, 13, -75, 75, -35, 43, 118, -11, 108, 10, -50, 90, -24, 8, 68, -107, -117, -100, -55, 123, -37, 33, 7, 21, -67, 98, 5, -16, 102, -97, -69, -120, 107, -78, -109, -39}; b[128] = new byte[]{-110, 35, 46, 23, -3, 66, 49, 25, 96, -95, 47, -18, 44, -87, -11, -104, -42, 69, 100, -47, -55, 54, 68, 80, -98, 43, -50, -81, 56, -4, 29, 0, 26, -125, 12, -17, 77, 123, -20, 26, 2, 61, -123, 117, -9, -87, -89, -103, 47, -33, -15, -4, -22, -66, 99, -111, 122, 14, 31, -80, 94, -113, -76, -110, -98, -119, 106, 1, 99, -67, -76, -55, 113, 4, -88, -64, 92, -56, -62, 14, -1, 87, -37, 26, -98, -51, 13, 19, 65, 35, -93, 14, 65, 125, -110, -81, -118, 17, 72, -29, -85, 7, -120, 2, -27, -42, -84, -24, 94, -94, -48, -85, -18, 95, 100, 98, 5, 71, 44, -104, -13, 1, 86, -42, -24, -115, -69, -39}; b[129] = new byte[]{97, 121, -126, 90, 24, -115, -49, -113, -56, -121, 44, 80, 33, -120, -32, 54, -8, -41, -7, 124, 3, -120, -12, -46, 4, -58, -123, 16, -71, -71, 95, -58, 56, -110, 113, -111, -98, 65, 120, -1, 56, -79, -14, 95, 112, 28, 22, -2, -20, 40, 31, -82, -66, 58, -84, 94, -34, -120, -116, -38, 0, 82, -29, 46, 56, -34, -61, 46, -73, 118, -32, 73, -119, 86, -60, 90, 58, -123, 59, 71, -18, -23, 63, 98, 34, 59, -124, 104, 93, -84, 78, -102, 111, -71, -109, 79, 31, 31, 52, -68, -33, -121, 44, 9, -64, 86, 104, 5, 17, 44, 57, 0, -11, -42, -97, 94, 93, -117, 59, -18, 81, -11, 71, 119, -104, -84, 10, -90, -64}; b[130] = new byte[]{24, -105, -44, -96, 24, -81, 91, -101, -86, 14, -107, 49, 77, 23, -29, 25, 99, 88, 124, -35, -1, 117, 49, 109, 117, 26, -126, 32, 126, 75, -39, -51, 103, 89, 125, 29, -127, -115, -37, 107, 95, -97, 91, -10, 23, -44, -24, 121, 107, 14, 37, 11, -96, 72, -118, 36, -31, -116, -102, 21, -43, 90, -51, -98, 85, -13, 109, -59, 28, 51, 47, -122, -80, 53, 20, 7, -60, 30, -14, 80, 111, 125, -17, -19, -31, 25, -115, 60, 29, 33, 86, 10, -46, -13, -39, -19, 110, -27, 52, 74, -64, -90, 91, 15, -67, 14, -93, 55, -98, 39, 79, 121, -80, 13, 40, 68, 98, -125, 92, -39, 76, 16, 74, -126, -107, 95, -20, 115, -59, 8}; b[131] = new byte[]{121, 55, -85, 54, -50, -35, 58, -94, 64, -60, 12, 92, 49, 4, 103, 80, 55, 54, 112, 24, -10, -57, 72, -44, -42, 13, 67, -36, 111, -101, -37, 105, 3, -49, -78, 65, -52, -20, -65, -101, 24, 70, 92, 4, 55, -41, 125, 37, 106, -11, -116, -124, -119, -110, 6, 68, 94, 83, -20, -12, 3, 93, -60, 97, 83, 20, -65, -45, -59, -52, 62, -8, -20, -96, -81, -98, -49, -110, 10, -114, 118, 96, -47, -63, -45, -49, 122, 111, -119, 120, -18, -81, 33, -69, -56, -20, 15, 94, -45, 103, 107, -106, 88, -104, 82, -31, -61, 103, 72, 77, 99, 120, -50, -115, -95, 113, -118, -67, -1, 116, -53, 23, -13, -62, -25, 13, 97, -50, 17, 117, -92}; b[132] = new byte[]{-107, -70, -58, -78, 54, -13, 19, -99, -75, -85, -53, 115, 84, 117, 123, -67, -60, -49, 114, 21, 39, -52, -113, -44, 125, -28, 118, 71, -25, 38, 57, -83, -67, 98, 88, -49, 88, -72, 109, -11, 108, 118, 38, -72, -30, 42, -2, 14, 127, -103, -41, 123, -71, 47, -122, 47, -117, 97, 75, -123, 86, -88, 26, -88, -127, 97, 11, -13, -53, 110, -93, -123, -119, 61, -107, 101, -59, -24, -83, 58, 26, 69, 63, 66, 46, 42, -107, -27, -66, -89, 28, -33, -45, -57, 62, -110, 35, -77, 34, 15, 120, 103, -109, -70, 108, 13, -72, 37, 60, -22, 62, -54, -38, -100, -10, -63, 71, -113, -75, 36, 71, 86, 92, -75, 8, -16, 21, -116, 9, -114, 92, 95}; b[133] = new byte[]{-103, 12, 0, 63, 54, 51, 127, 28, -3, 21, 113, 34, 103, -93, 60, -69, 90, 13, -36, 66, 91, 21, -119, -115, 85, -6, 102, -6, 61, 3, -86, 5, 62, 56, -14, 56, 81, 17, -63, 34, -79, 120, -58, -9, 76, -68, 3, -25, -47, 107, -102, -83, -76, 50, -3, -107, 77, -47, -30, -117, -19, 46, 10, -36, -53, -38, -97, 71, -27, 3, 6, -103, 116, -113, -98, -28, 122, 100, 127, 19, -88, 25, 58, 124, 14, 78, 68, 21, 53, -29, -103, -97, -20, -8, 106, 39, 120, -15, 16, 16, 99, 85, 60, -67, 86, 98, -128, -6, -59, 122, -128, 2, -13, 11, 42, -36, -85, 21, -54, 104, -120, 100, -67, 120, 48, 101, -79, -112, -48, -52, -4, -13, -2}; b[134] = new byte[]{-36, 110, -99, -41, 101, 24, -30, 94, 86, -20, -39, -16, -48, 18, -12, 30, 117, 98, 86, 15, 82, 116, 75, -117, 50, -89, -103, -61, 45, 17, -108, -108, 127, 98, -41, 32, 119, -7, -120, -60, -117, -105, 92, 9, 70, -122, -8, 104, 95, -91, -36, -40, 17, -108, -19, 26, 83, -117, 88, -40, 43, 48, 60, -21, 43, -91, -46, 63, 122, 117, -73, 4, -32, -21, 107, 63, -39, 84, 4, -103, 92, 99, -41, -106, -49, -97, 93, -68, -70, -118, -57, 11, 119, 112, 67, -127, -62, -77, -33, -21, -45, 7, -72, -122, -74, -25, -89, -84, -36, 3, -126, -95, -73, -62, -15, 20, 18, 113, 109, 15, 67, 68, 20, 107, 85, 71, 7, -9, -105, 74, -59, 83, 73, 104}; b[135] = new byte[]{3, 24, 43, 100, -92, -59, -109, -110, 111, 44, 45, -61, 4, 0, -121, -62, -99, -70, -24, 92, 74, 35, -4, -89, -12, 95, -75, -75, -119, 51, 47, -98, -47, 86, -50, 71, 8, -106, 18, -29, -75, 110, 27, 68, -12, 19, 108, 42, -52, 122, -100, 44, -93, -48, 49, -107, -108, -18, -10, -47, -93, 35, 6, 52, -67, -39, -75, -95, -24, 102, -92, -22, 114, -81, 74, 90, -45, -125, 11, -29, -89, 18, -12, -110, -17, -19, 79, -31, 41, -112, 14, -20, -117, -40, -62, 127, 120, -112, 1, 36, -93, 92, -69, 82, -65, 46, 77, 27, -72, 6, -114, -48, 91, -41, -24, -31, -127, 112, -4, -18, -41, -25, 111, -3, -103, 48, -72, -28, 74, -45, -70, -111, -97, 26, -112}; b[136] = new byte[]{106, -39, 6, -14, 93, -108, -4, -39, -26, -5, 50, -18, -17, 56, -34, -98, -73, -36, 1, 84, 9, 49, 74, -121, -118, 97, 89, -35, -60, 31, 105, 74, 120, -85, 42, -59, -97, 85, 34, -63, -99, -9, -113, -82, -107, -73, -83, -34, 85, -92, -1, 21, 124, 126, 46, 81, 39, -80, 121, -6, 1, 51, -63, 50, -99, -30, 17, -118, 1, 37, -116, -115, -90, 60, -1, -51, 19, -95, 5, -73, 51, -99, 0, 12, 117, 101, 19, 115, 34, -120, -98, -7, -58, -33, 30, -124, -58, 0, 87, -89, 42, -97, -57, 26, 127, 62, 111, 27, -53, -78, -27, 73, 68, -7, 48, -95, -35, 114, -17, -109, 17, -11, 23, 70, -119, 2, -81, 104, -113, -98, -34, -51, 98, -61, 67, 124}; b[137] = new byte[]{117, -56, -108, -42, 100, -121, 25, -64, 113, 56, 5, 65, -128, -100, 123, -28, -98, -125, 105, 7, 65, 101, -12, -56, -51, 13, 56, 90, 25, 36, 117, 19, 46, -92, -26, 86, 74, 123, -11, -9, 24, 115, -14, 24, -114, -7, -103, -37, 6, -48, -55, -72, -18, 107, 30, -59, 6, -52, 127, -29, 97, -89, 31, 103, 32, -112, -9, 110, 43, -95, 27, -28, -121, 116, -11, -53, 27, 11, -85, 118, -101, 100, -107, 2, 15, -47, -40, -100, -12, -60, 45, 88, 111, -41, -25, 4, 23, -122, -88, 59, 123, -58, 58, -19, -123, -91, -14, -44, -97, -108, 19, 119, 67, -24, -50, -62, 42, 114, -90, 85, 7, 101, 121, -20, 30, -61, -115, -8, -77, 81, -19, -61, -15, -121, -7, 85, -54}; b[138] = new byte[]{118, 4, 117, 60, -10, -100, 6, -5, 72, 44, 25, -96, -33, 123, 61, 41, 107, 110, 115, -82, -25, 118, 29, -21, 8, 118, 127, -108, -125, 123, -80, 67, 96, 108, 90, -119, 67, 46, 67, 11, 117, -56, 120, 116, -43, -18, -123, -99, -6, -46, 80, 105, 124, 104, 11, -67, 127, 73, 78, -47, -49, -93, -126, -108, 3, 10, 92, -74, -52, -49, -59, 58, 68, -8, -86, -97, 115, 59, 49, 16, -112, 112, 55, -51, -116, 14, 92, 8, -39, 39, 93, 63, 68, -121, 63, -56, 100, 95, -5, -107, -59, -85, -61, 16, 74, 98, 110, 1, -9, -55, 79, -110, -106, 109, 71, 100, 7, -99, -40, -112, -34, -9, -89, -51, 106, -49, -48, -2, 114, -37, -71, -111, 121, -95, 110, 104, -97, -66}; b[139] = new byte[]{-43, 15, 43, 126, -99, 71, -72, 107, 49, -70, -76, -32, 24, -58, -92, -58, 62, 82, -64, -47, 123, 18, 44, 87, -59, 83, -25, 124, 96, 3, 88, 55, 50, -126, 30, 66, -44, 19, 23, -86, 34, -11, 2, -27, 87, 57, 81, 78, -79, -84, -99, 124, -75, -122, 11, -62, -101, -121, -14, 98, 47, -95, -2, -41, 105, 88, -84, -47, -108, 79, -36, -119, 68, -116, -47, 14, 46, 23, -54, 83, 39, -83, -116, 1, -73, 0, -119, -114, -127, -46, -117, -121, -79, -49, -110, -74, -118, 30, 120, -70, -43, 64, -69, 53, -39, -125, -87, -89, 115, -40, -98, 119, -7, -115, 70, 56, -3, 119, 97, -59, 15, -103, -81, -45, 15, -22, 76, -33, -42, 23, 17, 38, -74, -26, 76, -2, 115, 12, 106}; b[140] = new byte[]{-61, 77, 83, -100, -13, -1, 23, 117, 103, -117, 119, -63, 117, 93, -10, 6, 118, -37, -32, -99, 69, 113, -74, -124, -7, 121, -8, -30, 122, 57, -70, 14, -5, 83, -63, 82, -42, 4, -90, -36, -70, -119, -13, 36, -14, 93, -37, -77, -105, -101, -10, 119, 0, 68, 127, 56, -124, 125, 59, -78, -86, 7, -117, 46, -64, -104, 76, 24, -41, -103, -125, -120, 29, 10, 44, 18, 94, -125, -56, 9, 39, -69, -123, -54, -25, 103, -112, 91, -31, 94, -77, -41, -110, -77, 99, 106, -8, 110, 26, 105, 30, 50, -30, 87, -98, 20, -39, -126, -95, -97, 65, 66, 96, 0, 102, -67, 11, 22, 74, -89, -66, -90, -118, -104, 21, 96, 114, 12, 79, -77, -65, -4, 73, 1, -25, -90, -85, -38, 83, -90}; b[141] = new byte[]{57, -4, -56, 23, 127, 19, -89, -104, 53, 91, -105, -107, 110, -71, 43, 49, -19, 12, -101, -73, -76, -64, 22, 32, -26, 21, 111, 46, -103, -1, -28, -59, -71, 56, 87, 38, 68, 59, -127, -89, 94, 90, -55, 16, 103, 39, 91, 1, 35, -35, -2, 8, -39, 116, 47, 3, -4, 67, 76, -3, 33, 113, 99, 76, 68, 121, -128, 118, 117, 41, -15, -68, 53, 95, -88, 105, -62, -115, 27, -74, -104, -83, -75, 31, -74, 68, -117, -2, -125, -33, 68, -45, -34, -49, -91, 52, 22, -27, -96, -67, 90, -41, 80, 30, -100, -64, -92, -42, -65, 6, -3, 42, -128, -5, -77, -96, 6, 97, 23, 71, -25, 70, 96, 37, -48, 103, -120, 80, -5, 116, -86, 14, 66, 114, 127, 16, 43, -109, 81, 114, 62}; b[142] = new byte[]{-30, 26, 23, -46, -56, -22, -106, 68, -119, 61, 74, -70, -37, -72, -119, -112, -42, 17, 110, -48, -2, 87, 106, -124, -84, 43, -109, -118, 70, -98, 68, 49, 25, -67, 81, -42, -65, 55, 111, -62, 62, 22, -41, 28, 73, -113, 63, -78, 28, 3, 122, -49, 97, 35, 9, 104, -99, 113, 43, 21, -127, 55, -93, 67, 86, -57, -14, -28, -13, 38, 8, 127, -50, -83, -14, 25, 68, -84, 38, -126, 86, -83, -25, 42, -58, -56, 30, -15, -79, 1, -114, 73, -66, -87, 67, -68, 27, 121, 0, -100, 46, -123, 50, 50, 118, 53, -124, 30, 93, -2, -114, 43, -93, -96, -78, -84, -119, -62, 81, -49, 79, 32, 38, -77, 111, -56, -95, -124, -63, -30, 33, 42, -128, -127, 70, -1, 103, -51, 16, -111, 8, 106}; b[143] = new byte[]{51, -9, 114, -41, -116, 77, 109, -109, 17, 124, 120, -118, 40, 87, 102, 15, -13, -85, 16, 31, -68, 49, -20, 107, 68, -17, 38, 50, 29, 34, -28, -70, -51, 3, -107, -108, -76, -75, -35, -63, 71, -64, -54, -58, 38, 106, 95, 120, 49, 42, 13, 37, -8, 38, -64, 96, -88, -88, -36, 37, 89, -112, 86, -42, 74, 80, 104, -9, 106, -78, -71, -10, 114, -9, 58, 37, -58, 86, -12, 89, 78, -57, 78, -61, 17, 18, 70, 109, -98, -91, -22, -121, -37, -51, -107, -96, 23, -20, -97, -6, 27, -45, -22, 57, -55, -67, 112, 85, 9, 52, -9, -107, -13, -73, -86, -114, 37, 120, -37, -124, 39, 11, 46, 83, -89, -85, 92, 96, -73, 10, 30, 119, -72, -5, 70, 34, -73, 67, 82, -105, 23, -21, -11}; b[144] = new byte[]{26, 2, -21, -38, 23, 119, -100, -82, -72, 33, -101, -12, 38, 75, 10, 1, 63, -14, 36, -44, 55, -15, -84, -82, 91, 32, 103, 88, -72, -41, 108, 73, -109, -45, -113, 20, 14, -102, 108, -82, -71, -49, -22, 24, -92, 70, -114, 111, -39, 57, 71, 26, 16, -10, 117, -52, 6, -12, -46, -54, -36, -8, 124, 34, -126, 40, -11, 103, -10, -67, -107, -127, 7, -28, -116, 35, -47, 105, -127, -100, 65, 88, -79, 35, -64, 118, -50, 90, -63, -38, 17, 3, 21, -79, 7, -28, -33, -63, 22, 64, -3, 5, -81, -91, 114, 48, -87, 68, 65, -6, 108, 70, 75, -126, -90, -99, 74, -58, -57, 26, -60, -82, -32, -28, 24, 23, 82, 86, -12, 107, 108, 116, 23, -32, -67, -124, 64, 116, 57, 83, -20, -113, -126, 77}; b[145] = new byte[]{91, -39, 74, 112, -80, -22, 52, 100, 0, 27, -5, 10, 64, -42, -111, -103, -29, -108, -104, -78, 123, 25, -61, 13, -88, 22, -122, 103, -82, 125, 70, 120, -21, -23, 20, -21, 126, 121, -92, -89, -106, 125, -103, -32, 11, -97, 5, -24, 30, 51, -29, -51, 36, 3, 38, 117, 88, -79, -113, -79, -56, -55, -18, 62, 9, 122, -128, -59, 64, -124, 9, -66, 94, -102, -40, 86, -101, 39, 123, -117, -19, -5, -70, 35, 82, -90, -81, 84, -16, 106, 47, 46, 93, -74, 120, 105, -42, -89, -36, -100, 8, -107, -27, -58, 97, 29, 117, -5, 53, -68, 100, 80, -20, -23, -74, 49, 6, 9, 8, -25, -123, 33, -8, -84, -10, -39, -74, 10, 8, 88, 79, 25, -23, -70, 5, -34, 95, -19, -124, -71, -59, 95, -32, 34, -119}; b[146] = new byte[]{-119, -126, -25, -26, 31, 101, 34, 16, -1, -57, -39, -88, 104, -12, 103, 77, 126, -90, 36, 66, 74, 78, 24, 56, 89, 124, 82, -20, -118, -47, -37, 54, -27, 31, 110, -82, 58, 66, 13, -49, 71, 73, 53, 50, 85, 122, -37, 52, 100, -42, 3, -98, -55, -45, -20, -99, -94, 35, 118, 58, -123, 53, 86, 60, 106, 24, 83, -113, 73, -36, 29, -117, -124, 36, 68, -77, 64, -39, 67, 112, -69, -45, -51, 5, -74, 35, -100, 124, 118, -33, 4, -77, 103, -48, 60, -126, 43, 82, -34, 0, 46, -40, 7, -10, -51, 118, 44, -95, 46, -95, -4, 124, -87, 126, -45, -30, -95, -120, -16, -56, 80, 18, 88, -39, -18, -56, 109, -108, 127, -10, -35, 44, -60, -106, -56, 95, 30, -100, 70, -14, 57, 1, 119, -79, -41, 106}; b[147] = new byte[]{74, 84, 73, 17, -50, -25, -91, 53, 47, 66, -81, 18, -128, 22, 10, -103, 86, 63, -33, 1, -40, -89, 104, 44, 15, 22, -97, 55, -14, 75, 82, -31, 42, 18, 57, -106, 50, -43, -69, 127, 16, 18, -117, -25, -113, 95, -120, 38, 36, -102, -117, -124, 62, 109, -8, 6, 113, -120, 44, 24, 43, 114, -9, 113, -21, -119, -57, -124, -30, -87, 88, 9, -49, -57, 122, -79, -50, -33, -127, 101, -27, -70, 29, 74, -8, 23, 6, 61, -74, 123, -8, 42, -72, 86, -56, 26, -20, -111, 1, 85, -23, 47, -120, 70, 121, 2, 30, 26, -92, -38, -4, 70, 64, 123, -96, -61, -108, 84, -15, -79, 69, -52, -78, 105, 81, 56, -52, 21, -66, -79, -64, 58, 115, 92, -94, -4, 116, 23, 117, -44, 61, -83, 108, -117, 82, -59, 104}; b[148] = new byte[]{0, 9, 91, 25, 30, -98, -112, -77, -77, -57, -120, 105, -87, -108, -44, -87, 85, 16, -48, 82, -10, 8, 90, 96, 8, -61, -87, -24, 43, -82, 83, 57, 18, -99, 101, -23, 82, 59, -50, -119, 32, -28, 52, -8, 40, 76, -8, 41, -126, 104, 55, -71, -117, -52, -79, 126, 55, -102, 67, -58, 80, 96, -67, 107, 0, -45, -123, 124, -122, 66, 30, -82, -35, 103, -42, -74, 104, 98, 61, 26, -105, -98, 49, 94, -109, -31, 15, 119, 66, -40, 94, -101, 59, -42, 122, 39, -24, 47, 102, -18, 117, 37, 96, -43, -77, 4, -99, 88, -50, -68, -42, -114, 80, 121, 44, -77, -63, 55, -58, -20, 100, 110, -111, 109, -42, 100, 96, -52, 73, -12, -98, 109, 107, -9, 55, -46, 111, 48, 12, 51, 110, 78, 109, 39, 16, 77, 25, 85}; b[149] = new byte[]{-99, 101, -101, 6, 28, -50, 110, -84, 4, 22, 31, -45, -120, -92, 68, 114, -54, -117, 97, -76, 99, 33, -58, 95, -108, -102, 104, -105, 94, -116, -117, -122, 3, 47, -95, 25, -82, 45, -74, -87, 25, -45, -126, -80, 109, 33, -113, -121, -119, -28, -40, 90, -30, -38, 9, 41, 63, 7, -43, -100, 98, -24, -24, 75, -94, 91, -27, -36, -96, -36, 84, 58, 92, 95, 91, 97, -93, 80, 27, 29, -80, -16, 49, -32, -57, 73, 54, -98, -95, -1, -47, 77, 108, 1, 77, 36, 126, -35, -10, 104, 61, -88, -82, -96, -116, 34, -102, -37, 59, 85, -119, 34, -35, -102, -71, 25, -17, 112, -28, -59, -96, -26, -79, -9, 110, -89, 2, 76, 111, 71, 121, -21, 21, 80, -34, -68, 88, -61, 110, -24, 41, 88, 121, 6, -62, 39, 58, 27, -70}; b[150] = new byte[]{88, -39, 53, 70, 125, -86, -76, 111, -96, -109, 64, 4, 123, 10, -32, -93, -26, -111, 108, -38, -58, -32, 40, 16, -92, -28, 124, 82, -114, -36, -38, 109, -105, 65, -113, 12, 84, 59, -72, -71, 16, 58, -81, 54, 6, 25, -40, 42, 77, -62, 2, 42, 76, -67, 50, -15, -34, 37, -29, 86, 84, 5, -50, -58, 96, 56, 17, -43, -48, -37, 18, 45, 20, -105, 80, -73, 16, 109, -25, -89, 26, 119, -47, 65, 93, 123, 51, -37, 92, -107, -80, -6, -7, 119, -114, 119, 105, -72, -69, 79, 117, -33, 29, 84, -45, -95, -23, 34, 58, 92, 64, 38, -49, -101, -91, -85, 125, 112, 84, 91, 33, -47, -32, -124, -17, 112, 115, -5, -100, -96, 10, -45, -25, 123, -23, 98, -55, -14, 121, 89, -26, 100, 109, -113, 95, -113, 37, 94, -109, 82}; b[151] = new byte[]{-63, 89, -94, 59, -87, -99, 127, 102, -102, -122, -78, 101, 114, 105, -63, 15, 68, 26, -25, -52, -68, 2, -4, -41, -76, -98, 120, 34, 108, 96, 60, -77, -25, -48, -48, -112, 34, -71, -108, -57, 51, 89, 53, 51, -125, 19, 117, -114, -22, 70, 76, 16, 38, -109, -3, 17, 42, 79, 115, -24, 56, 26, 125, -78, -48, -121, 8, 83, 87, 56, -50, -3, -17, -46, 120, -32, 45, 89, 69, 77, 50, 60, 40, 90, -45, 73, 16, 100, 17, 121, 18, 103, 11, -118, -43, 66, -49, 93, 45, 63, -56, 6, -43, -8, -120, -68, -56, -16, -91, -35, -103, 76, -26, -104, -29, -8, 56, 53, -30, 71, 46, 50, 79, -106, 93, 28, -26, 118, -57, -18, 126, 47, -5, 82, 62, -60, 110, -1, -18, 78, -58, -24, -33, 44, -89, 109, 105, 110, 10, 83, 96}; b[152] = new byte[]{58, -120, -107, 102, -117, 8, -8, -95, -76, 17, -108, -18, -7, 106, 71, -18, 66, -120, 75, 25, -114, -41, 52, 88, 105, 35, -52, 4, -59, -76, 3, 36, 98, 11, 104, -103, 84, 73, 14, 50, 34, -89, -41, 101, -49, -88, -128, -46, 91, -7, 21, 3, -97, 28, -66, -1, -14, -79, 48, 51, 40, -76, -18, -17, -59, 40, -6, -59, 92, 37, -19, -64, -76, -73, 96, 120, 15, 111, 57, 17, 68, 45, 51, -8, -65, -48, -48, -2, 96, 38, 122, 23, -73, 55, -52, 100, -7, 84, -53, 99, -84, 71, 90, 46, -97, -30, 63, 92, 76, 53, -65, 4, 60, -119, 72, 52, 88, -45, 74, 24, -96, 121, 111, -98, 56, 7, -93, -128, -121, 6, -115, 44, 48, 104, 23, -36, 44, 28, -100, -83, -95, -92, -63, 85, -76, 31, -9, -88, -7, 122, -65, 108}; b[153] = new byte[]{-9, -74, 85, -79, 54, 48, 15, -59, 107, -128, -35, 69, 56, -124, 89, -14, 57, -68, 56, -56, 43, -60, 109, -24, -43, -94, 104, 98, -45, -43, 89, 122, 125, 114, 56, -27, -127, 122, -109, 49, -107, 108, -95, 106, -9, -90, -66, -23, -71, -36, 62, 45, -118, 53, 18, 60, -9, 38, -104, -108, 60, 122, -106, 113, -99, -113, 90, -75, -84, -20, -12, 117, 106, 70, 6, -69, 7, 66, 4, 118, 47, 8, 100, -36, 101, -127, 94, -1, 43, -75, 0, 31, 48, -25, 54, 44, -105, 87, -119, 71, -114, 96, -46, -19, 67, -107, 119, -15, -28, 21, 0, 83, 55, 56, -56, -112, -29, 115, -113, 11, -77, -83, -101, -97, -53, 116, 16, -98, -2, -33, 75, 22, -62, 39, -22, 42, -20, -10, 16, 122, 108, -86, -99, 99, -2, 35, 37, -61, 50, -119, 26, 49, -124}; b[154] = new byte[]{-48, -44, -104, 41, 59, -63, 40, -94, 39, -64, -65, 79, 39, -6, 86, 81, 101, 87, -30, 8, -59, -34, 40, 44, 3, 106, -86, 64, -53, 17, 123, 13, 37, 35, 82, -36, 8, 29, 124, 120, 96, -104, -109, 64, 39, -55, 64, -98, -9, -36, 57, -107, 97, -58, 21, 67, 12, 120, 126, -125, 101, -56, -128, -54, 85, -122, 120, 57, -11, -12, -105, 115, 84, -28, -34, -68, 21, -92, -36, -78, 46, -116, -115, 70, -66, -63, 1, -34, -123, 106, 127, 102, 101, -12, -122, 94, 12, 96, -109, -29, -26, -48, 40, 21, -81, -127, -59, -57, -113, 43, 25, 126, 121, -1, -25, 63, 87, -49, 78, -86, -84, -6, -102, 115, -110, -33, 75, 126, -97, 13, -52, 39, -110, -75, 24, 65, 96, -20, 47, 98, 36, 123, 125, -128, 46, 99, -89, -111, -64, -29, 54, -83, 65, -96}; b[155] = new byte[]{-26, -119, 62, -83, -126, 56, 44, 40, 6, 107, 106, 108, 25, 67, 127, 125, -39, 19, -38, 4, 4, 78, -128, 125, 29, 24, -123, 93, 10, 94, -39, -121, 16, -68, 67, 118, -49, -74, 37, 36, 33, 19, -57, -120, -46, 91, 13, 58, -89, -106, 60, -75, -105, 41, -45, -55, -88, 40, -42, 48, 80, -98, 52, 14, -13, -23, 26, 80, -58, -5, 5, 41, 22, 16, -72, -110, 71, -24, -22, -8, -6, 78, -80, -93, -25, 42, 22, 38, 46, 67, -6, -89, 96, 31, 100, -12, 37, -27, -116, -13, 71, 24, 55, 70, -20, 58, -57, -83, 117, -86, -115, -124, 51, -115, -107, -123, -39, -38, 85, 88, -109, 37, 82, -1, 12, -16, -16, -82, 113, 95, -50, -60, 90, 75, 112, 59, 1, 106, -1, 38, 33, -71, 96, -104, 39, -47, -103, 47, -76, 46, 14, 42, 73, -116, 65}; b[156] = new byte[]{40, 124, -45, 106, 85, 61, -64, -12, -89, 34, 56, 121, -125, 71, -121, -117, 81, -44, 104, 91, -97, -60, -102, 87, -90, 48, -34, -48, -35, -16, 16, -94, 13, -87, -72, 51, -123, -72, -9, 41, -2, 42, 90, 54, -10, 119, 80, 62, -48, -55, 110, -10, -42, 5, -2, 64, 61, 56, -40, -35, 107, -104, -40, 125, 24, 2, 30, 110, 102, 82, -72, -44, -47, 48, 50, 79, -79, 16, 21, -99, -82, -23, 97, 74, -2, -63, 71, 63, -17, -78, 112, -108, 36, -14, 78, -54, 44, -11, 22, 3, -109, -106, 73, -52, -75, 16, -17, -99, 96, 94, 29, -46, -66, -118, -28, -17, -69, 31, -6, -23, -110, 124, 77, -24, -49, 69, -108, -1, 44, 31, -51, -61, 92, -83, 82, 119, -27, 23, 47, 125, -125, -5, -121, -27, 23, -97, 52, 21, -90, 121, 7, 116, -28, -57, 119, 71}; b[157] = new byte[]{70, -78, 85, -60, -126, -88, 13, 123, 66, -66, 37, -116, -65, -12, -105, 48, -18, 54, 14, 126, -108, 88, -30, -125, -53, 104, 97, -40, 4, -105, -78, -60, -12, 123, -31, -70, -101, -79, 117, -37, 125, 34, 37, 105, 68, 55, 76, 1, 71, -54, 126, 6, 84, -35, 6, 20, 43, -97, 110, 116, -9, -61, -9, 43, 94, -85, 6, 102, 105, -49, 15, -7, 118, 103, -84, 32, -100, 97, 96, -10, -116, -32, 104, -102, 58, 12, -19, 22, 59, -110, 113, 56, 36, -103, 93, 9, -105, -5, -39, -11, -32, -105, 116, 69, 77, 33, 39, -105, -112, -120, -79, 51, -118, 108, -79, 49, 110, 81, 94, -49, 99, -11, 41, -51, -40, -7, -26, -80, -54, 24, -70, -11, 121, 62, -64, 21, 84, -115, 63, 125, 15, -124, -65, 51, 102, -49, 12, 0, -38, -118, 5, -30, -127, 4, 59, -19, -61}; b[158] = new byte[]{-77, 46, 45, -26, -79, 64, -17, -111, -111, 4, 79, -125, -87, -81, 108, 67, 24, -49, -106, -30, -83, -4, -103, -60, 99, -98, 32, -72, 121, -54, -87, -57, 38, -57, 113, -58, -117, 34, 116, -115, 64, 62, 122, -34, 23, 59, -59, -32, -21, -36, 2, 3, -36, 85, -60, -106, 80, 47, -67, -13, -13, 73, -107, 124, -121, -8, -36, 114, 10, 59, 24, 49, 79, 98, 35, 27, -79, 10, 48, -32, -1, -85, 30, -115, -100, -60, -17, 123, -128, 107, -54, 8, 11, -75, -78, -48, 81, -28, 95, -122, -72, -112, 121, -114, -31, -21, -101, 67, -10, 39, -85, -123, -57, 23, -95, 112, -23, 26, 121, -127, -97, -39, -74, 5, 3, -5, -13, 47, -112, -123, -50, 30, 34, -58, -73, 45, -52, 91, 64, -107, 8, -62, -11, 17, -116, 90, 127, -82, 3, 3, -18, 88, 78, 45, -70, 26, -1, 102}; b[159] = new byte[]{102, -49, -63, 124, 90, 22, 34, 102, 26, -69, 103, 89, 45, -66, -55, -99, -25, -109, 66, -98, -20, 67, 78, -78, -94, 113, 42, -47, -122, -72, 4, -45, -119, 27, 47, -7, 116, 97, -8, -38, -116, -19, -48, -6, 79, -40, -122, 127, 75, -97, 23, -19, -21, 21, -127, -50, -93, 3, 92, -73, 5, -52, 99, -36, -61, -24, 14, 52, 9, 73, -111, -59, 18, -44, 119, 27, 125, 83, -15, -31, 121, 58, -109, -43, 11, -121, 112, -10, -49, 92, -106, 89, 76, -45, -101, 111, 113, -23, -84, -80, -73, 92, 119, -50, 84, 63, -4, 65, 104, 58, -26, -92, 9, 124, 100, 52, -100, -17, 124, -33, -108, -83, -25, 39, 15, 30, -48, 116, 5, 98, 123, 77, -98, 86, 79, 23, 44, -78, 4, -79, -25, 47, 39, 27, -24, -103, 111, -85, -79, 118, 58, -86, -39, 71, -31, 87, 102, 114, -9}; b[160] = new byte[]{-123, -41, -125, 38, -28, 103, -103, -65, 42, -12, 70, 30, 115, -49, -97, -70, -44, -1, 10, -6, -95, -90, -86, 20, 118, -39, -122, -24, 77, -11, 70, -74, 9, 14, -49, 122, 51, -107, -97, -98, 15, 116, 32, 74, -85, -99, -58, 94, -30, -75, 88, 14, -121, 17, 100, -83, -73, 118, -6, -83, 37, -93, -31, 77, 64, 87, 94, 30, 54, 35, 35, 37, 82, 122, -24, -21, -46, -120, -5, 78, -7, 22, -10, 24, -62, 5, 90, 81, -35, 116, -81, -79, 49, 88, -50, 89, -20, 48, -112, -37, 31, 19, -101, 89, -98, 43, 102, 2, 76, -7, 5, -43, 85, -41, 123, 25, 117, 82, 54, 2, -99, 20, 46, 67, 26, 105, 118, -118, 97, 51, 10, -24, 36, -81, 21, -86, 82, 91, 20, 91, 37, 114, 20, -46, 4, 91, -120, -17, 8, 28, 119, 47, -97, -4, -79, -52, 108, -53, 46, -79}; b[161] = new byte[]{10, 80, -126, 58, -3, 38, 15, -33, -1, 45, 29, 14, -118, -63, -33, 106, 108, 92, 78, -7, -91, -64, -62, -32, 0, -124, 45, -34, 22, -50, -115, 19, -28, 95, 1, 32, 104, 60, -49, -46, -18, -117, 55, -64, 77, -63, -45, -107, -61, -30, -31, -83, -68, -52, 35, -52, -48, -52, 123, -24, -18, 97, -113, -111, 2, 2, 121, -24, -90, -1, 31, -79, -104, 99, -48, -74, 101, -89, 95, 16, -106, -120, -67, 110, 127, -1, 30, 71, -107, -82, -53, -47, 43, -14, -55, 19, 7, -54, -58, -29, -5, -101, 111, 107, 44, -68, 41, 46, 108, -26, -49, 2, 67, 18, 58, 1, 103, 95, -43, 45, -58, 112, -115, -29, -23, -52, 53, 93, -81, -66, 126, 49, 49, 52, -81, -67, 12, -104, 89, -20, 31, -98, 83, 100, 126, 84, -14, -67, -83, 94, -92, 79, 81, 85, 109, -111, -87, 27, 73, -118, 70}; b[162] = new byte[]{22, -49, -128, -104, 80, -89, 82, -65, -30, -101, 15, 3, -48, 106, 77, -119, -46, 15, -10, -84, 22, -13, 36, 64, -50, 107, 106, 61, 47, -81, 79, -87, -7, 83, -122, 5, 65, -54, 96, 111, 57, -21, 96, -18, 19, 62, -87, 21, 23, 106, 51, -42, 106, 96, 45, -126, 32, -57, -5, -74, 94, -54, -19, -106, 49, -105, -29, -94, -33, 99, -61, -78, 80, -10, -80, -29, -9, 90, -33, -60, 6, -98, 10, 8, -107, 45, -100, 55, 77, 92, -128, -35, -34, 125, 40, -52, -106, 118, 69, -93, 92, 124, 79, -38, 116, 54, 125, 72, -127, 24, 30, -68, -25, 121, 123, 53, 84, 47, -75, -99, 99, -73, -98, -120, 77, 105, 93, 119, 6, 6, 0, -40, -97, -77, 67, 66, -104, 116, 116, 46, -121, 14, 80, 98, 75, -34, 91, 12, 87, 25, -5, -95, 88, -118, 1, 56, 91, 38, -23, -80, -31, -53}; b[163] = new byte[]{-62, 3, -72, 13, -47, -103, -53, -40, 53, -36, -117, -114, -122, 66, 70, 37, -60, -24, -56, -69, -126, 5, 89, -67, 79, -9, 60, -87, -114, 13, 58, 23, -107, 83, 83, 86, -38, 15, 44, 60, -118, 62, 70, 33, 44, 73, 36, -4, -77, 30, -66, 38, 31, -64, -2, 70, -126, -59, -117, -55, -12, 43, 32, -100, 24, -39, 48, -59, -111, -79, -35, -4, -36, 118, 64, -96, -101, 100, -57, 2, -81, -54, -121, -105, -49, 48, -2, -90, -31, 111, -88, -92, 1, 16, -86, -27, 4, 76, 31, 125, 120, 75, 14, -127, 80, 1, 109, -78, 113, -117, 65, 27, 59, 101, -48, 107, 20, -74, -125, -88, 111, 105, -17, -18, 39, -89, -57, 92, 67, -24, -93, 89, 53, -84, 88, -57, 99, -101, 68, 6, 18, -3, -17, 11, 75, 122, 96, -27, -39, 46, -12, -61, -63, -89, 85, -11, -38, 111, 25, 33, 116, 64, 107}; b[164] = new byte[]{18, 69, -19, -45, 100, -102, 69, 66, 35, 22, 106, 11, -57, 35, -70, 55, -24, 34, 47, -120, -128, -31, -10, 52, 19, 22, -88, -6, 104, -32, 17, -10, 126, 90, -2, -80, -9, -111, -105, 28, 18, 53, -58, 86, 12, 84, -71, 14, 114, 123, -67, -99, -21, 28, -67, -59, -48, 31, 67, -85, -88, -65, 110, 126, -118, -60, 81, 49, -109, 74, 13, -100, -117, -82, -26, -32, 106, -16, 2, -68, -116, -53, -18, 94, 82, -114, -5, 67, -111, -87, 88, -89, -20, -125, -55, -61, 108, 63, 26, -34, 5, 8, -1, -47, 4, -46, -64, -115, -89, -69, 76, 104, -84, 40, 39, -98, -100, -58, 22, -58, -35, 50, 88, -90, -91, -109, -90, -83, -1, 75, 122, -69, -21, 31, -73, 17, 50, -2, -49, 24, 122, 16, -56, 124, 48, -109, -33, 89, -62, 49, -108, 52, -69, 122, -14, -86, 116, -8, 18, -45, 66, -96, 82, -39}; b[165] = new byte[]{58, -32, 106, -57, -110, -59, 38, -70, 17, 108, 57, -8, -41, -18, 26, -52, 81, -27, 42, 12, 58, 108, -56, 27, -79, 17, -102, 43, -43, 39, 62, -8, -71, -59, -7, -107, -31, 34, -48, -39, -116, -56, -122, -118, 70, -117, 81, 121, -20, -66, -81, 42, -23, 26, 91, 69, -27, 22, 79, -59, 127, -108, -35, -28, -125, 2, -19, 79, -92, -67, 114, -91, 127, -57, -58, 32, -124, 60, 21, -95, -56, -46, -10, -56, 95, -49, 78, 38, 80, 106, -108, -128, -86, 126, -44, -115, -119, 84, 113, -75, -95, 62, 104, 40, 116, -84, 26, 3, 126, 3, -16, -72, 47, 42, 4, 45, -76, 35, 83, -73, 100, -69, -118, 125, -27, 21, 26, 67, 14, 44, 69, -98, 100, -76, -70, -102, 103, 39, -35, -60, -124, 70, 63, 104, -3, -47, 37, -15, 6, 48, 66, -8, 71, -7, 81, -70, 97, 97, 127, -1, 41, 34, -43, 91, -68}; b[166] = new byte[]{72, -17, -17, 14, -54, -103, 13, -46, 38, 57, -47, -11, -10, -58, 72, -20, 85, 21, -122, 92, 117, 16, -115, 23, 70, -65, 0, -83, 59, -128, 27, -111, 124, 44, 50, -69, -24, 23, 45, -40, 46, -33, 93, 53, 40, -62, 41, 87, -100, -107, -95, 67, 27, -37, 26, 43, -91, -111, 65, -110, -71, 88, -43, 63, 93, -77, 105, -49, 91, 74, 20, 105, -81, 82, -9, -71, -57, 94, -18, 125, 95, -9, 47, -51, 112, 114, 66, -63, -38, -109, 46, -82, -47, 99, 40, 8, -75, 14, 41, -91, 1, -94, 63, -40, -41, 127, 96, -25, -2, -87, -107, 101, -108, -31, -7, 38, 55, 1, -112, -120, 75, -29, -107, -93, 98, -64, -119, -126, 71, 90, 124, -13, -95, 127, 25, -73, -25, 78, 98, 35, -128, -3, -108, 10, 102, 39, -107, 38, 87, 60, -110, -49, -74, -58, -90, 15, 15, -98, 94, 31, 70, -19, 102, 126, 97, -52}; b[167] = new byte[]{-75, -110, -1, -88, 0, -116, 59, -44, -77, -102, 2, 97, 89, 3, 44, 108, -88, 4, -26, 83, -64, 17, -68, 103, -36, -44, 123, -25, 78, 34, -106, 0, 43, 71, -56, -5, -70, -3, 74, 23, -114, -82, 67, 40, -21, -112, 73, -14, 6, -118, -26, 96, 31, -6, -100, -79, -91, 30, 27, 122, -40, -124, 31, -76, -58, 31, -26, 1, -23, 28, 87, -45, -66, -23, 17, 40, 95, 59, -37, -52, -120, 96, 0, 24, 28, -12, 63, 90, 49, -13, 29, -43, 82, -87, 66, 106, 23, 102, -68, 68, 78, -110, -66, -10, 62, 41, 34, -106, 44, -59, 55, -122, 57, -11, 127, -89, 106, 95, -97, 125, -123, -128, -5, 2, 118, -49, 25, 58, 69, 40, 53, 57, -80, -79, 78, 93, -69, -78, -99, 77, 108, 61, 72, 79, -7, -82, 7, 122, -1, 114, 53, 78, -102, -76, -80, -24, -32, 41, 23, -3, -118, -73, 21, -70, 86, 86, -28}; b[168] = new byte[]{25, 23, -69, -72, 93, 112, 31, -97, -5, -44, 29, -17, -104, 97, 126, -92, -35, -57, -12, -14, -114, -42, -46, -16, -78, 118, -12, 15, -113, -49, -101, -77, -18, -28, -96, 30, -32, -25, -34, -106, 71, -59, 32, 24, 50, -114, -22, 25, -82, -105, -124, -112, 102, 103, 111, -22, -97, -8, -87, -5, 42, -35, 97, 15, 6, 43, -4, -58, -3, 123, 11, -80, 57, 123, 27, 34, -110, -48, 50, 7, -31, -48, -114, 87, -80, -6, -42, -95, -57, 110, 87, 57, -2, -69, -9, 38, -35, -54, -12, 103, 93, 115, -77, 29, 0, 102, 52, -22, -66, -55, 64, 10, 64, -22, -118, -85, -104, -29, 82, 97, -76, 103, 92, -37, 100, 66, -68, -122, 40, -101, 105, 126, -49, 51, 8, 51, 32, -113, -80, 119, -126, 72, 29, 76, 6, -17, 4, 88, -83, -30, 63, -76, -125, -35, -43, -83, -73, 12, -52, -125, 76, 90, -98, -125, -61, -126, 77, 20}; b[169] = new byte[]{-16, 16, -59, -69, -19, -67, -106, -101, 101, 25, 40, -36, 101, -18, -32, -123, 102, -108, -128, -116, -37, -71, 74, 76, -27, 112, -59, 110, -46, 85, 64, -15, 29, -35, -80, 4, -47, -63, -111, -107, 1, 61, 18, 18, -105, -117, -110, 127, 34, -55, 24, 54, -76, 55, -25, -69, 65, -124, 15, -108, 52, 51, 87, 10, 38, -45, -40, 6, 70, -89, 53, -128, 115, 1, 58, 116, -1, -75, -32, 91, -111, 47, -111, -79, -86, 31, -19, 122, -29, -40, 42, -66, 72, 34, 126, -52, -35, 38, -32, 59, 39, 33, 103, 50, -56, -20, 113, -126, -67, 88, 65, 82, 34, 65, -69, -54, 43, 35, 117, -90, 0, -123, 92, 82, 16, 44, 48, 97, -20, 22, -9, -100, -109, -10, 66, 93, 0, 62, 82, -81, -42, 86, 117, -75, 84, -37, 58, -123, 41, -120, -122, -64, 5, 115, -99, 106, -78, 107, 16, 43, 78, -13, -39, 106, 109, -57, -118, -47, -113}; b[170] = new byte[]{-78, 35, -46, 92, 62, 46, -33, -91, -104, -75, 59, -17, 15, 52, 101, 20, -8, -82, 100, -55, -47, 115, 58, -53, -35, -32, 53, -25, -34, 121, 36, 48, -100, -21, -11, 118, 10, -5, -70, -101, -15, -49, 59, -94, 113, -94, 12, 78, -47, -90, 19, 103, -101, 94, -115, -128, -50, 33, -104, 1, -53, -115, 3, -127, 70, 76, -88, -14, 118, 34, -106, 35, -78, 101, 27, -114, 50, 84, -14, -17, -50, -89, 8, 76, -94, 126, 118, -26, 109, -17, -48, 70, 37, -65, 40, -10, 66, -99, -23, -64, 82, -125, -110, -7, -36, 43, 118, -115, -116, -35, -54, 105, -91, -6, 30, -30, 50, -22, 76, -86, -80, 57, 116, 5, 49, 39, 7, -104, -119, -56, 114, -47, 4, 41, 30, -50, 116, -54, -45, 95, 110, -29, -58, 31, -78, -68, -10, -96, 107, -103, 113, 108, -51, -113, -97, -17, 40, -57, 113, 64, -8, -78, 39, -47, 7, -54, -116, 124, 2, -71}; b[171] = new byte[]{-5, -3, 120, 62, 113, 80, 85, -98, -63, 76, 114, -108, -66, 68, -19, 70, -74, 18, -19, 105, -49, 52, 62, 96, 103, -106, -14, 50, 21, 43, 12, -71, 9, 107, -91, 15, 5, 94, -13, -46, 122, -61, 50, 39, -60, -93, -9, 80, 125, 74, -73, 18, 48, -94, 27, -84, 70, 86, 26, -44, -68, 12, -32, -58, -93, -112, 101, 53, -75, 99, -38, 125, 51, 66, -106, 91, -31, 52, 94, -16, -112, -90, -111, -59, -90, -29, 42, 23, 91, -40, -80, 93, 14, 15, -96, 12, -120, 79, 73, -76, 105, -42, -77, 114, 92, 105, 99, -1, 92, 17, 127, 10, -8, 80, -108, 81, -101, 30, 45, -33, 110, -80, -1, -123, -92, -60, 6, 121, -87, 37, 96, 96, 49, -46, -85, -119, -73, 91, 92, 123, 65, 72, 86, 118, 51, 48, -105, -39, -32, -19, -58, -128, -35, 69, -47, 21, 26, -50, 47, -2, -81, 32, 84, 20, -66, 90, -55, -39, -35, 52, -59}; b[172] = new byte[]{-33, 82, 53, -115, -81, -127, -7, -86, 41, 42, 76, -19, 27, 50, 88, -68, -111, 22, 2, -56, 114, -96, 0, 21, -25, 43, -34, -32, -71, -49, -46, 71, 72, -103, 68, 26, 84, 68, -46, -70, -114, 66, 12, -122, 43, -17, 51, 60, 48, 32, -11, 121, -125, -23, 46, 39, 38, 26, 112, 62, 11, -35, -69, -93, -44, 6, 1, 82, -9, 114, -45, -65, 12, 37, -95, 54, 41, -42, -20, -39, -98, 96, -125, 62, -93, -121, 98, 40, 25, 3, 62, 49, -26, 73, 102, -66, -98, -82, 39, -81, -24, 14, 106, -98, 2, -73, 2, -10, -63, 109, -127, -27, -118, -83, -37, -86, 74, -128, -33, 110, 1, 78, 66, -103, 50, -10, -22, 22, 5, -128, -63, 14, 101, -6, -28, 67, -75, -35, 96, 108, -74, 8, -33, 17, 36, -71, -93, 121, 33, 85, 84, -48, 70, -4, 84, -38, 43, -69, 105, -69, 45, 11, 65, 41, 36, -93, -84, 28, -52, 22, 6, 122}; b[173] = new byte[]{93, -76, 95, 14, -95, -98, -35, -25, -120, -42, -47, -15, -15, 73, -49, -99, -32, -63, -25, -77, 124, 85, -28, -110, -51, 124, -43, 8, -44, -96, -60, -31, 31, 119, -89, 127, -70, 126, 66, 15, 17, -58, -6, 110, 48, -34, -46, 27, -75, 41, 50, -31, 29, -66, -52, -63, 126, 75, -105, 17, -67, 51, -80, 103, -5, -34, 122, 6, 45, 44, -92, -15, 3, 73, -107, 121, -43, -117, 22, 71, -31, -2, -2, 13, -128, -14, 126, 52, 69, 62, 115, 41, 91, 73, 38, 75, 1, -32, 104, 124, 59, -24, 39, 9, -40, 42, -24, -51, -40, -95, 90, -16, -15, -128, -58, -67, -40, -14, -68, -73, -87, -39, 18, -16, -26, -11, 102, 33, -40, 2, 98, -17, 41, 47, 108, 25, -65, -17, -115, 59, -47, -53, -26, -72, 67, -71, 14, 122, -101, 38, -20, -10, 34, -78, 41, -54, 122, 80, 64, -68, 57, -29, -106, 46, -65, -108, -21, -83, 26, -73, -89, -115, 126}; b[174] = new byte[]{-116, 97, 35, -4, 6, -127, 121, -10, -100, -10, -29, -100, -104, 107, -114, -10, 113, -2, 55, -20, -52, -80, 46, 42, 1, -18, -103, 80, 67, 12, 33, 119, 83, 26, 116, -106, -105, -75, -19, -45, -7, -54, -85, 35, -93, -35, -111, -10, -29, -47, -16, -112, -97, 27, -97, -112, -66, -47, -68, -50, -91, 13, 94, 3, 115, -15, 18, -82, -111, 124, -93, 43, -116, 114, 79, 38, 100, -39, 94, -76, -124, 73, 56, -33, -113, 122, 13, 45, 79, -62, -86, -96, -50, -87, -33, 51, -99, 56, 13, -22, 123, -25, 81, -48, -98, 74, -46, -52, -121, -42, -26, 88, 93, 126, -48, 109, 117, -100, 60, 32, -24, 100, 22, 89, 13, 51, -115, 80, -45, -85, -104, -5, -95, -59, -36, 20, -20, -108, 114, -19, 28, -54, 94, 88, 13, -59, 15, -46, 45, -90, 3, 98, 110, -106, 82, 39, 83, 107, -127, -75, -18, -25, 78, -121, -110, 24, 29, -59, 39, 18, -82, 120, 22, -17}; b[175] = new byte[]{68, 12, -51, 11, 25, 79, -39, 47, -4, 45, -10, -58, -74, 84, -125, 74, 26, 49, -15, -60, -96, -104, -109, 14, 115, 108, 79, 22, -49, 30, -127, -107, 73, -117, 9, 102, -99, 45, -38, 5, 98, -113, 69, -74, -15, -111, -104, -107, 85, -119, 110, -32, 99, 73, 55, 6, -24, 113, -50, -99, -126, -71, 118, -16, 117, -64, -79, -120, -92, 19, -100, 48, -95, 13, 76, 120, -30, 86, 83, 124, -13, 22, 38, 4, 54, 30, -46, 44, 20, 31, -115, 83, -48, 30, -25, 28, -74, -65, 15, -23, 25, 123, 96, -66, 112, 29, -49, -102, 11, -23, -67, -39, 29, -37, -97, 57, -71, -82, -99, 79, 120, 121, -69, -69, 60, -74, -119, 69, 13, -47, -56, 31, 111, 2, 120, 22, -70, 87, -123, 83, 19, -80, 5, 41, 77, -72, 53, -5, 77, -5, 17, 103, 6, 58, -20, 98, -81, -121, 70, -37, 16, 95, -128, -20, 26, -7, -24, -59, 30, 76, 59, -53, 66, -42, 71}; b[176] = new byte[]{-45, -56, 102, 102, -101, 65, 24, -94, -86, 71, -92, 51, -12, 99, 92, -39, 105, 53, 122, -40, 20, -4, -86, 32, 110, 35, -48, -104, 8, 121, 33, 121, 83, 5, -49, 123, 14, -31, 19, -96, -66, 1, 111, -49, 61, -99, -13, -101, 85, 15, -42, 122, 89, -94, 9, 47, 48, 18, 52, -127, 118, 105, -27, -110, 69, 59, -3, -66, 84, 79, 115, -8, -109, 90, 65, -23, -100, 79, 31, -44, 37, 118, 62, 90, 107, 57, 0, -1, 32, -101, -46, 76, -61, 124, -103, 92, 116, 83, -95, -43, -32, 28, -69, -110, -17, -63, 53, -50, -117, 57, -113, -62, -64, -17, 36, 73, -50, -111, -96, -39, -84, -95, 18, 102, -56, 108, 29, 77, -128, -24, -52, 122, 107, 9, 61, -2, -118, -33, -22, 32, 101, 36, 116, 8, 32, 125, -27, -30, -115, -37, -42, 12, 118, 76, -42, -1, -123, 72, 29, 2, 92, 45, 64, 56, 111, 40, -19, -20, -112, 29, 15, 75, -22, -36, 88, 12}; b[177] = new byte[]{-48, 104, 107, -127, -76, -110, 28, -14, -42, -73, 36, -74, -102, 116, -79, -84, -48, 35, -3, -36, -85, 21, 7, 49, 34, 3, -29, 79, -65, -69, -15, 38, 117, 101, 49, -100, -45, 123, -20, -102, 86, 120, 103, -10, -50, 59, -50, 4, -9, 34, -101, -107, -94, 57, 117, 33, -43, 94, -68, 121, -20, -67, 36, -118, 66, -4, -74, 2, -126, -80, 9, 20, 52, -19, -27, -1, -116, -17, -28, 87, -62, -83, 20, -32, 27, 30, 44, 21, 49, 65, -44, -45, 92, 45, -52, 26, -126, 75, -59, -51, -41, -69, -21, -128, -29, 98, 104, -8, 97, -104, 88, -79, 116, -103, 9, 82, -94, -46, -21, -71, 51, -57, -23, -128, 96, -39, -11, 67, 18, 21, 29, 52, -15, -58, -31, 104, -118, 5, 45, 100, -128, 54, -88, -115, 37, -124, -81, 77, 6, 97, 25, 103, -53, -76, -125, -58, 44, -33, -96, 32, -29, 28, 104, -88, 113, -43, -66, 111, -125, -93, -104, 75, 62, -110, 112, 3, 63}; b[178] = new byte[]{-39, 81, -94, 49, 95, -33, -38, 19, 89, 2, 60, 55, 125, -41, -121, -57, -4, 17, 33, 92, -34, 63, 77, 124, -107, -100, -89, -49, 4, -78, 72, 111, -13, 64, 28, 114, 70, 104, -73, 98, 98, -107, 102, 104, 119, 104, -101, -89, -70, 42, -90, -67, -37, 116, -112, -98, -91, 95, -77, 60, 5, -88, -40, 28, -16, -127, -110, -94, 78, -57, -54, 15, 39, -14, -75, -96, 0, -15, 86, 9, -38, -67, -98, -67, 116, -90, 43, 75, 47, 127, 62, 110, -84, 31, 24, -59, -83, -44, -77, -11, 55, -91, 80, -81, 108, -126, -127, 83, 89, 46, -122, -58, 12, -42, 18, -91, -47, 4, 48, -23, 25, 73, -20, 53, -76, -124, 113, 98, -49, 41, 82, -51, 54, -122, 0, 114, 91, 88, -9, -62, 89, 104, -44, -103, 5, 119, 41, 107, -47, 94, 72, -34, -20, 85, 78, 55, -85, 98, 4, 112, 60, 119, 102, 66, 115, 68, -102, 101, -2, 86, -5, -97, -24, -81, 51, 5, -1, 57}; b[179] = new byte[]{-120, -60, -126, -121, 89, -71, -67, -53, 119, 11, -78, -60, -97, -100, 10, 69, -117, 90, -105, 59, -58, -22, -110, -102, -124, 109, 125, -83, 54, -6, 103, -38, -69, -7, -69, -125, -80, -62, -7, -56, -50, -115, -88, 59, -24, 87, 27, 119, 14, -2, -54, 71, 7, 82, -33, 17, -65, 63, 38, -5, 108, -111, -81, 67, 102, -72, 22, 20, 103, 77, -82, 7, -68, -5, -27, -35, -54, 73, 116, -56, 2, 10, -5, 23, 121, 117, -24, 48, -66, 41, 31, 49, 101, -92, -3, 27, 54, -61, 40, -70, -103, -95, 67, 73, 33, 1, 110, 117, 60, 10, -8, 7, 94, -71, -69, 92, -71, 80, -70, 107, -69, 17, 62, 116, 108, 127, 28, -107, 16, -56, -57, -58, -124, -28, -103, -26, 48, -54, 43, 16, -7, 76, -42, 16, -112, 49, 24, -37, -59, -22, -106, 126, -123, -113, -57, 110, -51, 2, -13, 48, -120, 18, -96, 63, 10, 25, -110, -125, -14, 57, -70, -3, -1, 21, -62, -9, -8, -36, -47}; b[180] = new byte[]{-124, -34, 62, -57, -5, 10, -12, 84, 89, -97, -103, 101, 107, 14, -1, 92, 49, -80, -122, -35, -63, 112, -116, 64, 20, -2, 9, -96, 106, -107, 64, 44, 60, 115, -110, 14, -107, 42, -118, 16, -27, 98, 98, -53, 53, -102, 123, -28, -93, -87, 21, -83, -51, -94, 48, 64, 60, -121, -60, 108, -80, -98, 29, 36, 26, 69, 13, -97, -37, -111, -24, 66, -54, 20, 38, 90, -101, 41, 102, -48, 47, 68, -34, 125, -102, 62, -89, -57, 68, -127, -126, 86, 6, 113, -61, -14, -82, 125, -34, -46, -21, -17, 24, -98, 103, 98, 104, -45, 3, -72, 42, 7, 70, 62, 20, 81, -128, 99, 8, 0, 59, 126, 57, -118, -100, 83, -84, -63, 108, -100, -97, 26, -9, 93, -58, -50, -102, 27, 37, -41, 7, -117, 14, 97, 126, -90, 10, -38, 42, -88, -15, 36, -13, 86, 88, -38, 24, -57, 57, 89, 44, -49, -21, -37, -59, 13, 49, -46, 75, 127, 88, 73, -10, -60, -13, -35, 19, 60, 24, 38}; } /** * Tests to make sure Base64's implementation of the org.apache.commons.codec.Encoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */ public void testEncoder() throws EncoderException { Encoder enc = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64, (byte[]) enc.encode(binary)); assertTrue("Encoder test-" + i, b); } } } /** * Tests to make sure Base64's implementation of the org.apache.commons.codec.Decoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws DecoderException problem */ public void testDecoder() throws DecoderException { Decoder dec = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(binary, (byte[]) dec.decode(base64)); assertTrue("Decoder test-" + i, b); } } } /** * Tests to make sure Base64's implementation of the org.apache.commons.codec.BinaryEncoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */ public void testBinaryEncoder() throws EncoderException { BinaryEncoder enc = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64, enc.encode(binary)); assertTrue("BinaryEncoder test-" + i, b); } } } /** * Tests to make sure Base64's implementation of the org.apache.commons.codec.BinaryDecoder * interface is behaving identical to commons-codec-1.3.jar. * * @throws DecoderException problem */ public void testBinaryDecoder() throws DecoderException { BinaryDecoder dec = new Base64(); for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(binary, dec.decode(base64)); assertTrue("BinaryDecoder test-" + i, b); } } } /** * Tests to make sure Base64's implementation of Base64.encodeBase64() * static method is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */ public void testStaticEncode() throws EncoderException { for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64, Base64.encodeBase64(binary)); assertTrue("static Base64.encodeBase64() test-" + i, b); } } } /** * Tests to make sure Base64's implementation of Base64.decodeBase64() * static method is behaving identical to commons-codec-1.3.jar. * * @throws DecoderException problem */ public void testStaticDecode() throws DecoderException { for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64 = utf8(STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(binary, Base64.decodeBase64(base64)); assertTrue("static Base64.decodeBase64() test-" + i, b); } } } /** * Tests to make sure Base64's implementation of Base64.encodeBase64Chunked() * static method is behaving identical to commons-codec-1.3.jar. * * @throws EncoderException problem */ public void testStaticEncodeChunked() throws EncoderException { for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64Chunked = utf8(CHUNKED_STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(base64Chunked, Base64.encodeBase64Chunked(binary)); assertTrue("static Base64.encodeBase64Chunked() test-" + i, b); } } } /** * Tests to make sure Base64's implementation of Base64.decodeBase64() * static method is behaving identical to commons-codec-1.3.jar when * supplied with chunked input. * * @throws DecoderException problem */ public void testStaticDecodeChunked() throws DecoderException { for (int i = 0; i < STRINGS.length; i++) { if (STRINGS[i] != null) { byte[] base64Chunked = utf8(CHUNKED_STRINGS[i]); byte[] binary = BYTES[i]; boolean b = Arrays.equals(binary, Base64.decodeBase64(base64Chunked)); assertTrue("static Base64.decodeBase64Chunked() test-" + i, b); } } } private static byte[] utf8(String s) { // We would use commons-codec-1.4.jar own utility method for this, but we // need this class to be able to run against commons-codec-1.3.jar, hence the // duplication here. try { return s != null ? s.getBytes("UTF-8") : null; } catch (UnsupportedEncodingException uee) { throw new IllegalStateException(uee.toString()); } } /** * This main() method can be run with just commons-codec-1.3.jar and junit-3.8.1.jar * on the classpath to make sure these tests truly capture the behaviour of * commons-codec-1.3.jar. * * @param args command-line args */ public static void main(String[] args) { TestSuite suite = new TestSuite(Base64Codec13Test.class); TestResult r = new TestResult(); suite.run(r); int runCount = r.runCount(); int failureCount = r.failureCount(); System.out.println((runCount - failureCount) + "/" + runCount + " tests succeeded!"); if (!r.wasSuccessful()) { Enumeration en = r.errors(); while (en.hasMoreElements()) { TestFailure tf = (TestFailure) en.nextElement(); System.out.println(tf.toString()); } en = r.failures(); while (en.hasMoreElements()) { TestFailure tf = (TestFailure) en.nextElement(); System.out.println(tf.toString()); } } } }
public void testBigDecimal() { BigDecimal o1 = new BigDecimal("2.0"); BigDecimal o2 = new BigDecimal("2.00"); assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(new EqualsBuilder().append(o1, o2).isEquals()); }
org.apache.commons.lang.builder.EqualsBuilderTest::testBigDecimal
src/test/org/apache/commons/lang/builder/EqualsBuilderTest.java
385
src/test/org/apache/commons/lang/builder/EqualsBuilderTest.java
testBigDecimal
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.math.BigDecimal; import java.util.Arrays; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Unit tests {@link org.apache.commons.lang.builder.EqualsBuilder}. * * @author <a href="mailto:sdowney@panix.com">Steve Downey</a> * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a> * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @author Maarten Coene * @version $Id$ */ public class EqualsBuilderTest extends TestCase { public EqualsBuilderTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(EqualsBuilderTest.class); suite.setName("EqualsBuilder Tests"); return suite; } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- static class TestObject { private int a; public TestObject() { } public TestObject(int a) { this.a = a; } public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getClass() != getClass()) { return false; } TestObject rhs = (TestObject) o; return (a == rhs.a); } public void setA(int a) { this.a = a; } public int getA() { return a; } } static class TestSubObject extends TestObject { private int b; public TestSubObject() { super(0); } public TestSubObject(int a, int b) { super(a); this.b = b; } public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getClass() != getClass()) { return false; } TestSubObject rhs = (TestSubObject) o; return super.equals(o) && (b == rhs.b); } public void setB(int b) { this.b = b; } public int getB() { return b; } } static class TestEmptySubObject extends TestObject { public TestEmptySubObject(int a) { super(a); } } static class TestTSubObject extends TestObject { private transient int t; public TestTSubObject(int a, int t) { super(a); this.t = t; } } static class TestTTSubObject extends TestTSubObject { private transient int tt; public TestTTSubObject(int a, int t, int tt) { super(a, t); this.tt = tt; } } static class TestTTLeafObject extends TestTTSubObject { private int leafValue; public TestTTLeafObject(int a, int t, int tt, int leafValue) { super(a, t, tt); this.leafValue = leafValue; } } static class TestTSubObject2 extends TestObject { private transient int t; public TestTSubObject2(int a, int t) { super(a); } public int getT() { return t; } public void setT(int t) { this.t = t; } } public void testReflectionEquals() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertTrue(EqualsBuilder.reflectionEquals(o1, o1)); assertTrue(!EqualsBuilder.reflectionEquals(o1, o2)); o2.setA(4); assertTrue(EqualsBuilder.reflectionEquals(o1, o2)); assertTrue(!EqualsBuilder.reflectionEquals(o1, this)); assertTrue(!EqualsBuilder.reflectionEquals(o1, null)); assertTrue(!EqualsBuilder.reflectionEquals(null, o2)); assertTrue(EqualsBuilder.reflectionEquals((Object) null, (Object) null)); } public void testReflectionHierarchyEquals() { testReflectionHierarchyEquals(false); testReflectionHierarchyEquals(true); // Transients assertTrue(EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true)); assertTrue(EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), false)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 0, 0, 4), new TestTTLeafObject(1, 2, 3, 4), true)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 0), true)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(0, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true)); } public void testReflectionHierarchyEquals(boolean testTransients) { TestObject to1 = new TestObject(4); TestObject to1Bis = new TestObject(4); TestObject to1Ter = new TestObject(4); TestObject to2 = new TestObject(5); TestEmptySubObject teso = new TestEmptySubObject(4); TestTSubObject ttso = new TestTSubObject(4, 1); TestTTSubObject tttso = new TestTTSubObject(4, 1, 2); TestTTLeafObject ttlo = new TestTTLeafObject(4, 1, 2, 3); TestSubObject tso1 = new TestSubObject(1, 4); TestSubObject tso1bis = new TestSubObject(1, 4); TestSubObject tso1ter = new TestSubObject(1, 4); TestSubObject tso2 = new TestSubObject(2, 5); testReflectionEqualsEquivalenceRelationship(to1, to1Bis, to1Ter, to2, new TestObject(), testTransients); testReflectionEqualsEquivalenceRelationship(tso1, tso1bis, tso1ter, tso2, new TestSubObject(), testTransients); // More sanity checks: // same values assertTrue(EqualsBuilder.reflectionEquals(ttlo, ttlo, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 10), testTransients)); // same super values, diff sub values assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 11), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 11), new TestSubObject(1, 10), testTransients)); // diff super values, same sub values assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(0, 10), new TestSubObject(1, 10), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(0, 10), testTransients)); // mix super and sub types: equals assertTrue(EqualsBuilder.reflectionEquals(to1, teso, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(teso, to1, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(to1, ttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(ttso, to1, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(to1, tttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(tttso, to1, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(ttso, tttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(tttso, ttso, false)); // Force testTransients = false for this assert // mix super and sub types: NOT equals assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(0), new TestEmptySubObject(1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestEmptySubObject(1), new TestObject(0), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(0), new TestTSubObject(1, 1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTSubObject(1, 1), new TestObject(0), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(1), new TestSubObject(0, 10), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(0, 10), new TestObject(1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(to1, ttlo)); assertTrue(!EqualsBuilder.reflectionEquals(tso1, this)); } /** * Equivalence relationship tests inspired by "Effective Java": * <ul> * <li>reflection</li> * <li>symmetry</li> * <li>transitive</li> * <li>consistency</li> * <li>non-null reference</li> * </ul> * @param to a TestObject * @param toBis a TestObject, equal to to and toTer * @param toTer Left hand side, equal to to and toBis * @param to2 a different TestObject * @param oToChange a TestObject that will be changed */ public void testReflectionEqualsEquivalenceRelationship( TestObject to, TestObject toBis, TestObject toTer, TestObject to2, TestObject oToChange, boolean testTransients) { // reflection test assertTrue(EqualsBuilder.reflectionEquals(to, to, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(to2, to2, testTransients)); // symmetry test assertTrue(EqualsBuilder.reflectionEquals(to, toBis, testTransients) && EqualsBuilder.reflectionEquals(toBis, to, testTransients)); // transitive test assertTrue( EqualsBuilder.reflectionEquals(to, toBis, testTransients) && EqualsBuilder.reflectionEquals(toBis, toTer, testTransients) && EqualsBuilder.reflectionEquals(to, toTer, testTransients)); // consistency test oToChange.setA(to.getA()); if (oToChange instanceof TestSubObject) { ((TestSubObject) oToChange).setB(((TestSubObject) to).getB()); } assertTrue(EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); oToChange.setA(to.getA() + 1); if (oToChange instanceof TestSubObject) { ((TestSubObject) oToChange).setB(((TestSubObject) to).getB() + 1); } assertTrue(!EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); // non-null reference test assertTrue(!EqualsBuilder.reflectionEquals(to, null, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(to2, null, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(null, to, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(null, to2, testTransients)); assertTrue(EqualsBuilder.reflectionEquals((Object) null, (Object) null, testTransients)); } public void testSuper() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertEquals(true, new EqualsBuilder().appendSuper(true).append(o1, o1).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(false).append(o1, o1).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(true).append(o1, o2).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(false).append(o1, o2).isEquals()); } public void testObject() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); o2.setA(4); assertTrue(new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, this).isEquals()); assertTrue(!new EqualsBuilder().append(o1, null).isEquals()); assertTrue(!new EqualsBuilder().append(null, o2).isEquals()); assertTrue(new EqualsBuilder().append((Object) null, (Object) null).isEquals()); } public void testLong() { long o1 = 1L; long o2 = 2L; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testInt() { int o1 = 1; int o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testShort() { short o1 = 1; short o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testChar() { char o1 = 1; char o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testByte() { byte o1 = 1; byte o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testDouble() { double o1 = 1; double o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, Double.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Double.NaN, Double.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY).isEquals()); } public void testFloat() { float o1 = 1; float o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, Float.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Float.NaN, Float.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY).isEquals()); } // https://issues.apache.org/jira/browse/LANG-393 public void testBigDecimal() { BigDecimal o1 = new BigDecimal("2.0"); BigDecimal o2 = new BigDecimal("2.00"); assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(new EqualsBuilder().append(o1, o2).isEquals()); } public void testAccessors() { EqualsBuilder equalsBuilder = new EqualsBuilder(); assertTrue(equalsBuilder.isEquals()); equalsBuilder.setEquals(true); assertTrue(equalsBuilder.isEquals()); equalsBuilder.setEquals(false); assertFalse(equalsBuilder.isEquals()); } public void testBoolean() { boolean o1 = true; boolean o2 = false; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testObjectArray() { TestObject[] obj1 = new TestObject[3]; obj1[0] = new TestObject(4); obj1[1] = new TestObject(5); obj1[2] = null; TestObject[] obj2 = new TestObject[3]; obj2[0] = new TestObject(4); obj2[1] = new TestObject(5); obj2[2] = null; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj2, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1].setA(6); assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1].setA(5); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[2] = obj1[1]; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[2] = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testLongArray() { long[] obj1 = new long[2]; obj1[0] = 5L; obj1[1] = 6L; long[] obj2 = new long[2]; obj2[0] = 5L; obj2[1] = 6L; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testIntArray() { int[] obj1 = new int[2]; obj1[0] = 5; obj1[1] = 6; int[] obj2 = new int[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testShortArray() { short[] obj1 = new short[2]; obj1[0] = 5; obj1[1] = 6; short[] obj2 = new short[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testCharArray() { char[] obj1 = new char[2]; obj1[0] = 5; obj1[1] = 6; char[] obj2 = new char[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testByteArray() { byte[] obj1 = new byte[2]; obj1[0] = 5; obj1[1] = 6; byte[] obj2 = new byte[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testDoubleArray() { double[] obj1 = new double[2]; obj1[0] = 5; obj1[1] = 6; double[] obj2 = new double[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testFloatArray() { float[] obj1 = new float[2]; obj1[0] = 5; obj1[1] = 6; float[] obj2 = new float[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testBooleanArray() { boolean[] obj1 = new boolean[2]; obj1[0] = true; obj1[1] = false; boolean[] obj2 = new boolean[2]; obj2[0] = true; obj2[1] = false; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = true; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testMultiLongArray() { long[][] array1 = new long[2][2]; long[][] array2 = new long[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiIntArray() { int[][] array1 = new int[2][2]; int[][] array2 = new int[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiShortArray() { short[][] array1 = new short[2][2]; short[][] array2 = new short[2][2]; for (short i = 0; i < array1.length; ++i) { for (short j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiCharArray() { char[][] array1 = new char[2][2]; char[][] array2 = new char[2][2]; for (char i = 0; i < array1.length; ++i) { for (char j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiByteArray() { byte[][] array1 = new byte[2][2]; byte[][] array2 = new byte[2][2]; for (byte i = 0; i < array1.length; ++i) { for (byte j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiFloatArray() { float[][] array1 = new float[2][2]; float[][] array2 = new float[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiDoubleArray() { double[][] array1 = new double[2][2]; double[][] array2 = new double[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiBooleanArray() { boolean[][] array1 = new boolean[2][2]; boolean[][] array2 = new boolean[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i == 1) || (j == 1); array2[i][j] = (i == 1) || (j == 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = false; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); // compare 1 dim to 2. boolean[] array3 = new boolean[]{true, true}; assertFalse(new EqualsBuilder().append(array1, array3).isEquals()); assertFalse(new EqualsBuilder().append(array3, array1).isEquals()); assertFalse(new EqualsBuilder().append(array2, array3).isEquals()); assertFalse(new EqualsBuilder().append(array3, array2).isEquals()); } public void testRaggedArray() { long array1[][] = new long[2][]; long array2[][] = new long[2][]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; for (int j = 0; j < array1[i].length; ++j) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMixedArray() { Object array1[] = new Object[2]; Object array2[] = new Object[2]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; for (int j = 0; j < 2; ++j) { ((long[]) array1[i])[j] = (i + 1) * (j + 1); ((long[]) array2[i])[j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); ((long[]) array1[1])[1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testObjectArrayHiddenByObject() { TestObject[] array1 = new TestObject[2]; array1[0] = new TestObject(4); array1[1] = new TestObject(5); TestObject[] array2 = new TestObject[2]; array2[0] = new TestObject(4); array2[1] = new TestObject(5); Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1].setA(6); assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testLongArrayHiddenByObject() { long[] array1 = new long[2]; array1[0] = 5L; array1[1] = 6L; long[] array2 = new long[2]; array2[0] = 5L; array2[1] = 6L; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testIntArrayHiddenByObject() { int[] array1 = new int[2]; array1[0] = 5; array1[1] = 6; int[] array2 = new int[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testShortArrayHiddenByObject() { short[] array1 = new short[2]; array1[0] = 5; array1[1] = 6; short[] array2 = new short[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testCharArrayHiddenByObject() { char[] array1 = new char[2]; array1[0] = 5; array1[1] = 6; char[] array2 = new char[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testByteArrayHiddenByObject() { byte[] array1 = new byte[2]; array1[0] = 5; array1[1] = 6; byte[] array2 = new byte[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testDoubleArrayHiddenByObject() { double[] array1 = new double[2]; array1[0] = 5; array1[1] = 6; double[] array2 = new double[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testFloatArrayHiddenByObject() { float[] array1 = new float[2]; array1[0] = 5; array1[1] = 6; float[] array2 = new float[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testBooleanArrayHiddenByObject() { boolean[] array1 = new boolean[2]; array1[0] = true; array1[1] = false; boolean[] array2 = new boolean[2]; array2[0] = true; array2[1] = false; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = true; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public static class TestACanEqualB { private int a; public TestACanEqualB(int a) { this.a = a; } public boolean equals(Object o) { if (o == this) return true; if (o instanceof TestACanEqualB) return this.a == ((TestACanEqualB) o).getA(); if (o instanceof TestBCanEqualA) return this.a == ((TestBCanEqualA) o).getB(); return false; } public int getA() { return this.a; } } public static class TestBCanEqualA { private int b; public TestBCanEqualA(int b) { this.b = b; } public boolean equals(Object o) { if (o == this) return true; if (o instanceof TestACanEqualB) return this.b == ((TestACanEqualB) o).getA(); if (o instanceof TestBCanEqualA) return this.b == ((TestBCanEqualA) o).getB(); return false; } public int getB() { return this.b; } } /** * Tests two instances of classes that can be equal and that are not "related". The two classes are not subclasses * of each other and do not share a parent aside from Object. * See http://issues.apache.org/bugzilla/show_bug.cgi?id=33069 */ public void testUnrelatedClasses() { Object[] x = new Object[]{new TestACanEqualB(1)}; Object[] y = new Object[]{new TestBCanEqualA(1)}; // sanity checks: assertTrue(Arrays.equals(x, x)); assertTrue(Arrays.equals(y, y)); assertTrue(Arrays.equals(x, y)); assertTrue(Arrays.equals(y, x)); // real tests: assertTrue(x[0].equals(x[0])); assertTrue(y[0].equals(y[0])); assertTrue(x[0].equals(y[0])); assertTrue(y[0].equals(x[0])); assertTrue(new EqualsBuilder().append(x, x).isEquals()); assertTrue(new EqualsBuilder().append(y, y).isEquals()); assertTrue(new EqualsBuilder().append(x, y).isEquals()); assertTrue(new EqualsBuilder().append(y, x).isEquals()); } /** * Test from http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 */ public void testNpeForNullElement() { Object[] x1 = new Object[] { new Integer(1), null, new Integer(3) }; Object[] x2 = new Object[] { new Integer(1), new Integer(2), new Integer(3) }; // causes an NPE in 2.0 according to: // http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 new EqualsBuilder().append(x1, x2); } public void testReflectionEqualsExcludeFields() throws Exception { TestObjectWithMultipleFields x1 = new TestObjectWithMultipleFields(1, 2, 3); TestObjectWithMultipleFields x2 = new TestObjectWithMultipleFields(1, 3, 4); // not equal when including all fields assertTrue(!EqualsBuilder.reflectionEquals(x1, x2)); // doesn't barf on null, empty array, or non-existent field, but still tests as not equal assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, (String[]) null)); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {})); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"xxx"})); // not equal if only one of the differing fields excluded assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"two"})); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"three"})); // equal if both differing fields excluded assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"two", "three"})); // still equal as long as both differing fields are among excluded assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"one", "two", "three"})); assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"one", "two", "three", "xxx"})); } static class TestObjectWithMultipleFields { private TestObject one; private TestObject two; private TestObject three; public TestObjectWithMultipleFields(int one, int two, int three) { this.one = new TestObject(one); this.two = new TestObject(two); this.three = new TestObject(three); } } }
// You are a professional Java test case writer, please create a test case named `testBigDecimal` for the issue `Lang-LANG-393`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-393 // // ## Issue-Title: // EqualsBuilder don't compare BigDecimals correctly // // ## Issue-Description: // // When comparing a BigDecimal, the comparing is made using equals, not compareTo, which is more appropriate in the case of BigDecimal. // // // // // public void testBigDecimal() {
385
// https://issues.apache.org/jira/browse/LANG-393
48
380
src/test/org/apache/commons/lang/builder/EqualsBuilderTest.java
src/test
```markdown ## Issue-ID: Lang-LANG-393 ## Issue-Title: EqualsBuilder don't compare BigDecimals correctly ## Issue-Description: When comparing a BigDecimal, the comparing is made using equals, not compareTo, which is more appropriate in the case of BigDecimal. ``` You are a professional Java test case writer, please create a test case named `testBigDecimal` for the issue `Lang-LANG-393`, utilizing the provided issue report information and the following function signature. ```java public void testBigDecimal() { ```
380
[ "org.apache.commons.lang.builder.EqualsBuilder" ]
0be03ff601b5b4e22dfe2c53c818917daf5b757cc8a1c7a3c0cc641c5578a373
public void testBigDecimal()
// You are a professional Java test case writer, please create a test case named `testBigDecimal` for the issue `Lang-LANG-393`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-393 // // ## Issue-Title: // EqualsBuilder don't compare BigDecimals correctly // // ## Issue-Description: // // When comparing a BigDecimal, the comparing is made using equals, not compareTo, which is more appropriate in the case of BigDecimal. // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.math.BigDecimal; import java.util.Arrays; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Unit tests {@link org.apache.commons.lang.builder.EqualsBuilder}. * * @author <a href="mailto:sdowney@panix.com">Steve Downey</a> * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a> * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @author Maarten Coene * @version $Id$ */ public class EqualsBuilderTest extends TestCase { public EqualsBuilderTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(EqualsBuilderTest.class); suite.setName("EqualsBuilder Tests"); return suite; } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- static class TestObject { private int a; public TestObject() { } public TestObject(int a) { this.a = a; } public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getClass() != getClass()) { return false; } TestObject rhs = (TestObject) o; return (a == rhs.a); } public void setA(int a) { this.a = a; } public int getA() { return a; } } static class TestSubObject extends TestObject { private int b; public TestSubObject() { super(0); } public TestSubObject(int a, int b) { super(a); this.b = b; } public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getClass() != getClass()) { return false; } TestSubObject rhs = (TestSubObject) o; return super.equals(o) && (b == rhs.b); } public void setB(int b) { this.b = b; } public int getB() { return b; } } static class TestEmptySubObject extends TestObject { public TestEmptySubObject(int a) { super(a); } } static class TestTSubObject extends TestObject { private transient int t; public TestTSubObject(int a, int t) { super(a); this.t = t; } } static class TestTTSubObject extends TestTSubObject { private transient int tt; public TestTTSubObject(int a, int t, int tt) { super(a, t); this.tt = tt; } } static class TestTTLeafObject extends TestTTSubObject { private int leafValue; public TestTTLeafObject(int a, int t, int tt, int leafValue) { super(a, t, tt); this.leafValue = leafValue; } } static class TestTSubObject2 extends TestObject { private transient int t; public TestTSubObject2(int a, int t) { super(a); } public int getT() { return t; } public void setT(int t) { this.t = t; } } public void testReflectionEquals() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertTrue(EqualsBuilder.reflectionEquals(o1, o1)); assertTrue(!EqualsBuilder.reflectionEquals(o1, o2)); o2.setA(4); assertTrue(EqualsBuilder.reflectionEquals(o1, o2)); assertTrue(!EqualsBuilder.reflectionEquals(o1, this)); assertTrue(!EqualsBuilder.reflectionEquals(o1, null)); assertTrue(!EqualsBuilder.reflectionEquals(null, o2)); assertTrue(EqualsBuilder.reflectionEquals((Object) null, (Object) null)); } public void testReflectionHierarchyEquals() { testReflectionHierarchyEquals(false); testReflectionHierarchyEquals(true); // Transients assertTrue(EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true)); assertTrue(EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), false)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 0, 0, 4), new TestTTLeafObject(1, 2, 3, 4), true)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 0), true)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(0, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true)); } public void testReflectionHierarchyEquals(boolean testTransients) { TestObject to1 = new TestObject(4); TestObject to1Bis = new TestObject(4); TestObject to1Ter = new TestObject(4); TestObject to2 = new TestObject(5); TestEmptySubObject teso = new TestEmptySubObject(4); TestTSubObject ttso = new TestTSubObject(4, 1); TestTTSubObject tttso = new TestTTSubObject(4, 1, 2); TestTTLeafObject ttlo = new TestTTLeafObject(4, 1, 2, 3); TestSubObject tso1 = new TestSubObject(1, 4); TestSubObject tso1bis = new TestSubObject(1, 4); TestSubObject tso1ter = new TestSubObject(1, 4); TestSubObject tso2 = new TestSubObject(2, 5); testReflectionEqualsEquivalenceRelationship(to1, to1Bis, to1Ter, to2, new TestObject(), testTransients); testReflectionEqualsEquivalenceRelationship(tso1, tso1bis, tso1ter, tso2, new TestSubObject(), testTransients); // More sanity checks: // same values assertTrue(EqualsBuilder.reflectionEquals(ttlo, ttlo, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 10), testTransients)); // same super values, diff sub values assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 11), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 11), new TestSubObject(1, 10), testTransients)); // diff super values, same sub values assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(0, 10), new TestSubObject(1, 10), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(0, 10), testTransients)); // mix super and sub types: equals assertTrue(EqualsBuilder.reflectionEquals(to1, teso, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(teso, to1, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(to1, ttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(ttso, to1, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(to1, tttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(tttso, to1, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(ttso, tttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(tttso, ttso, false)); // Force testTransients = false for this assert // mix super and sub types: NOT equals assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(0), new TestEmptySubObject(1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestEmptySubObject(1), new TestObject(0), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(0), new TestTSubObject(1, 1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTSubObject(1, 1), new TestObject(0), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(1), new TestSubObject(0, 10), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(0, 10), new TestObject(1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(to1, ttlo)); assertTrue(!EqualsBuilder.reflectionEquals(tso1, this)); } /** * Equivalence relationship tests inspired by "Effective Java": * <ul> * <li>reflection</li> * <li>symmetry</li> * <li>transitive</li> * <li>consistency</li> * <li>non-null reference</li> * </ul> * @param to a TestObject * @param toBis a TestObject, equal to to and toTer * @param toTer Left hand side, equal to to and toBis * @param to2 a different TestObject * @param oToChange a TestObject that will be changed */ public void testReflectionEqualsEquivalenceRelationship( TestObject to, TestObject toBis, TestObject toTer, TestObject to2, TestObject oToChange, boolean testTransients) { // reflection test assertTrue(EqualsBuilder.reflectionEquals(to, to, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(to2, to2, testTransients)); // symmetry test assertTrue(EqualsBuilder.reflectionEquals(to, toBis, testTransients) && EqualsBuilder.reflectionEquals(toBis, to, testTransients)); // transitive test assertTrue( EqualsBuilder.reflectionEquals(to, toBis, testTransients) && EqualsBuilder.reflectionEquals(toBis, toTer, testTransients) && EqualsBuilder.reflectionEquals(to, toTer, testTransients)); // consistency test oToChange.setA(to.getA()); if (oToChange instanceof TestSubObject) { ((TestSubObject) oToChange).setB(((TestSubObject) to).getB()); } assertTrue(EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); oToChange.setA(to.getA() + 1); if (oToChange instanceof TestSubObject) { ((TestSubObject) oToChange).setB(((TestSubObject) to).getB() + 1); } assertTrue(!EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); // non-null reference test assertTrue(!EqualsBuilder.reflectionEquals(to, null, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(to2, null, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(null, to, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(null, to2, testTransients)); assertTrue(EqualsBuilder.reflectionEquals((Object) null, (Object) null, testTransients)); } public void testSuper() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertEquals(true, new EqualsBuilder().appendSuper(true).append(o1, o1).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(false).append(o1, o1).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(true).append(o1, o2).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(false).append(o1, o2).isEquals()); } public void testObject() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); o2.setA(4); assertTrue(new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, this).isEquals()); assertTrue(!new EqualsBuilder().append(o1, null).isEquals()); assertTrue(!new EqualsBuilder().append(null, o2).isEquals()); assertTrue(new EqualsBuilder().append((Object) null, (Object) null).isEquals()); } public void testLong() { long o1 = 1L; long o2 = 2L; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testInt() { int o1 = 1; int o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testShort() { short o1 = 1; short o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testChar() { char o1 = 1; char o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testByte() { byte o1 = 1; byte o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testDouble() { double o1 = 1; double o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, Double.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Double.NaN, Double.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY).isEquals()); } public void testFloat() { float o1 = 1; float o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, Float.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Float.NaN, Float.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY).isEquals()); } // https://issues.apache.org/jira/browse/LANG-393 public void testBigDecimal() { BigDecimal o1 = new BigDecimal("2.0"); BigDecimal o2 = new BigDecimal("2.00"); assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(new EqualsBuilder().append(o1, o2).isEquals()); } public void testAccessors() { EqualsBuilder equalsBuilder = new EqualsBuilder(); assertTrue(equalsBuilder.isEquals()); equalsBuilder.setEquals(true); assertTrue(equalsBuilder.isEquals()); equalsBuilder.setEquals(false); assertFalse(equalsBuilder.isEquals()); } public void testBoolean() { boolean o1 = true; boolean o2 = false; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testObjectArray() { TestObject[] obj1 = new TestObject[3]; obj1[0] = new TestObject(4); obj1[1] = new TestObject(5); obj1[2] = null; TestObject[] obj2 = new TestObject[3]; obj2[0] = new TestObject(4); obj2[1] = new TestObject(5); obj2[2] = null; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj2, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1].setA(6); assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1].setA(5); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[2] = obj1[1]; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[2] = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testLongArray() { long[] obj1 = new long[2]; obj1[0] = 5L; obj1[1] = 6L; long[] obj2 = new long[2]; obj2[0] = 5L; obj2[1] = 6L; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testIntArray() { int[] obj1 = new int[2]; obj1[0] = 5; obj1[1] = 6; int[] obj2 = new int[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testShortArray() { short[] obj1 = new short[2]; obj1[0] = 5; obj1[1] = 6; short[] obj2 = new short[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testCharArray() { char[] obj1 = new char[2]; obj1[0] = 5; obj1[1] = 6; char[] obj2 = new char[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testByteArray() { byte[] obj1 = new byte[2]; obj1[0] = 5; obj1[1] = 6; byte[] obj2 = new byte[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testDoubleArray() { double[] obj1 = new double[2]; obj1[0] = 5; obj1[1] = 6; double[] obj2 = new double[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testFloatArray() { float[] obj1 = new float[2]; obj1[0] = 5; obj1[1] = 6; float[] obj2 = new float[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testBooleanArray() { boolean[] obj1 = new boolean[2]; obj1[0] = true; obj1[1] = false; boolean[] obj2 = new boolean[2]; obj2[0] = true; obj2[1] = false; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = true; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testMultiLongArray() { long[][] array1 = new long[2][2]; long[][] array2 = new long[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiIntArray() { int[][] array1 = new int[2][2]; int[][] array2 = new int[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiShortArray() { short[][] array1 = new short[2][2]; short[][] array2 = new short[2][2]; for (short i = 0; i < array1.length; ++i) { for (short j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiCharArray() { char[][] array1 = new char[2][2]; char[][] array2 = new char[2][2]; for (char i = 0; i < array1.length; ++i) { for (char j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiByteArray() { byte[][] array1 = new byte[2][2]; byte[][] array2 = new byte[2][2]; for (byte i = 0; i < array1.length; ++i) { for (byte j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiFloatArray() { float[][] array1 = new float[2][2]; float[][] array2 = new float[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiDoubleArray() { double[][] array1 = new double[2][2]; double[][] array2 = new double[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiBooleanArray() { boolean[][] array1 = new boolean[2][2]; boolean[][] array2 = new boolean[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i == 1) || (j == 1); array2[i][j] = (i == 1) || (j == 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = false; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); // compare 1 dim to 2. boolean[] array3 = new boolean[]{true, true}; assertFalse(new EqualsBuilder().append(array1, array3).isEquals()); assertFalse(new EqualsBuilder().append(array3, array1).isEquals()); assertFalse(new EqualsBuilder().append(array2, array3).isEquals()); assertFalse(new EqualsBuilder().append(array3, array2).isEquals()); } public void testRaggedArray() { long array1[][] = new long[2][]; long array2[][] = new long[2][]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; for (int j = 0; j < array1[i].length; ++j) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMixedArray() { Object array1[] = new Object[2]; Object array2[] = new Object[2]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; for (int j = 0; j < 2; ++j) { ((long[]) array1[i])[j] = (i + 1) * (j + 1); ((long[]) array2[i])[j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); ((long[]) array1[1])[1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testObjectArrayHiddenByObject() { TestObject[] array1 = new TestObject[2]; array1[0] = new TestObject(4); array1[1] = new TestObject(5); TestObject[] array2 = new TestObject[2]; array2[0] = new TestObject(4); array2[1] = new TestObject(5); Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1].setA(6); assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testLongArrayHiddenByObject() { long[] array1 = new long[2]; array1[0] = 5L; array1[1] = 6L; long[] array2 = new long[2]; array2[0] = 5L; array2[1] = 6L; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testIntArrayHiddenByObject() { int[] array1 = new int[2]; array1[0] = 5; array1[1] = 6; int[] array2 = new int[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testShortArrayHiddenByObject() { short[] array1 = new short[2]; array1[0] = 5; array1[1] = 6; short[] array2 = new short[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testCharArrayHiddenByObject() { char[] array1 = new char[2]; array1[0] = 5; array1[1] = 6; char[] array2 = new char[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testByteArrayHiddenByObject() { byte[] array1 = new byte[2]; array1[0] = 5; array1[1] = 6; byte[] array2 = new byte[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testDoubleArrayHiddenByObject() { double[] array1 = new double[2]; array1[0] = 5; array1[1] = 6; double[] array2 = new double[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testFloatArrayHiddenByObject() { float[] array1 = new float[2]; array1[0] = 5; array1[1] = 6; float[] array2 = new float[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testBooleanArrayHiddenByObject() { boolean[] array1 = new boolean[2]; array1[0] = true; array1[1] = false; boolean[] array2 = new boolean[2]; array2[0] = true; array2[1] = false; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = true; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public static class TestACanEqualB { private int a; public TestACanEqualB(int a) { this.a = a; } public boolean equals(Object o) { if (o == this) return true; if (o instanceof TestACanEqualB) return this.a == ((TestACanEqualB) o).getA(); if (o instanceof TestBCanEqualA) return this.a == ((TestBCanEqualA) o).getB(); return false; } public int getA() { return this.a; } } public static class TestBCanEqualA { private int b; public TestBCanEqualA(int b) { this.b = b; } public boolean equals(Object o) { if (o == this) return true; if (o instanceof TestACanEqualB) return this.b == ((TestACanEqualB) o).getA(); if (o instanceof TestBCanEqualA) return this.b == ((TestBCanEqualA) o).getB(); return false; } public int getB() { return this.b; } } /** * Tests two instances of classes that can be equal and that are not "related". The two classes are not subclasses * of each other and do not share a parent aside from Object. * See http://issues.apache.org/bugzilla/show_bug.cgi?id=33069 */ public void testUnrelatedClasses() { Object[] x = new Object[]{new TestACanEqualB(1)}; Object[] y = new Object[]{new TestBCanEqualA(1)}; // sanity checks: assertTrue(Arrays.equals(x, x)); assertTrue(Arrays.equals(y, y)); assertTrue(Arrays.equals(x, y)); assertTrue(Arrays.equals(y, x)); // real tests: assertTrue(x[0].equals(x[0])); assertTrue(y[0].equals(y[0])); assertTrue(x[0].equals(y[0])); assertTrue(y[0].equals(x[0])); assertTrue(new EqualsBuilder().append(x, x).isEquals()); assertTrue(new EqualsBuilder().append(y, y).isEquals()); assertTrue(new EqualsBuilder().append(x, y).isEquals()); assertTrue(new EqualsBuilder().append(y, x).isEquals()); } /** * Test from http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 */ public void testNpeForNullElement() { Object[] x1 = new Object[] { new Integer(1), null, new Integer(3) }; Object[] x2 = new Object[] { new Integer(1), new Integer(2), new Integer(3) }; // causes an NPE in 2.0 according to: // http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 new EqualsBuilder().append(x1, x2); } public void testReflectionEqualsExcludeFields() throws Exception { TestObjectWithMultipleFields x1 = new TestObjectWithMultipleFields(1, 2, 3); TestObjectWithMultipleFields x2 = new TestObjectWithMultipleFields(1, 3, 4); // not equal when including all fields assertTrue(!EqualsBuilder.reflectionEquals(x1, x2)); // doesn't barf on null, empty array, or non-existent field, but still tests as not equal assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, (String[]) null)); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {})); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"xxx"})); // not equal if only one of the differing fields excluded assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"two"})); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"three"})); // equal if both differing fields excluded assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"two", "three"})); // still equal as long as both differing fields are among excluded assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"one", "two", "three"})); assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"one", "two", "three", "xxx"})); } static class TestObjectWithMultipleFields { private TestObject one; private TestObject two; private TestObject three; public TestObjectWithMultipleFields(int one, int two, int three) { this.one = new TestObject(one); this.two = new TestObject(two); this.three = new TestObject(three); } } }
public void testPolymorphicTypeViaCustom() throws Exception { Base1270<Poly1> req = new Base1270<Poly1>(); Poly1 o = new Poly1(); o.val = "optionValue"; req.options = o; req.val = "some value"; Top1270 top = new Top1270(); top.b = req; String json = MAPPER.writeValueAsString(top); JsonNode tree = MAPPER.readTree(json); assertNotNull(tree.get("b")); assertNotNull(tree.get("b").get("options")); assertNotNull(tree.get("b").get("options").get("val")); // Can we reverse the process? I have some doubts Top1270 itemRead = MAPPER.readValue(json, Top1270.class); assertNotNull(itemRead); assertNotNull(itemRead.b); }
com.fasterxml.jackson.databind.jsontype.TestCustomTypeIdResolver::testPolymorphicTypeViaCustom
src/test/java/com/fasterxml/jackson/databind/jsontype/TestCustomTypeIdResolver.java
228
src/test/java/com/fasterxml/jackson/databind/jsontype/TestCustomTypeIdResolver.java
testPolymorphicTypeViaCustom
package com.fasterxml.jackson.databind.jsontype; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase; import com.fasterxml.jackson.databind.type.TypeFactory; public class TestCustomTypeIdResolver extends BaseMapTest { @JsonTypeInfo(use=Id.CUSTOM, include=As.WRAPPER_OBJECT) @JsonTypeIdResolver(CustomResolver.class) static abstract class CustomBean { } static class CustomBeanImpl extends CustomBean { public int x; public CustomBeanImpl() { } public CustomBeanImpl(int x) { this.x = x; } } static class ExtBeanWrapper { @JsonTypeInfo(use=Id.CUSTOM, include=As.EXTERNAL_PROPERTY, property="type") @JsonTypeIdResolver(ExtResolver.class) public ExtBean value; } static class CustomResolver extends TestCustomResolverBase { // yes, static: just for test purposes, not real use static List<JavaType> initTypes; public CustomResolver() { super(CustomBean.class, CustomBeanImpl.class); } @Override public void init(JavaType baseType) { if (initTypes != null) { initTypes.add(baseType); } } } static abstract class ExtBean { } static class ExtBeanImpl extends ExtBean { public int y; public ExtBeanImpl() { } public ExtBeanImpl(int y) { this.y = y; } } static class ExtResolver extends TestCustomResolverBase { public ExtResolver() { super(ExtBean.class, ExtBeanImpl.class); } } static class TestCustomResolverBase extends TypeIdResolverBase { protected final Class<?> superType; protected final Class<?> subType; public TestCustomResolverBase(Class<?> baseType, Class<?> implType) { superType = baseType; subType = implType; } @Override public Id getMechanism() { return Id.CUSTOM; } @Override public String idFromValue(Object value) { if (superType.isAssignableFrom(value.getClass())) { return "*"; } return "unknown"; } @Override public String idFromValueAndType(Object value, Class<?> type) { return idFromValue(value); } @Override public void init(JavaType baseType) { } @Override public JavaType typeFromId(DatabindContext context, String id) { if ("*".equals(id)) { return TypeFactory.defaultInstance().constructType(subType); } return null; } @Override public String idFromBaseType() { return "xxx"; } } // for [databind#1270] static class Top1270 { @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeIdResolver(Resolver1270.class) public Base1270<?> b; } static class Base1270<O extends Poly1Base> { public O options; public String val; } static abstract class Poly1Base { } static class Poly1 extends Poly1Base { public String val; } static class Resolver1270 implements TypeIdResolver { public Resolver1270() { } @Override public void init(JavaType baseType) { } @Override public String idFromValue(Object value) { if (value.getClass() == Base1270.class) { return "poly1"; } return null; } @Override public String idFromValueAndType(Object value, Class<?> suggestedType) { return idFromValue(value); } @Override public String idFromBaseType() { return null; } @Override public JavaType typeFromId(DatabindContext context, String id) { if ("poly1".equals(id)) { return context.getTypeFactory() .constructType(new TypeReference<Base1270<Poly1>>() { }); } return null; } @Override public String getDescForKnownTypeIds() { return null; } @Override public JsonTypeInfo.Id getMechanism() { return JsonTypeInfo.Id.CUSTOM; } } /* /********************************************************** /* Unit tests /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); public void testCustomTypeIdResolver() throws Exception { List<JavaType> types = new ArrayList<JavaType>(); CustomResolver.initTypes = types; String json = MAPPER.writeValueAsString(new CustomBean[] { new CustomBeanImpl(28) }); assertEquals("[{\"*\":{\"x\":28}}]", json); assertEquals(1, types.size()); assertEquals(CustomBean.class, types.get(0).getRawClass()); types = new ArrayList<JavaType>(); CustomResolver.initTypes = types; CustomBean[] result = MAPPER.readValue(json, CustomBean[].class); assertNotNull(result); assertEquals(1, result.length); assertEquals(28, ((CustomBeanImpl) result[0]).x); assertEquals(1, types.size()); assertEquals(CustomBean.class, types.get(0).getRawClass()); } public void testCustomWithExternal() throws Exception { ExtBeanWrapper w = new ExtBeanWrapper(); w.value = new ExtBeanImpl(12); String json = MAPPER.writeValueAsString(w); ExtBeanWrapper out = MAPPER.readValue(json, ExtBeanWrapper.class); assertNotNull(out); assertEquals(12, ((ExtBeanImpl) out.value).y); } // for [databind#1270] public void testPolymorphicTypeViaCustom() throws Exception { Base1270<Poly1> req = new Base1270<Poly1>(); Poly1 o = new Poly1(); o.val = "optionValue"; req.options = o; req.val = "some value"; Top1270 top = new Top1270(); top.b = req; String json = MAPPER.writeValueAsString(top); JsonNode tree = MAPPER.readTree(json); assertNotNull(tree.get("b")); assertNotNull(tree.get("b").get("options")); assertNotNull(tree.get("b").get("options").get("val")); // Can we reverse the process? I have some doubts Top1270 itemRead = MAPPER.readValue(json, Top1270.class); assertNotNull(itemRead); assertNotNull(itemRead.b); } }
// You are a professional Java test case writer, please create a test case named `testPolymorphicTypeViaCustom` for the issue `JacksonDatabind-1270`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1270 // // ## Issue-Title: // Generic type returned from type id resolver seems to be ignored // // ## Issue-Description: // <https://github.com/benson-basis/jackson-custom-mess-tc> // // // Here's the situation, with Jackson 2.7.4. // // // I have a TypeIdResolver that returns a JavaType for a generic type. However, something seems to be forgetting/erasing the generic, as it is failing to use the generic type param to understand the type of a field in the class. // // // All the information is in the test case, so I'm not putting any code to read here in the issue. // // // // public void testPolymorphicTypeViaCustom() throws Exception {
228
// for [databind#1270]
51
210
src/test/java/com/fasterxml/jackson/databind/jsontype/TestCustomTypeIdResolver.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1270 ## Issue-Title: Generic type returned from type id resolver seems to be ignored ## Issue-Description: <https://github.com/benson-basis/jackson-custom-mess-tc> Here's the situation, with Jackson 2.7.4. I have a TypeIdResolver that returns a JavaType for a generic type. However, something seems to be forgetting/erasing the generic, as it is failing to use the generic type param to understand the type of a field in the class. All the information is in the test case, so I'm not putting any code to read here in the issue. ``` You are a professional Java test case writer, please create a test case named `testPolymorphicTypeViaCustom` for the issue `JacksonDatabind-1270`, utilizing the provided issue report information and the following function signature. ```java public void testPolymorphicTypeViaCustom() throws Exception { ```
210
[ "com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase" ]
0bf0b58e9d52cb0c7335793fbbef44cca00395ba2db2f9b50753c308d0075f92
public void testPolymorphicTypeViaCustom() throws Exception
// You are a professional Java test case writer, please create a test case named `testPolymorphicTypeViaCustom` for the issue `JacksonDatabind-1270`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1270 // // ## Issue-Title: // Generic type returned from type id resolver seems to be ignored // // ## Issue-Description: // <https://github.com/benson-basis/jackson-custom-mess-tc> // // // Here's the situation, with Jackson 2.7.4. // // // I have a TypeIdResolver that returns a JavaType for a generic type. However, something seems to be forgetting/erasing the generic, as it is failing to use the generic type param to understand the type of a field in the class. // // // All the information is in the test case, so I'm not putting any code to read here in the issue. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.jsontype; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase; import com.fasterxml.jackson.databind.type.TypeFactory; public class TestCustomTypeIdResolver extends BaseMapTest { @JsonTypeInfo(use=Id.CUSTOM, include=As.WRAPPER_OBJECT) @JsonTypeIdResolver(CustomResolver.class) static abstract class CustomBean { } static class CustomBeanImpl extends CustomBean { public int x; public CustomBeanImpl() { } public CustomBeanImpl(int x) { this.x = x; } } static class ExtBeanWrapper { @JsonTypeInfo(use=Id.CUSTOM, include=As.EXTERNAL_PROPERTY, property="type") @JsonTypeIdResolver(ExtResolver.class) public ExtBean value; } static class CustomResolver extends TestCustomResolverBase { // yes, static: just for test purposes, not real use static List<JavaType> initTypes; public CustomResolver() { super(CustomBean.class, CustomBeanImpl.class); } @Override public void init(JavaType baseType) { if (initTypes != null) { initTypes.add(baseType); } } } static abstract class ExtBean { } static class ExtBeanImpl extends ExtBean { public int y; public ExtBeanImpl() { } public ExtBeanImpl(int y) { this.y = y; } } static class ExtResolver extends TestCustomResolverBase { public ExtResolver() { super(ExtBean.class, ExtBeanImpl.class); } } static class TestCustomResolverBase extends TypeIdResolverBase { protected final Class<?> superType; protected final Class<?> subType; public TestCustomResolverBase(Class<?> baseType, Class<?> implType) { superType = baseType; subType = implType; } @Override public Id getMechanism() { return Id.CUSTOM; } @Override public String idFromValue(Object value) { if (superType.isAssignableFrom(value.getClass())) { return "*"; } return "unknown"; } @Override public String idFromValueAndType(Object value, Class<?> type) { return idFromValue(value); } @Override public void init(JavaType baseType) { } @Override public JavaType typeFromId(DatabindContext context, String id) { if ("*".equals(id)) { return TypeFactory.defaultInstance().constructType(subType); } return null; } @Override public String idFromBaseType() { return "xxx"; } } // for [databind#1270] static class Top1270 { @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeIdResolver(Resolver1270.class) public Base1270<?> b; } static class Base1270<O extends Poly1Base> { public O options; public String val; } static abstract class Poly1Base { } static class Poly1 extends Poly1Base { public String val; } static class Resolver1270 implements TypeIdResolver { public Resolver1270() { } @Override public void init(JavaType baseType) { } @Override public String idFromValue(Object value) { if (value.getClass() == Base1270.class) { return "poly1"; } return null; } @Override public String idFromValueAndType(Object value, Class<?> suggestedType) { return idFromValue(value); } @Override public String idFromBaseType() { return null; } @Override public JavaType typeFromId(DatabindContext context, String id) { if ("poly1".equals(id)) { return context.getTypeFactory() .constructType(new TypeReference<Base1270<Poly1>>() { }); } return null; } @Override public String getDescForKnownTypeIds() { return null; } @Override public JsonTypeInfo.Id getMechanism() { return JsonTypeInfo.Id.CUSTOM; } } /* /********************************************************** /* Unit tests /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); public void testCustomTypeIdResolver() throws Exception { List<JavaType> types = new ArrayList<JavaType>(); CustomResolver.initTypes = types; String json = MAPPER.writeValueAsString(new CustomBean[] { new CustomBeanImpl(28) }); assertEquals("[{\"*\":{\"x\":28}}]", json); assertEquals(1, types.size()); assertEquals(CustomBean.class, types.get(0).getRawClass()); types = new ArrayList<JavaType>(); CustomResolver.initTypes = types; CustomBean[] result = MAPPER.readValue(json, CustomBean[].class); assertNotNull(result); assertEquals(1, result.length); assertEquals(28, ((CustomBeanImpl) result[0]).x); assertEquals(1, types.size()); assertEquals(CustomBean.class, types.get(0).getRawClass()); } public void testCustomWithExternal() throws Exception { ExtBeanWrapper w = new ExtBeanWrapper(); w.value = new ExtBeanImpl(12); String json = MAPPER.writeValueAsString(w); ExtBeanWrapper out = MAPPER.readValue(json, ExtBeanWrapper.class); assertNotNull(out); assertEquals(12, ((ExtBeanImpl) out.value).y); } // for [databind#1270] public void testPolymorphicTypeViaCustom() throws Exception { Base1270<Poly1> req = new Base1270<Poly1>(); Poly1 o = new Poly1(); o.val = "optionValue"; req.options = o; req.val = "some value"; Top1270 top = new Top1270(); top.b = req; String json = MAPPER.writeValueAsString(top); JsonNode tree = MAPPER.readTree(json); assertNotNull(tree.get("b")); assertNotNull(tree.get("b").get("options")); assertNotNull(tree.get("b").get("options").get("val")); // Can we reverse the process? I have some doubts Top1270 itemRead = MAPPER.readValue(json, Top1270.class); assertNotNull(itemRead); assertNotNull(itemRead.b); } }
public void testCauseOfThrowableIgnoral() throws Exception { final SecurityManager origSecMan = System.getSecurityManager(); try { System.setSecurityManager(new CauseBlockingSecurityManager()); _testCauseOfThrowableIgnoral(); } finally { System.setSecurityManager(origSecMan); } }
com.fasterxml.jackson.databind.misc.AccessFixTest::testCauseOfThrowableIgnoral
src/test/java/com/fasterxml/jackson/databind/misc/AccessFixTest.java
32
src/test/java/com/fasterxml/jackson/databind/misc/AccessFixTest.java
testCauseOfThrowableIgnoral
package com.fasterxml.jackson.databind.misc; import java.io.IOException; import java.security.Permission; import com.fasterxml.jackson.databind.*; // Test(s) to verify that forced access works as expected public class AccessFixTest extends BaseMapTest { static class CauseBlockingSecurityManager extends SecurityManager { @Override public void checkPermission(Permission perm) throws SecurityException { if ("suppressAccessChecks".equals(perm.getName())) { throw new SecurityException("Can not force permission: "+perm); } } } // [databind#877]: avoid forcing access to `cause` field of `Throwable` // as it is never actually used (always call `initCause()` instead) public void testCauseOfThrowableIgnoral() throws Exception { final SecurityManager origSecMan = System.getSecurityManager(); try { System.setSecurityManager(new CauseBlockingSecurityManager()); _testCauseOfThrowableIgnoral(); } finally { System.setSecurityManager(origSecMan); } } private void _testCauseOfThrowableIgnoral() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS); IOException e = mapper.readValue("{}", IOException.class); assertNotNull(e); } }
// You are a professional Java test case writer, please create a test case named `testCauseOfThrowableIgnoral` for the issue `JacksonDatabind-877`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-877 // // ## Issue-Title: // @JsonIgnoreProperties: ignoring the "cause" property of Throwable on GAE // // ## Issue-Description: // Deserializing an exception class from json on Google App Engine causes this error: // // // // ``` // Caused by: java.lang.IllegalArgumentException: Can not access private java.lang.Throwable java.lang.Throwable.cause (from class java.lang.Throwable; failed to set access: java.lang.IllegalAccessException: Reflection is not allowed on private java.lang.Throwable java.lang.Throwable.cause // at com.fasterxml.jackson.databind.util.ClassUtil.checkAndFixAccess(ClassUtil.java:505) // at com.fasterxml.jackson.databind.introspect.AnnotatedMember.fixAccess(AnnotatedMember.java:123) // at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.constructSettableProperty(BeanDeserializerFactory.java:704) // at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.addBeanProps(BeanDeserializerFactory.java:501) // at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildThrowableDeserializer(BeanDeserializerFactory.java:356) // at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:114) // // ``` // // I tried preventing this by using `@JsonIgnoreProperties`: // // // // ``` // @JsonIgnoreProperties("cause") // public class MyException extends RuntimeException { ... } // ``` // // ... but the same error still occurs. What am I doing wrong? What else could I do? // // // I've also considered setting `MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS` to false, but I don't like this solution because I need this setting to be `true` in some other cases (in particular, I provide no-arg constructors for Jackson, but they should't be public in my API). // // // // public void testCauseOfThrowableIgnoral() throws Exception {
32
// as it is never actually used (always call `initCause()` instead) // [databind#877]: avoid forcing access to `cause` field of `Throwable`
58
23
src/test/java/com/fasterxml/jackson/databind/misc/AccessFixTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-877 ## Issue-Title: @JsonIgnoreProperties: ignoring the "cause" property of Throwable on GAE ## Issue-Description: Deserializing an exception class from json on Google App Engine causes this error: ``` Caused by: java.lang.IllegalArgumentException: Can not access private java.lang.Throwable java.lang.Throwable.cause (from class java.lang.Throwable; failed to set access: java.lang.IllegalAccessException: Reflection is not allowed on private java.lang.Throwable java.lang.Throwable.cause at com.fasterxml.jackson.databind.util.ClassUtil.checkAndFixAccess(ClassUtil.java:505) at com.fasterxml.jackson.databind.introspect.AnnotatedMember.fixAccess(AnnotatedMember.java:123) at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.constructSettableProperty(BeanDeserializerFactory.java:704) at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.addBeanProps(BeanDeserializerFactory.java:501) at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildThrowableDeserializer(BeanDeserializerFactory.java:356) at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:114) ``` I tried preventing this by using `@JsonIgnoreProperties`: ``` @JsonIgnoreProperties("cause") public class MyException extends RuntimeException { ... } ``` ... but the same error still occurs. What am I doing wrong? What else could I do? I've also considered setting `MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS` to false, but I don't like this solution because I need this setting to be `true` in some other cases (in particular, I provide no-arg constructors for Jackson, but they should't be public in my API). ``` You are a professional Java test case writer, please create a test case named `testCauseOfThrowableIgnoral` for the issue `JacksonDatabind-877`, utilizing the provided issue report information and the following function signature. ```java public void testCauseOfThrowableIgnoral() throws Exception { ```
23
[ "com.fasterxml.jackson.databind.deser.BeanDeserializerFactory" ]
0c321bf5e5a5b298337890281c78200331904ba91798249836158efdc396d20f
public void testCauseOfThrowableIgnoral() throws Exception
// You are a professional Java test case writer, please create a test case named `testCauseOfThrowableIgnoral` for the issue `JacksonDatabind-877`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-877 // // ## Issue-Title: // @JsonIgnoreProperties: ignoring the "cause" property of Throwable on GAE // // ## Issue-Description: // Deserializing an exception class from json on Google App Engine causes this error: // // // // ``` // Caused by: java.lang.IllegalArgumentException: Can not access private java.lang.Throwable java.lang.Throwable.cause (from class java.lang.Throwable; failed to set access: java.lang.IllegalAccessException: Reflection is not allowed on private java.lang.Throwable java.lang.Throwable.cause // at com.fasterxml.jackson.databind.util.ClassUtil.checkAndFixAccess(ClassUtil.java:505) // at com.fasterxml.jackson.databind.introspect.AnnotatedMember.fixAccess(AnnotatedMember.java:123) // at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.constructSettableProperty(BeanDeserializerFactory.java:704) // at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.addBeanProps(BeanDeserializerFactory.java:501) // at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildThrowableDeserializer(BeanDeserializerFactory.java:356) // at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:114) // // ``` // // I tried preventing this by using `@JsonIgnoreProperties`: // // // // ``` // @JsonIgnoreProperties("cause") // public class MyException extends RuntimeException { ... } // ``` // // ... but the same error still occurs. What am I doing wrong? What else could I do? // // // I've also considered setting `MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS` to false, but I don't like this solution because I need this setting to be `true` in some other cases (in particular, I provide no-arg constructors for Jackson, but they should't be public in my API). // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.misc; import java.io.IOException; import java.security.Permission; import com.fasterxml.jackson.databind.*; // Test(s) to verify that forced access works as expected public class AccessFixTest extends BaseMapTest { static class CauseBlockingSecurityManager extends SecurityManager { @Override public void checkPermission(Permission perm) throws SecurityException { if ("suppressAccessChecks".equals(perm.getName())) { throw new SecurityException("Can not force permission: "+perm); } } } // [databind#877]: avoid forcing access to `cause` field of `Throwable` // as it is never actually used (always call `initCause()` instead) public void testCauseOfThrowableIgnoral() throws Exception { final SecurityManager origSecMan = System.getSecurityManager(); try { System.setSecurityManager(new CauseBlockingSecurityManager()); _testCauseOfThrowableIgnoral(); } finally { System.setSecurityManager(origSecMan); } } private void _testCauseOfThrowableIgnoral() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS); IOException e = mapper.readValue("{}", IOException.class); assertNotNull(e); } }
public void testOffsetWithInputOffset() throws Exception { final JsonFactory f = new JsonFactory(); JsonLocation loc; JsonParser p; // 3 spaces before, 2 after, just for padding byte[] b = " { } ".getBytes("UTF-8"); // and then peel them off p = f.createParser(b, 3, b.length-5); assertToken(JsonToken.START_OBJECT, p.nextToken()); loc = p.getTokenLocation(); assertEquals(0L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(1, loc.getColumnNr()); loc = p.getCurrentLocation(); assertEquals(1L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(2, loc.getColumnNr()); p.close(); }
com.fasterxml.jackson.core.json.TestLocation::testOffsetWithInputOffset
src/test/java/com/fasterxml/jackson/core/json/TestLocation.java
79
src/test/java/com/fasterxml/jackson/core/json/TestLocation.java
testOffsetWithInputOffset
package com.fasterxml.jackson.core.json; import com.fasterxml.jackson.core.*; // NOTE: just a stub so for, fill me! public class TestLocation extends com.fasterxml.jackson.test.BaseTest { // Trivially simple unit test for basics wrt offsets public void testSimpleInitialOffsets() throws Exception { final JsonFactory f = new JsonFactory(); JsonLocation loc; JsonParser p; final String DOC = "{ }"; // first, char based: p = f.createParser(DOC); assertToken(JsonToken.START_OBJECT, p.nextToken()); loc = p.getTokenLocation(); assertEquals(-1L, loc.getByteOffset()); assertEquals(0L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(1, loc.getColumnNr()); loc = p.getCurrentLocation(); assertEquals(-1L, loc.getByteOffset()); assertEquals(1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(2, loc.getColumnNr()); p.close(); // then byte-based p = f.createParser(DOC.getBytes("UTF-8")); assertToken(JsonToken.START_OBJECT, p.nextToken()); loc = p.getTokenLocation(); assertEquals(0L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(1, loc.getColumnNr()); loc = p.getCurrentLocation(); assertEquals(1L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(2, loc.getColumnNr()); p.close(); } // for [Issue#111] public void testOffsetWithInputOffset() throws Exception { final JsonFactory f = new JsonFactory(); JsonLocation loc; JsonParser p; // 3 spaces before, 2 after, just for padding byte[] b = " { } ".getBytes("UTF-8"); // and then peel them off p = f.createParser(b, 3, b.length-5); assertToken(JsonToken.START_OBJECT, p.nextToken()); loc = p.getTokenLocation(); assertEquals(0L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(1, loc.getColumnNr()); loc = p.getCurrentLocation(); assertEquals(1L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(2, loc.getColumnNr()); p.close(); } }
// You are a professional Java test case writer, please create a test case named `testOffsetWithInputOffset` for the issue `JacksonCore-111`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-111 // // ## Issue-Title: // _currInputRowStart isn't initialized in UTF8StreamJsonParser() constructor. The column position will be wrong. // // ## Issue-Description: // The UTF8StreamJson Parser constructor allows to specify the start position. But it doesn't set the "\_currInputRowStart" as the same value. It is still 0. So when raise the exception, the column calculation (ParserBase.getCurrentLocation() )will be wrong. // // // int col = \_inputPtr - \_currInputRowStart + 1; // 1-based // // // public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, // // ObjectCodec codec, BytesToNameCanonicalizer sym, // // byte[] inputBuffer, int start, int end, // // boolean bufferRecyclable) // // // // public void testOffsetWithInputOffset() throws Exception {
79
// for [Issue#111]
3
54
src/test/java/com/fasterxml/jackson/core/json/TestLocation.java
src/test/java
```markdown ## Issue-ID: JacksonCore-111 ## Issue-Title: _currInputRowStart isn't initialized in UTF8StreamJsonParser() constructor. The column position will be wrong. ## Issue-Description: The UTF8StreamJson Parser constructor allows to specify the start position. But it doesn't set the "\_currInputRowStart" as the same value. It is still 0. So when raise the exception, the column calculation (ParserBase.getCurrentLocation() )will be wrong. int col = \_inputPtr - \_currInputRowStart + 1; // 1-based public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, ObjectCodec codec, BytesToNameCanonicalizer sym, byte[] inputBuffer, int start, int end, boolean bufferRecyclable) ``` You are a professional Java test case writer, please create a test case named `testOffsetWithInputOffset` for the issue `JacksonCore-111`, utilizing the provided issue report information and the following function signature. ```java public void testOffsetWithInputOffset() throws Exception { ```
54
[ "com.fasterxml.jackson.core.json.UTF8StreamJsonParser" ]
0c9c4815231007cb0481f58f73678fcf99ede10d957e82300e3b609e4623b460
public void testOffsetWithInputOffset() throws Exception
// You are a professional Java test case writer, please create a test case named `testOffsetWithInputOffset` for the issue `JacksonCore-111`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-111 // // ## Issue-Title: // _currInputRowStart isn't initialized in UTF8StreamJsonParser() constructor. The column position will be wrong. // // ## Issue-Description: // The UTF8StreamJson Parser constructor allows to specify the start position. But it doesn't set the "\_currInputRowStart" as the same value. It is still 0. So when raise the exception, the column calculation (ParserBase.getCurrentLocation() )will be wrong. // // // int col = \_inputPtr - \_currInputRowStart + 1; // 1-based // // // public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, // // ObjectCodec codec, BytesToNameCanonicalizer sym, // // byte[] inputBuffer, int start, int end, // // boolean bufferRecyclable) // // // //
JacksonCore
package com.fasterxml.jackson.core.json; import com.fasterxml.jackson.core.*; // NOTE: just a stub so for, fill me! public class TestLocation extends com.fasterxml.jackson.test.BaseTest { // Trivially simple unit test for basics wrt offsets public void testSimpleInitialOffsets() throws Exception { final JsonFactory f = new JsonFactory(); JsonLocation loc; JsonParser p; final String DOC = "{ }"; // first, char based: p = f.createParser(DOC); assertToken(JsonToken.START_OBJECT, p.nextToken()); loc = p.getTokenLocation(); assertEquals(-1L, loc.getByteOffset()); assertEquals(0L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(1, loc.getColumnNr()); loc = p.getCurrentLocation(); assertEquals(-1L, loc.getByteOffset()); assertEquals(1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(2, loc.getColumnNr()); p.close(); // then byte-based p = f.createParser(DOC.getBytes("UTF-8")); assertToken(JsonToken.START_OBJECT, p.nextToken()); loc = p.getTokenLocation(); assertEquals(0L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(1, loc.getColumnNr()); loc = p.getCurrentLocation(); assertEquals(1L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(2, loc.getColumnNr()); p.close(); } // for [Issue#111] public void testOffsetWithInputOffset() throws Exception { final JsonFactory f = new JsonFactory(); JsonLocation loc; JsonParser p; // 3 spaces before, 2 after, just for padding byte[] b = " { } ".getBytes("UTF-8"); // and then peel them off p = f.createParser(b, 3, b.length-5); assertToken(JsonToken.START_OBJECT, p.nextToken()); loc = p.getTokenLocation(); assertEquals(0L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(1, loc.getColumnNr()); loc = p.getCurrentLocation(); assertEquals(1L, loc.getByteOffset()); assertEquals(-1L, loc.getCharOffset()); assertEquals(1, loc.getLineNr()); assertEquals(2, loc.getColumnNr()); p.close(); } }
public void testMapToProperties() throws Exception { Bean bean = new Bean(); bean.A = 129; bean.B = "13"; Properties props = MAPPER.convertValue(bean, Properties.class); assertEquals(2, props.size()); assertEquals("13", props.getProperty("B")); // should coercce non-Strings to Strings assertEquals("129", props.getProperty("A")); }
com.fasterxml.jackson.databind.convert.TestMapConversions::testMapToProperties
src/test/java/com/fasterxml/jackson/databind/convert/TestMapConversions.java
113
src/test/java/com/fasterxml/jackson/databind/convert/TestMapConversions.java
testMapToProperties
package com.fasterxml.jackson.databind.convert; import java.util.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.util.StdConverter; public class TestMapConversions extends com.fasterxml.jackson.databind.BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); enum AB { A, B; } static class Bean { public Integer A; public String B; } // [Issue#287] @JsonSerialize(converter=RequestConverter.class) static class Request { public int x() { return 1; } } static class RequestConverter extends StdConverter<Request, Map<String,Object>> { @Override public Map<String,Object> convert(final Request value) { final Map<String, Object> test = new LinkedHashMap<String, Object>(); final Map<String, Object> innerTest = new LinkedHashMap<String, Object>(); innerTest.put("value", value.x()); test.put("hello", innerTest); return test; } } /* /********************************************************** /* Test methods /********************************************************** */ /** * Test that verifies that we can go between couple of types of Maps... */ public void testMapToMap() { Map<String,Integer> input = new LinkedHashMap<String,Integer>(); input.put("A", Integer.valueOf(3)); input.put("B", Integer.valueOf(-4)); Map<AB,String> output = MAPPER.convertValue(input, new TypeReference<Map<AB,String>>() { }); assertEquals(2, output.size()); assertEquals("3", output.get(AB.A)); assertEquals("-4", output.get(AB.B)); // Let's try the other way too... and mix up types a bit Map<String,Integer> roundtrip = MAPPER.convertValue(input, new TypeReference<TreeMap<String,Integer>>() { }); assertEquals(2, roundtrip.size()); assertEquals(Integer.valueOf(3), roundtrip.get("A")); assertEquals(Integer.valueOf(-4), roundtrip.get("B")); } public void testMapToBean() { EnumMap<AB,String> map = new EnumMap<AB,String>(AB.class); map.put(AB.A, " 17"); map.put(AB.B, " -1"); Bean bean = MAPPER.convertValue(map, Bean.class); assertEquals(Integer.valueOf(17), bean.A); assertEquals(" -1", bean.B); } public void testBeanToMap() { Bean bean = new Bean(); bean.A = 129; bean.B = "13"; EnumMap<AB,String> result = MAPPER.convertValue(bean, new TypeReference<EnumMap<AB,String>>() { }); assertEquals("129", result.get(AB.A)); assertEquals("13", result.get(AB.B)); } // [Issue#287]: Odd problems with `Object` type, static typing public void testIssue287() throws Exception { // use local instance to ensure no caching affects it: final ObjectMapper mapper = new ObjectMapper(); final Request request = new Request(); final String retString = mapper.writeValueAsString(request); assertEquals("{\"hello\":{\"value\":1}}",retString); } // [databind#810] public void testMapToProperties() throws Exception { Bean bean = new Bean(); bean.A = 129; bean.B = "13"; Properties props = MAPPER.convertValue(bean, Properties.class); assertEquals(2, props.size()); assertEquals("13", props.getProperty("B")); // should coercce non-Strings to Strings assertEquals("129", props.getProperty("A")); } }
// You are a professional Java test case writer, please create a test case named `testMapToProperties` for the issue `JacksonDatabind-810`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-810 // // ## Issue-Title: // Force value coercion for java.util.Properties, so that values are Strings // // ## Issue-Description: // Currently there is no custom handling for `java.util.Properties`, and although it is possible to use it (since it really is a `Map` under the hood), results are only good if values are already `String`s. // // The problem here is that `Properties` is actually declared as `Map<String,Object>`, probably due to backwards-compatibility constraints. // // // But Jackson should know better: perhaps by `TypeFactory` tweaking parameterizations a bit? // // // // public void testMapToProperties() throws Exception {
113
// [databind#810]
19
101
src/test/java/com/fasterxml/jackson/databind/convert/TestMapConversions.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-810 ## Issue-Title: Force value coercion for java.util.Properties, so that values are Strings ## Issue-Description: Currently there is no custom handling for `java.util.Properties`, and although it is possible to use it (since it really is a `Map` under the hood), results are only good if values are already `String`s. The problem here is that `Properties` is actually declared as `Map<String,Object>`, probably due to backwards-compatibility constraints. But Jackson should know better: perhaps by `TypeFactory` tweaking parameterizations a bit? ``` You are a professional Java test case writer, please create a test case named `testMapToProperties` for the issue `JacksonDatabind-810`, utilizing the provided issue report information and the following function signature. ```java public void testMapToProperties() throws Exception { ```
101
[ "com.fasterxml.jackson.databind.type.TypeFactory" ]
0cc038c14964d85eb2eb9e02db66d57cc6b055ec4a629f3b9049ab079f6d05e9
public void testMapToProperties() throws Exception
// You are a professional Java test case writer, please create a test case named `testMapToProperties` for the issue `JacksonDatabind-810`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-810 // // ## Issue-Title: // Force value coercion for java.util.Properties, so that values are Strings // // ## Issue-Description: // Currently there is no custom handling for `java.util.Properties`, and although it is possible to use it (since it really is a `Map` under the hood), results are only good if values are already `String`s. // // The problem here is that `Properties` is actually declared as `Map<String,Object>`, probably due to backwards-compatibility constraints. // // // But Jackson should know better: perhaps by `TypeFactory` tweaking parameterizations a bit? // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.convert; import java.util.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.util.StdConverter; public class TestMapConversions extends com.fasterxml.jackson.databind.BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); enum AB { A, B; } static class Bean { public Integer A; public String B; } // [Issue#287] @JsonSerialize(converter=RequestConverter.class) static class Request { public int x() { return 1; } } static class RequestConverter extends StdConverter<Request, Map<String,Object>> { @Override public Map<String,Object> convert(final Request value) { final Map<String, Object> test = new LinkedHashMap<String, Object>(); final Map<String, Object> innerTest = new LinkedHashMap<String, Object>(); innerTest.put("value", value.x()); test.put("hello", innerTest); return test; } } /* /********************************************************** /* Test methods /********************************************************** */ /** * Test that verifies that we can go between couple of types of Maps... */ public void testMapToMap() { Map<String,Integer> input = new LinkedHashMap<String,Integer>(); input.put("A", Integer.valueOf(3)); input.put("B", Integer.valueOf(-4)); Map<AB,String> output = MAPPER.convertValue(input, new TypeReference<Map<AB,String>>() { }); assertEquals(2, output.size()); assertEquals("3", output.get(AB.A)); assertEquals("-4", output.get(AB.B)); // Let's try the other way too... and mix up types a bit Map<String,Integer> roundtrip = MAPPER.convertValue(input, new TypeReference<TreeMap<String,Integer>>() { }); assertEquals(2, roundtrip.size()); assertEquals(Integer.valueOf(3), roundtrip.get("A")); assertEquals(Integer.valueOf(-4), roundtrip.get("B")); } public void testMapToBean() { EnumMap<AB,String> map = new EnumMap<AB,String>(AB.class); map.put(AB.A, " 17"); map.put(AB.B, " -1"); Bean bean = MAPPER.convertValue(map, Bean.class); assertEquals(Integer.valueOf(17), bean.A); assertEquals(" -1", bean.B); } public void testBeanToMap() { Bean bean = new Bean(); bean.A = 129; bean.B = "13"; EnumMap<AB,String> result = MAPPER.convertValue(bean, new TypeReference<EnumMap<AB,String>>() { }); assertEquals("129", result.get(AB.A)); assertEquals("13", result.get(AB.B)); } // [Issue#287]: Odd problems with `Object` type, static typing public void testIssue287() throws Exception { // use local instance to ensure no caching affects it: final ObjectMapper mapper = new ObjectMapper(); final Request request = new Request(); final String retString = mapper.writeValueAsString(request); assertEquals("{\"hello\":{\"value\":1}}",retString); } // [databind#810] public void testMapToProperties() throws Exception { Bean bean = new Bean(); bean.A = 129; bean.B = "13"; Properties props = MAPPER.convertValue(bean, Properties.class); assertEquals(2, props.size()); assertEquals("13", props.getProperty("B")); // should coercce non-Strings to Strings assertEquals("129", props.getProperty("A")); } }
public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); }
com.google.javascript.jscomp.TypeCheckTest::testGetprop4
test/com/google/javascript/jscomp/TypeCheckTest.java
3,930
test/com/google/javascript/jscomp/TypeCheckTest.java
testGetprop4
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.rhino.testing.Asserts.assertTypeEquals; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar)['x'];"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2);" + "}", "Property name2 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testGenerics1() throws Exception { String FN_DECL = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( FN_DECL + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void disable_testBackwardsInferenceGoogArrayFilter1() throws Exception { // TODO(johnlenz): this doesn't fail because any Array is regarded as // a subtype of any other array regardless of the type parameter. testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testGetprop4` for the issue `Closure-810`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-810 // // ## Issue-Title: // Record type invalid property not reported on function with @this annotation // // ## Issue-Description: // Code: // // var makeClass = function(protoMethods) { // var clazz = function() { // this.initialize.apply(this, arguments); // } // for (var i in protoMethods) { // clazz.prototype[i] = protoMethods[i]; // } // // return clazz; // } // // /\*\* // \* @constructor // \* @param {{name: string, height: number}} options // \*/ // var Person = function(options){}; // Person = makeClass(/\*\* @lends Person.prototype \*/ { // /\*\* // \* @this {Person} // \* @param {{name: string, height: number}} options // \*/ // initialize: function(options) { // /\*\* @type {string} \*/ this.name\_ = options.thisPropDoesNotExist; // }, // // /\*\* // \* @param {string} message // \* @this {Person} // \*/ // say: function(message) { // window.console.log(this.name\_ + ' says: ' + message); // } // }); // // // var joe = new Person({name: 'joe', height: 300}); // joe.say('hi'); // // // compiled with: // java -jar build/compiler.jar --formatting=PRETTY\_PRINT --jscomp\_error=checkTypes --jscomp\_error=externsValidation --compilation\_level=SIMPLE\_OPTIMIZATIONS repro.js // // // I would expect an error on this line: // /\*\* @type {string} \*/ this.name\_ = options.thisPropDoesNotExist; // // which works in other contexts. // // Thanks! // // public void testGetprop4() throws Exception {
3,930
11
3,925
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-810 ## Issue-Title: Record type invalid property not reported on function with @this annotation ## Issue-Description: Code: var makeClass = function(protoMethods) { var clazz = function() { this.initialize.apply(this, arguments); } for (var i in protoMethods) { clazz.prototype[i] = protoMethods[i]; } return clazz; } /\*\* \* @constructor \* @param {{name: string, height: number}} options \*/ var Person = function(options){}; Person = makeClass(/\*\* @lends Person.prototype \*/ { /\*\* \* @this {Person} \* @param {{name: string, height: number}} options \*/ initialize: function(options) { /\*\* @type {string} \*/ this.name\_ = options.thisPropDoesNotExist; }, /\*\* \* @param {string} message \* @this {Person} \*/ say: function(message) { window.console.log(this.name\_ + ' says: ' + message); } }); var joe = new Person({name: 'joe', height: 300}); joe.say('hi'); compiled with: java -jar build/compiler.jar --formatting=PRETTY\_PRINT --jscomp\_error=checkTypes --jscomp\_error=externsValidation --compilation\_level=SIMPLE\_OPTIMIZATIONS repro.js I would expect an error on this line: /\*\* @type {string} \*/ this.name\_ = options.thisPropDoesNotExist; which works in other contexts. Thanks! ``` You are a professional Java test case writer, please create a test case named `testGetprop4` for the issue `Closure-810`, utilizing the provided issue report information and the following function signature. ```java public void testGetprop4() throws Exception { ```
3,925
[ "com.google.javascript.jscomp.TypeCheck" ]
0d6678696c911b9ae38c26f9ee00702e7b83d41b3a130f91b31408e84639cbb6
public void testGetprop4() throws Exception
// You are a professional Java test case writer, please create a test case named `testGetprop4` for the issue `Closure-810`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-810 // // ## Issue-Title: // Record type invalid property not reported on function with @this annotation // // ## Issue-Description: // Code: // // var makeClass = function(protoMethods) { // var clazz = function() { // this.initialize.apply(this, arguments); // } // for (var i in protoMethods) { // clazz.prototype[i] = protoMethods[i]; // } // // return clazz; // } // // /\*\* // \* @constructor // \* @param {{name: string, height: number}} options // \*/ // var Person = function(options){}; // Person = makeClass(/\*\* @lends Person.prototype \*/ { // /\*\* // \* @this {Person} // \* @param {{name: string, height: number}} options // \*/ // initialize: function(options) { // /\*\* @type {string} \*/ this.name\_ = options.thisPropDoesNotExist; // }, // // /\*\* // \* @param {string} message // \* @this {Person} // \*/ // say: function(message) { // window.console.log(this.name\_ + ' says: ' + message); // } // }); // // // var joe = new Person({name: 'joe', height: 300}); // joe.say('hi'); // // // compiled with: // java -jar build/compiler.jar --formatting=PRETTY\_PRINT --jscomp\_error=checkTypes --jscomp\_error=externsValidation --compilation\_level=SIMPLE\_OPTIMIZATIONS repro.js // // // I would expect an error on this line: // /\*\* @type {string} \*/ this.name\_ = options.thisPropDoesNotExist; // // which works in other contexts. // // Thanks! // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.rhino.testing.Asserts.assertTypeEquals; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar)['x'];"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2);" + "}", "Property name2 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testGenerics1() throws Exception { String FN_DECL = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( FN_DECL + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void disable_testBackwardsInferenceGoogArrayFilter1() throws Exception { // TODO(johnlenz): this doesn't fail because any Array is regarded as // a subtype of any other array regardless of the type parameter. testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
public void testNumberAsStringDeserialization() { Number value = gson.fromJson("\"18\"", Number.class); assertEquals(18, value.intValue()); }
com.google.gson.functional.PrimitiveTest::testNumberAsStringDeserialization
gson/src/test/java/com/google/gson/functional/PrimitiveTest.java
163
gson/src/test/java/com/google/gson/functional/PrimitiveTest.java
testNumberAsStringDeserialization
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.functional; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.google.gson.LongSerializationPolicy; import com.google.gson.reflect.TypeToken; import java.io.Serializable; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; /** * Functional tests for Json primitive values: integers, and floating point numbers. * * @author Inderjeet Singh * @author Joel Leitch */ public class PrimitiveTest extends TestCase { private Gson gson; @Override protected void setUp() throws Exception { super.setUp(); gson = new Gson(); } public void testPrimitiveIntegerAutoboxedSerialization() { assertEquals("1", gson.toJson(1)); } public void testPrimitiveIntegerAutoboxedDeserialization() { int expected = 1; int actual = gson.fromJson("1", int.class); assertEquals(expected, actual); actual = gson.fromJson("1", Integer.class); assertEquals(expected, actual); } public void testByteSerialization() { assertEquals("1", gson.toJson(1, byte.class)); assertEquals("1", gson.toJson(1, Byte.class)); } public void testShortSerialization() { assertEquals("1", gson.toJson(1, short.class)); assertEquals("1", gson.toJson(1, Short.class)); } public void testByteDeserialization() { Byte target = gson.fromJson("1", Byte.class); assertEquals(1, (byte)target); byte primitive = gson.fromJson("1", byte.class); assertEquals(1, primitive); } public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() { int target[] = {-9332}; assertEquals("[-9332]", gson.toJson(target)); assertEquals("[-9332]", gson.toJson(target, int[].class)); assertEquals("[-9332]", gson.toJson(target, Integer[].class)); } public void testReallyLongValuesSerialization() { long value = 333961828784581L; assertEquals("333961828784581", gson.toJson(value)); } public void testReallyLongValuesDeserialization() { String json = "333961828784581"; long value = gson.fromJson(json, Long.class); assertEquals(333961828784581L, value); } public void testPrimitiveLongAutoboxedSerialization() { assertEquals("1", gson.toJson(1L, long.class)); assertEquals("1", gson.toJson(1L, Long.class)); } public void testPrimitiveLongAutoboxedDeserialization() { long expected = 1L; long actual = gson.fromJson("1", long.class); assertEquals(expected, actual); actual = gson.fromJson("1", Long.class); assertEquals(expected, actual); } public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() { long[] target = {-23L}; assertEquals("[-23]", gson.toJson(target)); assertEquals("[-23]", gson.toJson(target, long[].class)); assertEquals("[-23]", gson.toJson(target, Long[].class)); } public void testPrimitiveBooleanAutoboxedSerialization() { assertEquals("true", gson.toJson(true)); assertEquals("false", gson.toJson(false)); } public void testBooleanDeserialization() { boolean value = gson.fromJson("false", boolean.class); assertEquals(false, value); value = gson.fromJson("true", boolean.class); assertEquals(true, value); } public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() { boolean target[] = {false}; assertEquals("[false]", gson.toJson(target)); assertEquals("[false]", gson.toJson(target, boolean[].class)); assertEquals("[false]", gson.toJson(target, Boolean[].class)); } public void testNumberSerialization() { Number expected = 1L; String json = gson.toJson(expected); assertEquals(expected.toString(), json); json = gson.toJson(expected, Number.class); assertEquals(expected.toString(), json); } public void testNumberDeserialization() { String json = "1"; Number expected = new Integer(json); Number actual = gson.fromJson(json, Number.class); assertEquals(expected.intValue(), actual.intValue()); json = String.valueOf(Long.MAX_VALUE); expected = new Long(json); actual = gson.fromJson(json, Number.class); assertEquals(expected.longValue(), actual.longValue()); json = "1.0"; actual = gson.fromJson(json, Number.class); assertEquals(1L, actual.longValue()); } public void testNumberAsStringDeserialization() { Number value = gson.fromJson("\"18\"", Number.class); assertEquals(18, value.intValue()); } public void testPrimitiveDoubleAutoboxedSerialization() { assertEquals("-122.08234335", gson.toJson(-122.08234335)); assertEquals("122.08112002", gson.toJson(new Double(122.08112002))); } public void testPrimitiveDoubleAutoboxedDeserialization() { double actual = gson.fromJson("-122.08858585", double.class); assertEquals(-122.08858585, actual); actual = gson.fromJson("122.023900008000", Double.class); assertEquals(122.023900008, actual); } public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() { double[] target = {-122.08D}; assertEquals("[-122.08]", gson.toJson(target)); assertEquals("[-122.08]", gson.toJson(target, double[].class)); assertEquals("[-122.08]", gson.toJson(target, Double[].class)); } public void testDoubleAsStringRepresentationDeserialization() { String doubleValue = "1.0043E+5"; Double expected = Double.valueOf(doubleValue); Double actual = gson.fromJson(doubleValue, Double.class); assertEquals(expected, actual); double actual1 = gson.fromJson(doubleValue, double.class); assertEquals(expected.doubleValue(), actual1); } public void testDoubleNoFractAsStringRepresentationDeserialization() { String doubleValue = "1E+5"; Double expected = Double.valueOf(doubleValue); Double actual = gson.fromJson(doubleValue, Double.class); assertEquals(expected, actual); double actual1 = gson.fromJson(doubleValue, double.class); assertEquals(expected.doubleValue(), actual1); } public void testDoubleArrayDeserialization() { String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4," + "0.0011904761904761906, 0.0]"; double[] values = gson.fromJson(json, double[].class); assertEquals(6, values.length); assertEquals(0.0, values[0]); assertEquals(0.004761904761904762, values[1]); assertEquals(3.4013606962703525E-4, values[2]); assertEquals(7.936508173034305E-4, values[3]); assertEquals(0.0011904761904761906, values[4]); assertEquals(0.0, values[5]); } public void testLargeDoubleDeserialization() { String doubleValue = "1.234567899E8"; Double expected = Double.valueOf(doubleValue); Double actual = gson.fromJson(doubleValue, Double.class); assertEquals(expected, actual); double actual1 = gson.fromJson(doubleValue, double.class); assertEquals(expected.doubleValue(), actual1); } public void testBigDecimalSerialization() { BigDecimal target = new BigDecimal("-122.0e-21"); String json = gson.toJson(target); assertEquals(target, new BigDecimal(json)); } public void testBigDecimalDeserialization() { BigDecimal target = new BigDecimal("-122.0e-21"); String json = "-122.0e-21"; assertEquals(target, gson.fromJson(json, BigDecimal.class)); } public void testBigDecimalInASingleElementArraySerialization() { BigDecimal[] target = {new BigDecimal("-122.08e-21")}; String json = gson.toJson(target); String actual = extractElementFromArray(json); assertEquals(target[0], new BigDecimal(actual)); json = gson.toJson(target, BigDecimal[].class); actual = extractElementFromArray(json); assertEquals(target[0], new BigDecimal(actual)); } public void testSmallValueForBigDecimalSerialization() { BigDecimal target = new BigDecimal("1.55"); String actual = gson.toJson(target); assertEquals(target.toString(), actual); } public void testSmallValueForBigDecimalDeserialization() { BigDecimal expected = new BigDecimal("1.55"); BigDecimal actual = gson.fromJson("1.55", BigDecimal.class); assertEquals(expected, actual); } public void testBigDecimalPreservePrecisionSerialization() { String expectedValue = "1.000"; BigDecimal obj = new BigDecimal(expectedValue); String actualValue = gson.toJson(obj); assertEquals(expectedValue, actualValue); } public void testBigDecimalPreservePrecisionDeserialization() { String json = "1.000"; BigDecimal expected = new BigDecimal(json); BigDecimal actual = gson.fromJson(json, BigDecimal.class); assertEquals(expected, actual); } public void testBigDecimalAsStringRepresentationDeserialization() { String doubleValue = "0.05E+5"; BigDecimal expected = new BigDecimal(doubleValue); BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class); assertEquals(expected, actual); } public void testBigDecimalNoFractAsStringRepresentationDeserialization() { String doubleValue = "5E+5"; BigDecimal expected = new BigDecimal(doubleValue); BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class); assertEquals(expected, actual); } public void testBigIntegerSerialization() { BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435"); assertEquals(target.toString(), gson.toJson(target)); } public void testBigIntegerDeserialization() { String json = "12121211243123245845384534687435634558945453489543985435"; BigInteger target = new BigInteger(json); assertEquals(target, gson.fromJson(json, BigInteger.class)); } public void testBigIntegerInASingleElementArraySerialization() { BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")}; String json = gson.toJson(target); String actual = extractElementFromArray(json); assertEquals(target[0], new BigInteger(actual)); json = gson.toJson(target, BigInteger[].class); actual = extractElementFromArray(json); assertEquals(target[0], new BigInteger(actual)); } public void testSmallValueForBigIntegerSerialization() { BigInteger target = new BigInteger("15"); String actual = gson.toJson(target); assertEquals(target.toString(), actual); } public void testSmallValueForBigIntegerDeserialization() { BigInteger expected = new BigInteger("15"); BigInteger actual = gson.fromJson("15", BigInteger.class); assertEquals(expected, actual); } public void testBadValueForBigIntegerDeserialization() { try { gson.fromJson("15.099", BigInteger.class); fail("BigInteger can not be decimal values."); } catch (JsonSyntaxException expected) { } } public void testMoreSpecificSerialization() { Gson gson = new Gson(); String expected = "This is a string"; String expectedJson = gson.toJson(expected); Serializable serializableString = expected; String actualJson = gson.toJson(serializableString, Serializable.class); assertFalse(expectedJson.equals(actualJson)); } private String extractElementFromArray(String json) { return json.substring(json.indexOf('[') + 1, json.indexOf(']')); } public void testDoubleNaNSerializationNotSupportedByDefault() { try { double nan = Double.NaN; gson.toJson(nan); fail("Gson should not accept NaN for serialization"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Double.NaN); fail("Gson should not accept NaN for serialization"); } catch (IllegalArgumentException expected) { } } public void testDoubleNaNSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); double nan = Double.NaN; assertEquals("NaN", gson.toJson(nan)); assertEquals("NaN", gson.toJson(Double.NaN)); } public void testDoubleNaNDeserialization() { assertTrue(Double.isNaN(gson.fromJson("NaN", Double.class))); assertTrue(Double.isNaN(gson.fromJson("NaN", double.class))); } public void testFloatNaNSerializationNotSupportedByDefault() { try { float nan = Float.NaN; gson.toJson(nan); fail("Gson should not accept NaN for serialization"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Float.NaN); fail("Gson should not accept NaN for serialization"); } catch (IllegalArgumentException expected) { } } public void testFloatNaNSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); float nan = Float.NaN; assertEquals("NaN", gson.toJson(nan)); assertEquals("NaN", gson.toJson(Float.NaN)); } public void testFloatNaNDeserialization() { assertTrue(Float.isNaN(gson.fromJson("NaN", Float.class))); assertTrue(Float.isNaN(gson.fromJson("NaN", float.class))); } public void testBigDecimalNaNDeserializationNotSupported() { try { gson.fromJson("NaN", BigDecimal.class); fail("Gson should not accept NaN for deserialization by default."); } catch (JsonSyntaxException expected) { } } public void testDoubleInfinitySerializationNotSupportedByDefault() { try { double infinity = Double.POSITIVE_INFINITY; gson.toJson(infinity); fail("Gson should not accept positive infinity for serialization by default."); } catch (IllegalArgumentException expected) { } try { gson.toJson(Double.POSITIVE_INFINITY); fail("Gson should not accept positive infinity for serialization by default."); } catch (IllegalArgumentException expected) { } } public void testDoubleInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); double infinity = Double.POSITIVE_INFINITY; assertEquals("Infinity", gson.toJson(infinity)); assertEquals("Infinity", gson.toJson(Double.POSITIVE_INFINITY)); } public void testDoubleInfinityDeserialization() { assertTrue(Double.isInfinite(gson.fromJson("Infinity", Double.class))); assertTrue(Double.isInfinite(gson.fromJson("Infinity", double.class))); } public void testFloatInfinitySerializationNotSupportedByDefault() { try { float infinity = Float.POSITIVE_INFINITY; gson.toJson(infinity); fail("Gson should not accept positive infinity for serialization by default"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Float.POSITIVE_INFINITY); fail("Gson should not accept positive infinity for serialization by default"); } catch (IllegalArgumentException expected) { } } public void testFloatInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); float infinity = Float.POSITIVE_INFINITY; assertEquals("Infinity", gson.toJson(infinity)); assertEquals("Infinity", gson.toJson(Float.POSITIVE_INFINITY)); } public void testFloatInfinityDeserialization() { assertTrue(Float.isInfinite(gson.fromJson("Infinity", Float.class))); assertTrue(Float.isInfinite(gson.fromJson("Infinity", float.class))); } public void testBigDecimalInfinityDeserializationNotSupported() { try { gson.fromJson("Infinity", BigDecimal.class); fail("Gson should not accept positive infinity for deserialization with BigDecimal"); } catch (JsonSyntaxException expected) { } } public void testNegativeInfinitySerializationNotSupportedByDefault() { try { double negativeInfinity = Double.NEGATIVE_INFINITY; gson.toJson(negativeInfinity); fail("Gson should not accept negative infinity for serialization by default"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Double.NEGATIVE_INFINITY); fail("Gson should not accept negative infinity for serialization by default"); } catch (IllegalArgumentException expected) { } } public void testNegativeInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); double negativeInfinity = Double.NEGATIVE_INFINITY; assertEquals("-Infinity", gson.toJson(negativeInfinity)); assertEquals("-Infinity", gson.toJson(Double.NEGATIVE_INFINITY)); } public void testNegativeInfinityDeserialization() { assertTrue(Double.isInfinite(gson.fromJson("-Infinity", double.class))); assertTrue(Double.isInfinite(gson.fromJson("-Infinity", Double.class))); } public void testNegativeInfinityFloatSerializationNotSupportedByDefault() { try { float negativeInfinity = Float.NEGATIVE_INFINITY; gson.toJson(negativeInfinity); fail("Gson should not accept negative infinity for serialization by default"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Float.NEGATIVE_INFINITY); fail("Gson should not accept negative infinity for serialization by default"); } catch (IllegalArgumentException expected) { } } public void testNegativeInfinityFloatSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); float negativeInfinity = Float.NEGATIVE_INFINITY; assertEquals("-Infinity", gson.toJson(negativeInfinity)); assertEquals("-Infinity", gson.toJson(Float.NEGATIVE_INFINITY)); } public void testNegativeInfinityFloatDeserialization() { assertTrue(Float.isInfinite(gson.fromJson("-Infinity", float.class))); assertTrue(Float.isInfinite(gson.fromJson("-Infinity", Float.class))); } public void testBigDecimalNegativeInfinityDeserializationNotSupported() { try { gson.fromJson("-Infinity", BigDecimal.class); fail("Gson should not accept positive infinity for deserialization"); } catch (JsonSyntaxException expected) { } } public void testLongAsStringSerialization() throws Exception { gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); String result = gson.toJson(15L); assertEquals("\"15\"", result); // Test with an integer and ensure its still a number result = gson.toJson(2); assertEquals("2", result); } public void testLongAsStringDeserialization() throws Exception { long value = gson.fromJson("\"15\"", long.class); assertEquals(15, value); gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); value = gson.fromJson("\"25\"", long.class); assertEquals(25, value); } public void testQuotedStringSerializationAndDeserialization() throws Exception { String value = "String Blah Blah Blah...1, 2, 3"; String serializedForm = gson.toJson(value); assertEquals("\"" + value + "\"", serializedForm); String actual = gson.fromJson(serializedForm, String.class); assertEquals(value, actual); } public void testUnquotedStringDeserializationFails() throws Exception { assertEquals("UnquotedSingleWord", gson.fromJson("UnquotedSingleWord", String.class)); String value = "String Blah Blah Blah...1, 2, 3"; try { gson.fromJson(value, String.class); fail(); } catch (JsonSyntaxException expected) { } } public void testHtmlCharacterSerialization() throws Exception { String target = "<script>var a = 12;</script>"; String result = gson.toJson(target); assertFalse(result.equals('"' + target + '"')); gson = new GsonBuilder().disableHtmlEscaping().create(); result = gson.toJson(target); assertTrue(result.equals('"' + target + '"')); } public void testDeserializePrimitiveWrapperAsObjectField() { String json = "{i:10}"; ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class); assertEquals(10, target.i.intValue()); } private static class ClassWithIntegerField { Integer i; } public void testPrimitiveClassLiteral() { assertEquals(1, gson.fromJson("1", int.class).intValue()); assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue()); assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue()); } public void testDeserializeJsonObjectAsLongPrimitive() { try { gson.fromJson("{'abc':1}", long.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsLongWrapper() { try { gson.fromJson("[1,2,3]", Long.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsInt() { try { gson.fromJson("[1, 2, 3, 4]", int.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsInteger() { try { gson.fromJson("{}", Integer.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsShortPrimitive() { try { gson.fromJson("{'abc':1}", short.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsShortWrapper() { try { gson.fromJson("['a','b']", Short.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsDoublePrimitive() { try { gson.fromJson("[1,2]", double.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsDoubleWrapper() { try { gson.fromJson("{'abc':1}", Double.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsFloatPrimitive() { try { gson.fromJson("{'abc':1}", float.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsFloatWrapper() { try { gson.fromJson("[1,2,3]", Float.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsBytePrimitive() { try { gson.fromJson("{'abc':1}", byte.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsByteWrapper() { try { gson.fromJson("[1,2,3,4]", Byte.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsBooleanPrimitive() { try { gson.fromJson("{'abc':1}", boolean.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsBooleanWrapper() { try { gson.fromJson("[1,2,3,4]", Boolean.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsBigDecimal() { try { gson.fromJson("[1,2,3,4]", BigDecimal.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsBigDecimal() { try { gson.fromJson("{'a':1}", BigDecimal.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsBigInteger() { try { gson.fromJson("[1,2,3,4]", BigInteger.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsBigInteger() { try { gson.fromJson("{'c':2}", BigInteger.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsNumber() { try { gson.fromJson("[1,2,3,4]", Number.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsNumber() { try { gson.fromJson("{'c':2}", Number.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializingDecimalPointValueZeroSucceeds() { assertEquals(1, (int) gson.fromJson("1.0", Integer.class)); } public void testDeserializingNonZeroDecimalPointValuesAsIntegerFails() { try { gson.fromJson("1.02", Byte.class); fail(); } catch (JsonSyntaxException expected) { } try { gson.fromJson("1.02", Short.class); fail(); } catch (JsonSyntaxException expected) { } try { gson.fromJson("1.02", Integer.class); fail(); } catch (JsonSyntaxException expected) { } try { gson.fromJson("1.02", Long.class); fail(); } catch (JsonSyntaxException expected) { } } public void testDeserializingBigDecimalAsIntegerFails() { try { gson.fromJson("-122.08e-213", Integer.class); fail(); } catch (JsonSyntaxException expected) { } } public void testDeserializingBigIntegerAsInteger() { try { gson.fromJson("12121211243123245845384534687435634558945453489543985435", Integer.class); fail(); } catch (JsonSyntaxException expected) { } } public void testDeserializingBigIntegerAsLong() { try { gson.fromJson("12121211243123245845384534687435634558945453489543985435", Long.class); fail(); } catch (JsonSyntaxException expected) { } } public void testValueVeryCloseToZeroIsZero() { assertEquals(0, (byte) gson.fromJson("-122.08e-2132", byte.class)); assertEquals(0, (short) gson.fromJson("-122.08e-2132", short.class)); assertEquals(0, (int) gson.fromJson("-122.08e-2132", int.class)); assertEquals(0, (long) gson.fromJson("-122.08e-2132", long.class)); assertEquals(-0.0f, gson.fromJson("-122.08e-2132", float.class)); assertEquals(-0.0, gson.fromJson("-122.08e-2132", double.class)); assertEquals(0.0f, gson.fromJson("122.08e-2132", float.class)); assertEquals(0.0, gson.fromJson("122.08e-2132", double.class)); } public void testDeserializingBigDecimalAsFloat() { String json = "-122.08e-2132332"; float actual = gson.fromJson(json, float.class); assertEquals(-0.0f, actual); } public void testDeserializingBigDecimalAsDouble() { String json = "-122.08e-2132332"; double actual = gson.fromJson(json, double.class); assertEquals(-0.0d, actual); } public void testDeserializingBigDecimalAsBigIntegerFails() { try { gson.fromJson("-122.08e-213", BigInteger.class); fail(); } catch (JsonSyntaxException expected) { } } public void testDeserializingBigIntegerAsBigDecimal() { BigDecimal actual = gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class); assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString()); } public void testStringsAsBooleans() { String json = "['true', 'false', 'TRUE', 'yes', '1']"; assertEquals(Arrays.asList(true, false, true, false, false), gson.<List<Boolean>>fromJson(json, new TypeToken<List<Boolean>>() {}.getType())); } }
// You are a professional Java test case writer, please create a test case named `testNumberAsStringDeserialization` for the issue `Gson-964`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-964 // // ## Issue-Title: // Allow deserialization of a Number represented as a String // // ## Issue-Description: // This works: // // // // ``` // gson.fromJson("\"15\"", int.class) // // ``` // // This doesn't: // // // // ``` // gson.fromJson("\"15\"", Number.class) // // ``` // // This PR makes it so the second case works too. // // // // public void testNumberAsStringDeserialization() {
163
11
160
gson/src/test/java/com/google/gson/functional/PrimitiveTest.java
gson/src/test/java
```markdown ## Issue-ID: Gson-964 ## Issue-Title: Allow deserialization of a Number represented as a String ## Issue-Description: This works: ``` gson.fromJson("\"15\"", int.class) ``` This doesn't: ``` gson.fromJson("\"15\"", Number.class) ``` This PR makes it so the second case works too. ``` You are a professional Java test case writer, please create a test case named `testNumberAsStringDeserialization` for the issue `Gson-964`, utilizing the provided issue report information and the following function signature. ```java public void testNumberAsStringDeserialization() { ```
160
[ "com.google.gson.internal.bind.TypeAdapters" ]
0d9b16bc3594690dc6a4d30050f52a520430c540d44ff39a4e60a10c232357e6
public void testNumberAsStringDeserialization()
// You are a professional Java test case writer, please create a test case named `testNumberAsStringDeserialization` for the issue `Gson-964`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-964 // // ## Issue-Title: // Allow deserialization of a Number represented as a String // // ## Issue-Description: // This works: // // // // ``` // gson.fromJson("\"15\"", int.class) // // ``` // // This doesn't: // // // // ``` // gson.fromJson("\"15\"", Number.class) // // ``` // // This PR makes it so the second case works too. // // // //
Gson
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.functional; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.google.gson.LongSerializationPolicy; import com.google.gson.reflect.TypeToken; import java.io.Serializable; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; /** * Functional tests for Json primitive values: integers, and floating point numbers. * * @author Inderjeet Singh * @author Joel Leitch */ public class PrimitiveTest extends TestCase { private Gson gson; @Override protected void setUp() throws Exception { super.setUp(); gson = new Gson(); } public void testPrimitiveIntegerAutoboxedSerialization() { assertEquals("1", gson.toJson(1)); } public void testPrimitiveIntegerAutoboxedDeserialization() { int expected = 1; int actual = gson.fromJson("1", int.class); assertEquals(expected, actual); actual = gson.fromJson("1", Integer.class); assertEquals(expected, actual); } public void testByteSerialization() { assertEquals("1", gson.toJson(1, byte.class)); assertEquals("1", gson.toJson(1, Byte.class)); } public void testShortSerialization() { assertEquals("1", gson.toJson(1, short.class)); assertEquals("1", gson.toJson(1, Short.class)); } public void testByteDeserialization() { Byte target = gson.fromJson("1", Byte.class); assertEquals(1, (byte)target); byte primitive = gson.fromJson("1", byte.class); assertEquals(1, primitive); } public void testPrimitiveIntegerAutoboxedInASingleElementArraySerialization() { int target[] = {-9332}; assertEquals("[-9332]", gson.toJson(target)); assertEquals("[-9332]", gson.toJson(target, int[].class)); assertEquals("[-9332]", gson.toJson(target, Integer[].class)); } public void testReallyLongValuesSerialization() { long value = 333961828784581L; assertEquals("333961828784581", gson.toJson(value)); } public void testReallyLongValuesDeserialization() { String json = "333961828784581"; long value = gson.fromJson(json, Long.class); assertEquals(333961828784581L, value); } public void testPrimitiveLongAutoboxedSerialization() { assertEquals("1", gson.toJson(1L, long.class)); assertEquals("1", gson.toJson(1L, Long.class)); } public void testPrimitiveLongAutoboxedDeserialization() { long expected = 1L; long actual = gson.fromJson("1", long.class); assertEquals(expected, actual); actual = gson.fromJson("1", Long.class); assertEquals(expected, actual); } public void testPrimitiveLongAutoboxedInASingleElementArraySerialization() { long[] target = {-23L}; assertEquals("[-23]", gson.toJson(target)); assertEquals("[-23]", gson.toJson(target, long[].class)); assertEquals("[-23]", gson.toJson(target, Long[].class)); } public void testPrimitiveBooleanAutoboxedSerialization() { assertEquals("true", gson.toJson(true)); assertEquals("false", gson.toJson(false)); } public void testBooleanDeserialization() { boolean value = gson.fromJson("false", boolean.class); assertEquals(false, value); value = gson.fromJson("true", boolean.class); assertEquals(true, value); } public void testPrimitiveBooleanAutoboxedInASingleElementArraySerialization() { boolean target[] = {false}; assertEquals("[false]", gson.toJson(target)); assertEquals("[false]", gson.toJson(target, boolean[].class)); assertEquals("[false]", gson.toJson(target, Boolean[].class)); } public void testNumberSerialization() { Number expected = 1L; String json = gson.toJson(expected); assertEquals(expected.toString(), json); json = gson.toJson(expected, Number.class); assertEquals(expected.toString(), json); } public void testNumberDeserialization() { String json = "1"; Number expected = new Integer(json); Number actual = gson.fromJson(json, Number.class); assertEquals(expected.intValue(), actual.intValue()); json = String.valueOf(Long.MAX_VALUE); expected = new Long(json); actual = gson.fromJson(json, Number.class); assertEquals(expected.longValue(), actual.longValue()); json = "1.0"; actual = gson.fromJson(json, Number.class); assertEquals(1L, actual.longValue()); } public void testNumberAsStringDeserialization() { Number value = gson.fromJson("\"18\"", Number.class); assertEquals(18, value.intValue()); } public void testPrimitiveDoubleAutoboxedSerialization() { assertEquals("-122.08234335", gson.toJson(-122.08234335)); assertEquals("122.08112002", gson.toJson(new Double(122.08112002))); } public void testPrimitiveDoubleAutoboxedDeserialization() { double actual = gson.fromJson("-122.08858585", double.class); assertEquals(-122.08858585, actual); actual = gson.fromJson("122.023900008000", Double.class); assertEquals(122.023900008, actual); } public void testPrimitiveDoubleAutoboxedInASingleElementArraySerialization() { double[] target = {-122.08D}; assertEquals("[-122.08]", gson.toJson(target)); assertEquals("[-122.08]", gson.toJson(target, double[].class)); assertEquals("[-122.08]", gson.toJson(target, Double[].class)); } public void testDoubleAsStringRepresentationDeserialization() { String doubleValue = "1.0043E+5"; Double expected = Double.valueOf(doubleValue); Double actual = gson.fromJson(doubleValue, Double.class); assertEquals(expected, actual); double actual1 = gson.fromJson(doubleValue, double.class); assertEquals(expected.doubleValue(), actual1); } public void testDoubleNoFractAsStringRepresentationDeserialization() { String doubleValue = "1E+5"; Double expected = Double.valueOf(doubleValue); Double actual = gson.fromJson(doubleValue, Double.class); assertEquals(expected, actual); double actual1 = gson.fromJson(doubleValue, double.class); assertEquals(expected.doubleValue(), actual1); } public void testDoubleArrayDeserialization() { String json = "[0.0, 0.004761904761904762, 3.4013606962703525E-4, 7.936508173034305E-4," + "0.0011904761904761906, 0.0]"; double[] values = gson.fromJson(json, double[].class); assertEquals(6, values.length); assertEquals(0.0, values[0]); assertEquals(0.004761904761904762, values[1]); assertEquals(3.4013606962703525E-4, values[2]); assertEquals(7.936508173034305E-4, values[3]); assertEquals(0.0011904761904761906, values[4]); assertEquals(0.0, values[5]); } public void testLargeDoubleDeserialization() { String doubleValue = "1.234567899E8"; Double expected = Double.valueOf(doubleValue); Double actual = gson.fromJson(doubleValue, Double.class); assertEquals(expected, actual); double actual1 = gson.fromJson(doubleValue, double.class); assertEquals(expected.doubleValue(), actual1); } public void testBigDecimalSerialization() { BigDecimal target = new BigDecimal("-122.0e-21"); String json = gson.toJson(target); assertEquals(target, new BigDecimal(json)); } public void testBigDecimalDeserialization() { BigDecimal target = new BigDecimal("-122.0e-21"); String json = "-122.0e-21"; assertEquals(target, gson.fromJson(json, BigDecimal.class)); } public void testBigDecimalInASingleElementArraySerialization() { BigDecimal[] target = {new BigDecimal("-122.08e-21")}; String json = gson.toJson(target); String actual = extractElementFromArray(json); assertEquals(target[0], new BigDecimal(actual)); json = gson.toJson(target, BigDecimal[].class); actual = extractElementFromArray(json); assertEquals(target[0], new BigDecimal(actual)); } public void testSmallValueForBigDecimalSerialization() { BigDecimal target = new BigDecimal("1.55"); String actual = gson.toJson(target); assertEquals(target.toString(), actual); } public void testSmallValueForBigDecimalDeserialization() { BigDecimal expected = new BigDecimal("1.55"); BigDecimal actual = gson.fromJson("1.55", BigDecimal.class); assertEquals(expected, actual); } public void testBigDecimalPreservePrecisionSerialization() { String expectedValue = "1.000"; BigDecimal obj = new BigDecimal(expectedValue); String actualValue = gson.toJson(obj); assertEquals(expectedValue, actualValue); } public void testBigDecimalPreservePrecisionDeserialization() { String json = "1.000"; BigDecimal expected = new BigDecimal(json); BigDecimal actual = gson.fromJson(json, BigDecimal.class); assertEquals(expected, actual); } public void testBigDecimalAsStringRepresentationDeserialization() { String doubleValue = "0.05E+5"; BigDecimal expected = new BigDecimal(doubleValue); BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class); assertEquals(expected, actual); } public void testBigDecimalNoFractAsStringRepresentationDeserialization() { String doubleValue = "5E+5"; BigDecimal expected = new BigDecimal(doubleValue); BigDecimal actual = gson.fromJson(doubleValue, BigDecimal.class); assertEquals(expected, actual); } public void testBigIntegerSerialization() { BigInteger target = new BigInteger("12121211243123245845384534687435634558945453489543985435"); assertEquals(target.toString(), gson.toJson(target)); } public void testBigIntegerDeserialization() { String json = "12121211243123245845384534687435634558945453489543985435"; BigInteger target = new BigInteger(json); assertEquals(target, gson.fromJson(json, BigInteger.class)); } public void testBigIntegerInASingleElementArraySerialization() { BigInteger[] target = {new BigInteger("1212121243434324323254365345367456456456465464564564")}; String json = gson.toJson(target); String actual = extractElementFromArray(json); assertEquals(target[0], new BigInteger(actual)); json = gson.toJson(target, BigInteger[].class); actual = extractElementFromArray(json); assertEquals(target[0], new BigInteger(actual)); } public void testSmallValueForBigIntegerSerialization() { BigInteger target = new BigInteger("15"); String actual = gson.toJson(target); assertEquals(target.toString(), actual); } public void testSmallValueForBigIntegerDeserialization() { BigInteger expected = new BigInteger("15"); BigInteger actual = gson.fromJson("15", BigInteger.class); assertEquals(expected, actual); } public void testBadValueForBigIntegerDeserialization() { try { gson.fromJson("15.099", BigInteger.class); fail("BigInteger can not be decimal values."); } catch (JsonSyntaxException expected) { } } public void testMoreSpecificSerialization() { Gson gson = new Gson(); String expected = "This is a string"; String expectedJson = gson.toJson(expected); Serializable serializableString = expected; String actualJson = gson.toJson(serializableString, Serializable.class); assertFalse(expectedJson.equals(actualJson)); } private String extractElementFromArray(String json) { return json.substring(json.indexOf('[') + 1, json.indexOf(']')); } public void testDoubleNaNSerializationNotSupportedByDefault() { try { double nan = Double.NaN; gson.toJson(nan); fail("Gson should not accept NaN for serialization"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Double.NaN); fail("Gson should not accept NaN for serialization"); } catch (IllegalArgumentException expected) { } } public void testDoubleNaNSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); double nan = Double.NaN; assertEquals("NaN", gson.toJson(nan)); assertEquals("NaN", gson.toJson(Double.NaN)); } public void testDoubleNaNDeserialization() { assertTrue(Double.isNaN(gson.fromJson("NaN", Double.class))); assertTrue(Double.isNaN(gson.fromJson("NaN", double.class))); } public void testFloatNaNSerializationNotSupportedByDefault() { try { float nan = Float.NaN; gson.toJson(nan); fail("Gson should not accept NaN for serialization"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Float.NaN); fail("Gson should not accept NaN for serialization"); } catch (IllegalArgumentException expected) { } } public void testFloatNaNSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); float nan = Float.NaN; assertEquals("NaN", gson.toJson(nan)); assertEquals("NaN", gson.toJson(Float.NaN)); } public void testFloatNaNDeserialization() { assertTrue(Float.isNaN(gson.fromJson("NaN", Float.class))); assertTrue(Float.isNaN(gson.fromJson("NaN", float.class))); } public void testBigDecimalNaNDeserializationNotSupported() { try { gson.fromJson("NaN", BigDecimal.class); fail("Gson should not accept NaN for deserialization by default."); } catch (JsonSyntaxException expected) { } } public void testDoubleInfinitySerializationNotSupportedByDefault() { try { double infinity = Double.POSITIVE_INFINITY; gson.toJson(infinity); fail("Gson should not accept positive infinity for serialization by default."); } catch (IllegalArgumentException expected) { } try { gson.toJson(Double.POSITIVE_INFINITY); fail("Gson should not accept positive infinity for serialization by default."); } catch (IllegalArgumentException expected) { } } public void testDoubleInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); double infinity = Double.POSITIVE_INFINITY; assertEquals("Infinity", gson.toJson(infinity)); assertEquals("Infinity", gson.toJson(Double.POSITIVE_INFINITY)); } public void testDoubleInfinityDeserialization() { assertTrue(Double.isInfinite(gson.fromJson("Infinity", Double.class))); assertTrue(Double.isInfinite(gson.fromJson("Infinity", double.class))); } public void testFloatInfinitySerializationNotSupportedByDefault() { try { float infinity = Float.POSITIVE_INFINITY; gson.toJson(infinity); fail("Gson should not accept positive infinity for serialization by default"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Float.POSITIVE_INFINITY); fail("Gson should not accept positive infinity for serialization by default"); } catch (IllegalArgumentException expected) { } } public void testFloatInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); float infinity = Float.POSITIVE_INFINITY; assertEquals("Infinity", gson.toJson(infinity)); assertEquals("Infinity", gson.toJson(Float.POSITIVE_INFINITY)); } public void testFloatInfinityDeserialization() { assertTrue(Float.isInfinite(gson.fromJson("Infinity", Float.class))); assertTrue(Float.isInfinite(gson.fromJson("Infinity", float.class))); } public void testBigDecimalInfinityDeserializationNotSupported() { try { gson.fromJson("Infinity", BigDecimal.class); fail("Gson should not accept positive infinity for deserialization with BigDecimal"); } catch (JsonSyntaxException expected) { } } public void testNegativeInfinitySerializationNotSupportedByDefault() { try { double negativeInfinity = Double.NEGATIVE_INFINITY; gson.toJson(negativeInfinity); fail("Gson should not accept negative infinity for serialization by default"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Double.NEGATIVE_INFINITY); fail("Gson should not accept negative infinity for serialization by default"); } catch (IllegalArgumentException expected) { } } public void testNegativeInfinitySerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); double negativeInfinity = Double.NEGATIVE_INFINITY; assertEquals("-Infinity", gson.toJson(negativeInfinity)); assertEquals("-Infinity", gson.toJson(Double.NEGATIVE_INFINITY)); } public void testNegativeInfinityDeserialization() { assertTrue(Double.isInfinite(gson.fromJson("-Infinity", double.class))); assertTrue(Double.isInfinite(gson.fromJson("-Infinity", Double.class))); } public void testNegativeInfinityFloatSerializationNotSupportedByDefault() { try { float negativeInfinity = Float.NEGATIVE_INFINITY; gson.toJson(negativeInfinity); fail("Gson should not accept negative infinity for serialization by default"); } catch (IllegalArgumentException expected) { } try { gson.toJson(Float.NEGATIVE_INFINITY); fail("Gson should not accept negative infinity for serialization by default"); } catch (IllegalArgumentException expected) { } } public void testNegativeInfinityFloatSerialization() { Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); float negativeInfinity = Float.NEGATIVE_INFINITY; assertEquals("-Infinity", gson.toJson(negativeInfinity)); assertEquals("-Infinity", gson.toJson(Float.NEGATIVE_INFINITY)); } public void testNegativeInfinityFloatDeserialization() { assertTrue(Float.isInfinite(gson.fromJson("-Infinity", float.class))); assertTrue(Float.isInfinite(gson.fromJson("-Infinity", Float.class))); } public void testBigDecimalNegativeInfinityDeserializationNotSupported() { try { gson.fromJson("-Infinity", BigDecimal.class); fail("Gson should not accept positive infinity for deserialization"); } catch (JsonSyntaxException expected) { } } public void testLongAsStringSerialization() throws Exception { gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); String result = gson.toJson(15L); assertEquals("\"15\"", result); // Test with an integer and ensure its still a number result = gson.toJson(2); assertEquals("2", result); } public void testLongAsStringDeserialization() throws Exception { long value = gson.fromJson("\"15\"", long.class); assertEquals(15, value); gson = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); value = gson.fromJson("\"25\"", long.class); assertEquals(25, value); } public void testQuotedStringSerializationAndDeserialization() throws Exception { String value = "String Blah Blah Blah...1, 2, 3"; String serializedForm = gson.toJson(value); assertEquals("\"" + value + "\"", serializedForm); String actual = gson.fromJson(serializedForm, String.class); assertEquals(value, actual); } public void testUnquotedStringDeserializationFails() throws Exception { assertEquals("UnquotedSingleWord", gson.fromJson("UnquotedSingleWord", String.class)); String value = "String Blah Blah Blah...1, 2, 3"; try { gson.fromJson(value, String.class); fail(); } catch (JsonSyntaxException expected) { } } public void testHtmlCharacterSerialization() throws Exception { String target = "<script>var a = 12;</script>"; String result = gson.toJson(target); assertFalse(result.equals('"' + target + '"')); gson = new GsonBuilder().disableHtmlEscaping().create(); result = gson.toJson(target); assertTrue(result.equals('"' + target + '"')); } public void testDeserializePrimitiveWrapperAsObjectField() { String json = "{i:10}"; ClassWithIntegerField target = gson.fromJson(json, ClassWithIntegerField.class); assertEquals(10, target.i.intValue()); } private static class ClassWithIntegerField { Integer i; } public void testPrimitiveClassLiteral() { assertEquals(1, gson.fromJson("1", int.class).intValue()); assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue()); assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue()); } public void testDeserializeJsonObjectAsLongPrimitive() { try { gson.fromJson("{'abc':1}", long.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsLongWrapper() { try { gson.fromJson("[1,2,3]", Long.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsInt() { try { gson.fromJson("[1, 2, 3, 4]", int.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsInteger() { try { gson.fromJson("{}", Integer.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsShortPrimitive() { try { gson.fromJson("{'abc':1}", short.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsShortWrapper() { try { gson.fromJson("['a','b']", Short.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsDoublePrimitive() { try { gson.fromJson("[1,2]", double.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsDoubleWrapper() { try { gson.fromJson("{'abc':1}", Double.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsFloatPrimitive() { try { gson.fromJson("{'abc':1}", float.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsFloatWrapper() { try { gson.fromJson("[1,2,3]", Float.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsBytePrimitive() { try { gson.fromJson("{'abc':1}", byte.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsByteWrapper() { try { gson.fromJson("[1,2,3,4]", Byte.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsBooleanPrimitive() { try { gson.fromJson("{'abc':1}", boolean.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsBooleanWrapper() { try { gson.fromJson("[1,2,3,4]", Boolean.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsBigDecimal() { try { gson.fromJson("[1,2,3,4]", BigDecimal.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsBigDecimal() { try { gson.fromJson("{'a':1}", BigDecimal.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsBigInteger() { try { gson.fromJson("[1,2,3,4]", BigInteger.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsBigInteger() { try { gson.fromJson("{'c':2}", BigInteger.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonArrayAsNumber() { try { gson.fromJson("[1,2,3,4]", Number.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializeJsonObjectAsNumber() { try { gson.fromJson("{'c':2}", Number.class); fail(); } catch (JsonSyntaxException expected) {} } public void testDeserializingDecimalPointValueZeroSucceeds() { assertEquals(1, (int) gson.fromJson("1.0", Integer.class)); } public void testDeserializingNonZeroDecimalPointValuesAsIntegerFails() { try { gson.fromJson("1.02", Byte.class); fail(); } catch (JsonSyntaxException expected) { } try { gson.fromJson("1.02", Short.class); fail(); } catch (JsonSyntaxException expected) { } try { gson.fromJson("1.02", Integer.class); fail(); } catch (JsonSyntaxException expected) { } try { gson.fromJson("1.02", Long.class); fail(); } catch (JsonSyntaxException expected) { } } public void testDeserializingBigDecimalAsIntegerFails() { try { gson.fromJson("-122.08e-213", Integer.class); fail(); } catch (JsonSyntaxException expected) { } } public void testDeserializingBigIntegerAsInteger() { try { gson.fromJson("12121211243123245845384534687435634558945453489543985435", Integer.class); fail(); } catch (JsonSyntaxException expected) { } } public void testDeserializingBigIntegerAsLong() { try { gson.fromJson("12121211243123245845384534687435634558945453489543985435", Long.class); fail(); } catch (JsonSyntaxException expected) { } } public void testValueVeryCloseToZeroIsZero() { assertEquals(0, (byte) gson.fromJson("-122.08e-2132", byte.class)); assertEquals(0, (short) gson.fromJson("-122.08e-2132", short.class)); assertEquals(0, (int) gson.fromJson("-122.08e-2132", int.class)); assertEquals(0, (long) gson.fromJson("-122.08e-2132", long.class)); assertEquals(-0.0f, gson.fromJson("-122.08e-2132", float.class)); assertEquals(-0.0, gson.fromJson("-122.08e-2132", double.class)); assertEquals(0.0f, gson.fromJson("122.08e-2132", float.class)); assertEquals(0.0, gson.fromJson("122.08e-2132", double.class)); } public void testDeserializingBigDecimalAsFloat() { String json = "-122.08e-2132332"; float actual = gson.fromJson(json, float.class); assertEquals(-0.0f, actual); } public void testDeserializingBigDecimalAsDouble() { String json = "-122.08e-2132332"; double actual = gson.fromJson(json, double.class); assertEquals(-0.0d, actual); } public void testDeserializingBigDecimalAsBigIntegerFails() { try { gson.fromJson("-122.08e-213", BigInteger.class); fail(); } catch (JsonSyntaxException expected) { } } public void testDeserializingBigIntegerAsBigDecimal() { BigDecimal actual = gson.fromJson("12121211243123245845384534687435634558945453489543985435", BigDecimal.class); assertEquals("12121211243123245845384534687435634558945453489543985435", actual.toPlainString()); } public void testStringsAsBooleans() { String json = "['true', 'false', 'TRUE', 'yes', '1']"; assertEquals(Arrays.asList(true, false, true, false, false), gson.<List<Boolean>>fromJson(json, new TypeToken<List<Boolean>>() {}.getType())); } }
public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); System.err.println(sw.toString()); String expected = "usage:\n" + " org.apache.comm\n" + " ons.cli.bug.Bug\n" + " CLI162Test\n" + "Header\n" + "-x,--extralongarg\n" + " This description is\n" + " Long.\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); }
org.apache.commons.cli.bug.BugCLI162Test::testLongLineChunkingIndentIgnored
src/test/org/apache/commons/cli/bug/BugCLI162Test.java
280
src/test/org/apache/commons/cli/bug/BugCLI162Test.java
testLongLineChunkingIndentIgnored
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli.bug; import java.io.IOException; import java.io.StringWriter; import java.io.PrintWriter; import java.sql.ParameterMetaData; import java.sql.Types; import junit.framework.TestCase; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class BugCLI162Test extends TestCase { public void testInfiniteLoop() { Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } public void testPrintHelpLongLines() throws ParseException, IOException { // Constants used for options final String OPT = "-"; final String OPT_COLUMN_NAMES = "l"; final String OPT_CONNECTION = "c"; final String OPT_DESCRIPTION = "e"; final String OPT_DRIVER = "d"; final String OPT_DRIVER_INFO = "n"; final String OPT_FILE_BINDING = "b"; final String OPT_FILE_JDBC = "j"; final String OPT_FILE_SFMD = "f"; final String OPT_HELP = "h"; final String OPT_HELP_ = "help"; final String OPT_INTERACTIVE = "i"; final String OPT_JDBC_TO_SFMD = "2"; final String OPT_JDBC_TO_SFMD_L = "jdbc2sfmd"; final String OPT_METADATA = "m"; final String OPT_PARAM_MODES_INT = "o"; final String OPT_PARAM_MODES_NAME = "O"; final String OPT_PARAM_NAMES = "a"; final String OPT_PARAM_TYPES_INT = "y"; final String OPT_PARAM_TYPES_NAME = "Y"; final String OPT_PASSWORD = "p"; final String OPT_PASSWORD_L = "password"; final String OPT_SQL = "s"; final String OPT_SQL_L = "sql"; final String OPT_SQL_SPLIT_DEFAULT = "###"; final String OPT_SQL_SPLIT_L = "splitSql"; final String OPT_STACK_TRACE = "t"; final String OPT_TIMING = "g"; final String OPT_TRIM_L = "trim"; final String OPT_USER = "u"; final String OPT_WRITE_TO_FILE = "w"; final String _PMODE_IN = "IN"; final String _PMODE_INOUT = "INOUT"; final String _PMODE_OUT = "OUT"; final String _PMODE_UNK = "Unknown"; final String PMODES = _PMODE_IN + ", " + _PMODE_INOUT + ", " + _PMODE_OUT + ", " + _PMODE_UNK; // Options build Options commandLineOptions; commandLineOptions = new Options(); commandLineOptions.addOption(OPT_HELP, OPT_HELP_, false, "Prints help and quits"); commandLineOptions.addOption(OPT_DRIVER, "driver", true, "JDBC driver class name"); commandLineOptions.addOption(OPT_DRIVER_INFO, "info", false, "Prints driver information and properties. If " + OPT + OPT_CONNECTION + " is not specified, all drivers on the classpath are displayed."); commandLineOptions.addOption(OPT_CONNECTION, "url", true, "Connection URL"); commandLineOptions.addOption(OPT_USER, "user", true, "A database user name"); commandLineOptions .addOption( OPT_PASSWORD, OPT_PASSWORD_L, true, "The database password for the user specified with the " + OPT + OPT_USER + " option. You can obfuscate the password with org.mortbay.jetty.security.Password, see http://docs.codehaus.org/display/JETTY/Securing+Passwords"); commandLineOptions.addOption(OPT_SQL, OPT_SQL_L, true, "Runs SQL or {call stored_procedure(?, ?)} or {?=call function(?, ?)}"); commandLineOptions.addOption(OPT_FILE_SFMD, "sfmd", true, "Writes a SFMD file for the given SQL"); commandLineOptions.addOption(OPT_FILE_BINDING, "jdbc", true, "Writes a JDBC binding node file for the given SQL"); commandLineOptions.addOption(OPT_FILE_JDBC, "node", true, "Writes a JDBC node file for the given SQL (internal debugging)"); commandLineOptions.addOption(OPT_WRITE_TO_FILE, "outfile", true, "Writes the SQL output to the given file"); commandLineOptions.addOption(OPT_DESCRIPTION, "description", true, "SFMD description. A default description is used if omited. Example: " + OPT + OPT_DESCRIPTION + " \"Runs such and such\""); commandLineOptions.addOption(OPT_INTERACTIVE, "interactive", false, "Runs in interactive mode, reading and writing from the console, 'go' or '/' sends a statement"); commandLineOptions.addOption(OPT_TIMING, "printTiming", false, "Prints timing information"); commandLineOptions.addOption(OPT_METADATA, "printMetaData", false, "Prints metadata information"); commandLineOptions.addOption(OPT_STACK_TRACE, "printStack", false, "Prints stack traces on errors"); Option option = new Option(OPT_COLUMN_NAMES, "columnNames", true, "Column XML names; default names column labels. Example: " + OPT + OPT_COLUMN_NAMES + " \"cname1 cname2\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_NAMES, "paramNames", true, "Parameter XML names; default names are param1, param2, etc. Example: " + OPT + OPT_PARAM_NAMES + " \"pname1 pname2\""); commandLineOptions.addOption(option); // OptionGroup pOutTypesOptionGroup = new OptionGroup(); String pOutTypesOptionGroupDoc = OPT + OPT_PARAM_TYPES_INT + " and " + OPT + OPT_PARAM_TYPES_NAME + " are mutually exclusive."; final String typesClassName = Types.class.getName(); option = new Option(OPT_PARAM_TYPES_INT, "paramTypes", true, "Parameter types from " + typesClassName + ". " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_INT + " \"-10 12\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_TYPES_NAME, "paramTypeNames", true, "Parameter " + typesClassName + " names. " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_NAME + " \"CURSOR VARCHAR\""); commandLineOptions.addOption(option); commandLineOptions.addOptionGroup(pOutTypesOptionGroup); // OptionGroup modesOptionGroup = new OptionGroup(); String modesOptionGroupDoc = OPT + OPT_PARAM_MODES_INT + " and " + OPT + OPT_PARAM_MODES_NAME + " are mutually exclusive."; option = new Option(OPT_PARAM_MODES_INT, "paramModes", true, "Parameters modes (" + ParameterMetaData.parameterModeIn + "=IN, " + ParameterMetaData.parameterModeInOut + "=INOUT, " + ParameterMetaData.parameterModeOut + "=OUT, " + ParameterMetaData.parameterModeUnknown + "=Unknown" + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_INT + " \"" + ParameterMetaData.parameterModeOut + " " + ParameterMetaData.parameterModeIn + "\""); modesOptionGroup.addOption(option); option = new Option(OPT_PARAM_MODES_NAME, "paramModeNames", true, "Parameters mode names (" + PMODES + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_NAME + " \"" + _PMODE_OUT + " " + _PMODE_IN + "\""); modesOptionGroup.addOption(option); commandLineOptions.addOptionGroup(modesOptionGroup); option = new Option(null, OPT_TRIM_L, true, "Trims leading and trailing spaces from all column values. Column XML names can be optionally specified to set which columns to trim."); option.setOptionalArg(true); commandLineOptions.addOption(option); option = new Option(OPT_JDBC_TO_SFMD, OPT_JDBC_TO_SFMD_L, true, "Converts the JDBC file in the first argument to an SMFD file specified in the second argument."); option.setArgs(2); commandLineOptions.addOption(option); new HelpFormatter().printHelp(this.getClass().getName(), commandLineOptions); } public void testLongLineChunking() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description has ReallyLongValuesThatAreLongerThanTheWidthOfTheColumns " + "and also other ReallyLongValuesThatAreHugerAndBiggerThanTheWidthOfTheColumnsBob, " + "yes. "); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 35, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:\n" + " org.apache.commons.cli.bug.B\n" + " ugCLI162Test\n" + "Header\n" + "-x,--extralongarg This\n" + " description\n" + " has\n" + " ReallyLongVal\n" + " uesThatAreLon\n" + " gerThanTheWid\n" + " thOfTheColumn\n" + " s and also\n" + " other\n" + " ReallyLongVal\n" + " uesThatAreHug\n" + " erAndBiggerTh\n" + " anTheWidthOfT\n" + " heColumnsBob,\n" + " yes.\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); System.err.println(sw.toString()); String expected = "usage:\n" + " org.apache.comm\n" + " ons.cli.bug.Bug\n" + " CLI162Test\n" + "Header\n" + "-x,--extralongarg\n" + " This description is\n" + " Long.\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } }
// You are a professional Java test case writer, please create a test case named `testLongLineChunkingIndentIgnored` for the issue `Cli-CLI-162`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-162 // // ## Issue-Title: // infinite loop in the wrapping code of HelpFormatter // // ## Issue-Description: // // If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError. // // // Test case: // // // // // ``` // Options options = new Options(); // options.addOption("h", "help", false, "This is a looooong description"); // // HelpFormatter formatter = new HelpFormatter(); // formatter.setWidth(20); // formatter.printHelp("app", options); // hang & crash // // ``` // // // An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError. // // // // // public void testLongLineChunkingIndentIgnored() throws ParseException, IOException {
280
25
263
src/test/org/apache/commons/cli/bug/BugCLI162Test.java
src/test
```markdown ## Issue-ID: Cli-CLI-162 ## Issue-Title: infinite loop in the wrapping code of HelpFormatter ## Issue-Description: If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError. Test case: ``` Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // hang & crash ``` An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError. ``` You are a professional Java test case writer, please create a test case named `testLongLineChunkingIndentIgnored` for the issue `Cli-CLI-162`, utilizing the provided issue report information and the following function signature. ```java public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { ```
263
[ "org.apache.commons.cli.HelpFormatter" ]
0db33056a501a1f41b22e9a9ea8468dcdcb04e835d513f7a80372e82b0788b17
public void testLongLineChunkingIndentIgnored() throws ParseException, IOException
// You are a professional Java test case writer, please create a test case named `testLongLineChunkingIndentIgnored` for the issue `Cli-CLI-162`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-162 // // ## Issue-Title: // infinite loop in the wrapping code of HelpFormatter // // ## Issue-Description: // // If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError. // // // Test case: // // // // // ``` // Options options = new Options(); // options.addOption("h", "help", false, "This is a looooong description"); // // HelpFormatter formatter = new HelpFormatter(); // formatter.setWidth(20); // formatter.printHelp("app", options); // hang & crash // // ``` // // // An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError. // // // // //
Cli
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli.bug; import java.io.IOException; import java.io.StringWriter; import java.io.PrintWriter; import java.sql.ParameterMetaData; import java.sql.Types; import junit.framework.TestCase; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class BugCLI162Test extends TestCase { public void testInfiniteLoop() { Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } public void testPrintHelpLongLines() throws ParseException, IOException { // Constants used for options final String OPT = "-"; final String OPT_COLUMN_NAMES = "l"; final String OPT_CONNECTION = "c"; final String OPT_DESCRIPTION = "e"; final String OPT_DRIVER = "d"; final String OPT_DRIVER_INFO = "n"; final String OPT_FILE_BINDING = "b"; final String OPT_FILE_JDBC = "j"; final String OPT_FILE_SFMD = "f"; final String OPT_HELP = "h"; final String OPT_HELP_ = "help"; final String OPT_INTERACTIVE = "i"; final String OPT_JDBC_TO_SFMD = "2"; final String OPT_JDBC_TO_SFMD_L = "jdbc2sfmd"; final String OPT_METADATA = "m"; final String OPT_PARAM_MODES_INT = "o"; final String OPT_PARAM_MODES_NAME = "O"; final String OPT_PARAM_NAMES = "a"; final String OPT_PARAM_TYPES_INT = "y"; final String OPT_PARAM_TYPES_NAME = "Y"; final String OPT_PASSWORD = "p"; final String OPT_PASSWORD_L = "password"; final String OPT_SQL = "s"; final String OPT_SQL_L = "sql"; final String OPT_SQL_SPLIT_DEFAULT = "###"; final String OPT_SQL_SPLIT_L = "splitSql"; final String OPT_STACK_TRACE = "t"; final String OPT_TIMING = "g"; final String OPT_TRIM_L = "trim"; final String OPT_USER = "u"; final String OPT_WRITE_TO_FILE = "w"; final String _PMODE_IN = "IN"; final String _PMODE_INOUT = "INOUT"; final String _PMODE_OUT = "OUT"; final String _PMODE_UNK = "Unknown"; final String PMODES = _PMODE_IN + ", " + _PMODE_INOUT + ", " + _PMODE_OUT + ", " + _PMODE_UNK; // Options build Options commandLineOptions; commandLineOptions = new Options(); commandLineOptions.addOption(OPT_HELP, OPT_HELP_, false, "Prints help and quits"); commandLineOptions.addOption(OPT_DRIVER, "driver", true, "JDBC driver class name"); commandLineOptions.addOption(OPT_DRIVER_INFO, "info", false, "Prints driver information and properties. If " + OPT + OPT_CONNECTION + " is not specified, all drivers on the classpath are displayed."); commandLineOptions.addOption(OPT_CONNECTION, "url", true, "Connection URL"); commandLineOptions.addOption(OPT_USER, "user", true, "A database user name"); commandLineOptions .addOption( OPT_PASSWORD, OPT_PASSWORD_L, true, "The database password for the user specified with the " + OPT + OPT_USER + " option. You can obfuscate the password with org.mortbay.jetty.security.Password, see http://docs.codehaus.org/display/JETTY/Securing+Passwords"); commandLineOptions.addOption(OPT_SQL, OPT_SQL_L, true, "Runs SQL or {call stored_procedure(?, ?)} or {?=call function(?, ?)}"); commandLineOptions.addOption(OPT_FILE_SFMD, "sfmd", true, "Writes a SFMD file for the given SQL"); commandLineOptions.addOption(OPT_FILE_BINDING, "jdbc", true, "Writes a JDBC binding node file for the given SQL"); commandLineOptions.addOption(OPT_FILE_JDBC, "node", true, "Writes a JDBC node file for the given SQL (internal debugging)"); commandLineOptions.addOption(OPT_WRITE_TO_FILE, "outfile", true, "Writes the SQL output to the given file"); commandLineOptions.addOption(OPT_DESCRIPTION, "description", true, "SFMD description. A default description is used if omited. Example: " + OPT + OPT_DESCRIPTION + " \"Runs such and such\""); commandLineOptions.addOption(OPT_INTERACTIVE, "interactive", false, "Runs in interactive mode, reading and writing from the console, 'go' or '/' sends a statement"); commandLineOptions.addOption(OPT_TIMING, "printTiming", false, "Prints timing information"); commandLineOptions.addOption(OPT_METADATA, "printMetaData", false, "Prints metadata information"); commandLineOptions.addOption(OPT_STACK_TRACE, "printStack", false, "Prints stack traces on errors"); Option option = new Option(OPT_COLUMN_NAMES, "columnNames", true, "Column XML names; default names column labels. Example: " + OPT + OPT_COLUMN_NAMES + " \"cname1 cname2\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_NAMES, "paramNames", true, "Parameter XML names; default names are param1, param2, etc. Example: " + OPT + OPT_PARAM_NAMES + " \"pname1 pname2\""); commandLineOptions.addOption(option); // OptionGroup pOutTypesOptionGroup = new OptionGroup(); String pOutTypesOptionGroupDoc = OPT + OPT_PARAM_TYPES_INT + " and " + OPT + OPT_PARAM_TYPES_NAME + " are mutually exclusive."; final String typesClassName = Types.class.getName(); option = new Option(OPT_PARAM_TYPES_INT, "paramTypes", true, "Parameter types from " + typesClassName + ". " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_INT + " \"-10 12\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_TYPES_NAME, "paramTypeNames", true, "Parameter " + typesClassName + " names. " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_NAME + " \"CURSOR VARCHAR\""); commandLineOptions.addOption(option); commandLineOptions.addOptionGroup(pOutTypesOptionGroup); // OptionGroup modesOptionGroup = new OptionGroup(); String modesOptionGroupDoc = OPT + OPT_PARAM_MODES_INT + " and " + OPT + OPT_PARAM_MODES_NAME + " are mutually exclusive."; option = new Option(OPT_PARAM_MODES_INT, "paramModes", true, "Parameters modes (" + ParameterMetaData.parameterModeIn + "=IN, " + ParameterMetaData.parameterModeInOut + "=INOUT, " + ParameterMetaData.parameterModeOut + "=OUT, " + ParameterMetaData.parameterModeUnknown + "=Unknown" + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_INT + " \"" + ParameterMetaData.parameterModeOut + " " + ParameterMetaData.parameterModeIn + "\""); modesOptionGroup.addOption(option); option = new Option(OPT_PARAM_MODES_NAME, "paramModeNames", true, "Parameters mode names (" + PMODES + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_NAME + " \"" + _PMODE_OUT + " " + _PMODE_IN + "\""); modesOptionGroup.addOption(option); commandLineOptions.addOptionGroup(modesOptionGroup); option = new Option(null, OPT_TRIM_L, true, "Trims leading and trailing spaces from all column values. Column XML names can be optionally specified to set which columns to trim."); option.setOptionalArg(true); commandLineOptions.addOption(option); option = new Option(OPT_JDBC_TO_SFMD, OPT_JDBC_TO_SFMD_L, true, "Converts the JDBC file in the first argument to an SMFD file specified in the second argument."); option.setArgs(2); commandLineOptions.addOption(option); new HelpFormatter().printHelp(this.getClass().getName(), commandLineOptions); } public void testLongLineChunking() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description has ReallyLongValuesThatAreLongerThanTheWidthOfTheColumns " + "and also other ReallyLongValuesThatAreHugerAndBiggerThanTheWidthOfTheColumnsBob, " + "yes. "); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 35, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:\n" + " org.apache.commons.cli.bug.B\n" + " ugCLI162Test\n" + "Header\n" + "-x,--extralongarg This\n" + " description\n" + " has\n" + " ReallyLongVal\n" + " uesThatAreLon\n" + " gerThanTheWid\n" + " thOfTheColumn\n" + " s and also\n" + " other\n" + " ReallyLongVal\n" + " uesThatAreHug\n" + " erAndBiggerTh\n" + " anTheWidthOfT\n" + " heColumnsBob,\n" + " yes.\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); System.err.println(sw.toString()); String expected = "usage:\n" + " org.apache.comm\n" + " ons.cli.bug.Bug\n" + " CLI162Test\n" + "Header\n" + "-x,--extralongarg\n" + " This description is\n" + " Long.\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } }
public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", new Integer("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", new Long(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", new Integer("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 10 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertEquals("createNumber(String) 11 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); // jdk 1.2 doesn't support this. unsure about jdk 1.2.2 if (SystemUtils.isJavaVersionAtLeast(1.3f)) { assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); } assertEquals("createNumber(String) 16 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", new Float("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); }
org.apache.commons.lang3.math.NumberUtilsTest::testCreateNumber
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
216
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
testCreateNumber
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.math; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import junit.framework.TestCase; import org.apache.commons.lang3.SystemUtils; /** * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}. * * @author Apache Software Foundation * @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a> * @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a> * @author Eric Pugh * @author Phil Steitz * @author Matthew Hawthorne * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @version $Id$ */ public class NumberUtilsTest extends TestCase { public NumberUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new NumberUtils()); Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(NumberUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#toInt(String)}. */ public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {@link NumberUtils#toDouble(String)}. */ public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", new Integer("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", new Long(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", new Integer("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 10 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertEquals("createNumber(String) 11 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); // jdk 1.2 doesn't support this. unsure about jdk 1.2.2 if (SystemUtils.isJavaVersionAtLeast(1.3f)) { assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); } assertEquals("createNumber(String) 16 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", new Float("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); } public void testCreateFloat() { assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(String str) { try { Float value = NumberUtils.createFloat(str); fail("createFloat(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateDouble() { assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(String str) { try { Double value = NumberUtils.createDouble(str); fail("createDouble(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateInteger() { assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(String str) { try { Integer value = NumberUtils.createInteger(str); fail("createInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateLong() { assertEquals("createLong(String) failed", new Long("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(String str) { try { Long value = NumberUtils.createLong(str); fail("createLong(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigIntegerFailure(String str) { try { BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigDecimalFailure(String str) { try { BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- public void testMinLong() { final long[] l = null; try { NumberUtils.min(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } public void testMinInt() { final int[] i = null; try { NumberUtils.min(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } public void testMinShort() { final short[] s = null; try { NumberUtils.min(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } public void testMinByte() { final byte[] b = null; try { NumberUtils.min(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } public void testMinDouble() { final double[] d = null; try { NumberUtils.min(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } public void testMinFloat() { final float[] f = null; try { NumberUtils.min(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } public void testMaxLong() { final long[] l = null; try { NumberUtils.max(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } public void testMaxInt() { final int[] i = null; try { NumberUtils.max(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } public void testMaxShort() { final short[] s = null; try { NumberUtils.max(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } public void testMaxByte() { final byte[] b = null; try { NumberUtils.max(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } public void testMaxFloat() { final float[] f = null; try { NumberUtils.max(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } public void testMinimumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } public void testMinimumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } public void testMaximumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } public void testMaximumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } // Testing JDK against old Lang functionality public void testCompareDouble() { assertTrue(Double.compare(Double.NaN, Double.NaN) == 0); assertTrue(Double.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, 1.2d) == +1); assertTrue(Double.compare(Double.NaN, 0.0d) == +1); assertTrue(Double.compare(Double.NaN, -0.0d) == +1); assertTrue(Double.compare(Double.NaN, -1.2d) == +1); assertTrue(Double.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(Double.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(1.2d, Double.NaN) == -1); assertTrue(Double.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(1.2d, 1.2d) == 0); assertTrue(Double.compare(1.2d, 0.0d) == +1); assertTrue(Double.compare(1.2d, -0.0d) == +1); assertTrue(Double.compare(1.2d, -1.2d) == +1); assertTrue(Double.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(0.0d, Double.NaN) == -1); assertTrue(Double.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(0.0d, 1.2d) == -1); assertTrue(Double.compare(0.0d, 0.0d) == 0); assertTrue(Double.compare(0.0d, -0.0d) == +1); assertTrue(Double.compare(0.0d, -1.2d) == +1); assertTrue(Double.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-0.0d, Double.NaN) == -1); assertTrue(Double.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-0.0d, 1.2d) == -1); assertTrue(Double.compare(-0.0d, 0.0d) == -1); assertTrue(Double.compare(-0.0d, -0.0d) == 0); assertTrue(Double.compare(-0.0d, -1.2d) == +1); assertTrue(Double.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-1.2d, Double.NaN) == -1); assertTrue(Double.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-1.2d, 1.2d) == -1); assertTrue(Double.compare(-1.2d, 0.0d) == -1); assertTrue(Double.compare(-1.2d, -0.0d) == -1); assertTrue(Double.compare(-1.2d, -1.2d) == 0); assertTrue(Double.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } public void testCompareFloat() { assertTrue(Float.compare(Float.NaN, Float.NaN) == 0); assertTrue(Float.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, 1.2f) == +1); assertTrue(Float.compare(Float.NaN, 0.0f) == +1); assertTrue(Float.compare(Float.NaN, -0.0f) == +1); assertTrue(Float.compare(Float.NaN, -1.2f) == +1); assertTrue(Float.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(Float.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(1.2f, Float.NaN) == -1); assertTrue(Float.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(1.2f, 1.2f) == 0); assertTrue(Float.compare(1.2f, 0.0f) == +1); assertTrue(Float.compare(1.2f, -0.0f) == +1); assertTrue(Float.compare(1.2f, -1.2f) == +1); assertTrue(Float.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(0.0f, Float.NaN) == -1); assertTrue(Float.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(0.0f, 1.2f) == -1); assertTrue(Float.compare(0.0f, 0.0f) == 0); assertTrue(Float.compare(0.0f, -0.0f) == +1); assertTrue(Float.compare(0.0f, -1.2f) == +1); assertTrue(Float.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-0.0f, Float.NaN) == -1); assertTrue(Float.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-0.0f, 1.2f) == -1); assertTrue(Float.compare(-0.0f, 0.0f) == -1); assertTrue(Float.compare(-0.0f, -0.0f) == 0); assertTrue(Float.compare(-0.0f, -1.2f) == +1); assertTrue(Float.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-1.2f, Float.NaN) == -1); assertTrue(Float.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-1.2f, 1.2f) == -1); assertTrue(Float.compare(-1.2f, 0.0f) == -1); assertTrue(Float.compare(-1.2f, -0.0f) == -1); assertTrue(Float.compare(-1.2f, -1.2f) == 0); assertTrue(Float.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } public void testIsDigits() { assertEquals("isDigits(null) failed", false, NumberUtils.isDigits(null)); assertEquals("isDigits('') failed", false, NumberUtils.isDigits("")); assertEquals("isDigits(String) failed", true, NumberUtils.isDigits("12345")); assertEquals("isDigits(String) neg 1 failed", false, NumberUtils.isDigits("1234.5")); assertEquals("isDigits(String) neg 3 failed", false, NumberUtils.isDigits("1ab")); assertEquals("isDigits(String) neg 4 failed", false, NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(String val) { try { Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (NumberFormatException e) { return false; } } @SuppressWarnings("cast") // suppress instanceof warning check public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } }
// You are a professional Java test case writer, please create a test case named `testCreateNumber` for the issue `Lang-LANG-638`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-638 // // ## Issue-Title: // NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in // // ## Issue-Description: // // NumberUtils createNumber throws a StringIndexOutOfBoundsException instead of NumberFormatException when a String containing both possible exponent indicators is passed in. // // One example of such a String is "1eE". // // // // // public void testCreateNumber() {
216
27
175
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-638 ## Issue-Title: NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in ## Issue-Description: NumberUtils createNumber throws a StringIndexOutOfBoundsException instead of NumberFormatException when a String containing both possible exponent indicators is passed in. One example of such a String is "1eE". ``` You are a professional Java test case writer, please create a test case named `testCreateNumber` for the issue `Lang-LANG-638`, utilizing the provided issue report information and the following function signature. ```java public void testCreateNumber() { ```
175
[ "org.apache.commons.lang3.math.NumberUtils" ]
0e775b0e1b955e52c4aa702af1630060a82ba36598d01a18b929143336124559
public void testCreateNumber()
// You are a professional Java test case writer, please create a test case named `testCreateNumber` for the issue `Lang-LANG-638`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-638 // // ## Issue-Title: // NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in // // ## Issue-Description: // // NumberUtils createNumber throws a StringIndexOutOfBoundsException instead of NumberFormatException when a String containing both possible exponent indicators is passed in. // // One example of such a String is "1eE". // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.math; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import junit.framework.TestCase; import org.apache.commons.lang3.SystemUtils; /** * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}. * * @author Apache Software Foundation * @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a> * @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a> * @author Eric Pugh * @author Phil Steitz * @author Matthew Hawthorne * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @version $Id$ */ public class NumberUtilsTest extends TestCase { public NumberUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new NumberUtils()); Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(NumberUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#toInt(String)}. */ public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {@link NumberUtils#toDouble(String)}. */ public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", new Integer("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", new Long(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", new Integer("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 10 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertEquals("createNumber(String) 11 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); // jdk 1.2 doesn't support this. unsure about jdk 1.2.2 if (SystemUtils.isJavaVersionAtLeast(1.3f)) { assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); } assertEquals("createNumber(String) 16 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", new Float("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); } public void testCreateFloat() { assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(String str) { try { Float value = NumberUtils.createFloat(str); fail("createFloat(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateDouble() { assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(String str) { try { Double value = NumberUtils.createDouble(str); fail("createDouble(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateInteger() { assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(String str) { try { Integer value = NumberUtils.createInteger(str); fail("createInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateLong() { assertEquals("createLong(String) failed", new Long("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(String str) { try { Long value = NumberUtils.createLong(str); fail("createLong(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigIntegerFailure(String str) { try { BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigDecimalFailure(String str) { try { BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- public void testMinLong() { final long[] l = null; try { NumberUtils.min(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } public void testMinInt() { final int[] i = null; try { NumberUtils.min(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } public void testMinShort() { final short[] s = null; try { NumberUtils.min(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } public void testMinByte() { final byte[] b = null; try { NumberUtils.min(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } public void testMinDouble() { final double[] d = null; try { NumberUtils.min(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } public void testMinFloat() { final float[] f = null; try { NumberUtils.min(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } public void testMaxLong() { final long[] l = null; try { NumberUtils.max(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } public void testMaxInt() { final int[] i = null; try { NumberUtils.max(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } public void testMaxShort() { final short[] s = null; try { NumberUtils.max(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } public void testMaxByte() { final byte[] b = null; try { NumberUtils.max(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } public void testMaxFloat() { final float[] f = null; try { NumberUtils.max(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } public void testMinimumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } public void testMinimumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } public void testMaximumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } public void testMaximumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } // Testing JDK against old Lang functionality public void testCompareDouble() { assertTrue(Double.compare(Double.NaN, Double.NaN) == 0); assertTrue(Double.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, 1.2d) == +1); assertTrue(Double.compare(Double.NaN, 0.0d) == +1); assertTrue(Double.compare(Double.NaN, -0.0d) == +1); assertTrue(Double.compare(Double.NaN, -1.2d) == +1); assertTrue(Double.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(Double.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(1.2d, Double.NaN) == -1); assertTrue(Double.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(1.2d, 1.2d) == 0); assertTrue(Double.compare(1.2d, 0.0d) == +1); assertTrue(Double.compare(1.2d, -0.0d) == +1); assertTrue(Double.compare(1.2d, -1.2d) == +1); assertTrue(Double.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(0.0d, Double.NaN) == -1); assertTrue(Double.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(0.0d, 1.2d) == -1); assertTrue(Double.compare(0.0d, 0.0d) == 0); assertTrue(Double.compare(0.0d, -0.0d) == +1); assertTrue(Double.compare(0.0d, -1.2d) == +1); assertTrue(Double.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-0.0d, Double.NaN) == -1); assertTrue(Double.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-0.0d, 1.2d) == -1); assertTrue(Double.compare(-0.0d, 0.0d) == -1); assertTrue(Double.compare(-0.0d, -0.0d) == 0); assertTrue(Double.compare(-0.0d, -1.2d) == +1); assertTrue(Double.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-1.2d, Double.NaN) == -1); assertTrue(Double.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-1.2d, 1.2d) == -1); assertTrue(Double.compare(-1.2d, 0.0d) == -1); assertTrue(Double.compare(-1.2d, -0.0d) == -1); assertTrue(Double.compare(-1.2d, -1.2d) == 0); assertTrue(Double.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } public void testCompareFloat() { assertTrue(Float.compare(Float.NaN, Float.NaN) == 0); assertTrue(Float.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, 1.2f) == +1); assertTrue(Float.compare(Float.NaN, 0.0f) == +1); assertTrue(Float.compare(Float.NaN, -0.0f) == +1); assertTrue(Float.compare(Float.NaN, -1.2f) == +1); assertTrue(Float.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(Float.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(1.2f, Float.NaN) == -1); assertTrue(Float.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(1.2f, 1.2f) == 0); assertTrue(Float.compare(1.2f, 0.0f) == +1); assertTrue(Float.compare(1.2f, -0.0f) == +1); assertTrue(Float.compare(1.2f, -1.2f) == +1); assertTrue(Float.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(0.0f, Float.NaN) == -1); assertTrue(Float.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(0.0f, 1.2f) == -1); assertTrue(Float.compare(0.0f, 0.0f) == 0); assertTrue(Float.compare(0.0f, -0.0f) == +1); assertTrue(Float.compare(0.0f, -1.2f) == +1); assertTrue(Float.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-0.0f, Float.NaN) == -1); assertTrue(Float.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-0.0f, 1.2f) == -1); assertTrue(Float.compare(-0.0f, 0.0f) == -1); assertTrue(Float.compare(-0.0f, -0.0f) == 0); assertTrue(Float.compare(-0.0f, -1.2f) == +1); assertTrue(Float.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-1.2f, Float.NaN) == -1); assertTrue(Float.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-1.2f, 1.2f) == -1); assertTrue(Float.compare(-1.2f, 0.0f) == -1); assertTrue(Float.compare(-1.2f, -0.0f) == -1); assertTrue(Float.compare(-1.2f, -1.2f) == 0); assertTrue(Float.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } public void testIsDigits() { assertEquals("isDigits(null) failed", false, NumberUtils.isDigits(null)); assertEquals("isDigits('') failed", false, NumberUtils.isDigits("")); assertEquals("isDigits(String) failed", true, NumberUtils.isDigits("12345")); assertEquals("isDigits(String) neg 1 failed", false, NumberUtils.isDigits("1234.5")); assertEquals("isDigits(String) neg 3 failed", false, NumberUtils.isDigits("1ab")); assertEquals("isDigits(String) neg 4 failed", false, NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(String val) { try { Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (NumberFormatException e) { return false; } } @SuppressWarnings("cast") // suppress instanceof warning check public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } }
@Test public void testMath718() { // for large trials the evaluation of ContinuedFraction was inaccurate // do a sweep over several large trials to test if the current implementation is // numerically stable. for (int trials = 500000; trials < 20000000; trials += 100000) { BinomialDistribution dist = new BinomialDistribution(trials, 0.5); int p = dist.inverseCumulativeProbability(0.5); Assert.assertEquals(trials / 2, p); } }
org.apache.commons.math3.distribution.BinomialDistributionTest::testMath718
src/test/java/org/apache/commons/math3/distribution/BinomialDistributionTest.java
143
src/test/java/org/apache/commons/math3/distribution/BinomialDistributionTest.java
testMath718
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.apache.commons.math3.distribution; import org.junit.Assert; import org.junit.Test; /** * Test cases for BinomialDistribution. Extends IntegerDistributionAbstractTest. * See class javadoc for IntegerDistributionAbstractTest for details. * * @version $Id$ * 2009) $ */ public class BinomialDistributionTest extends IntegerDistributionAbstractTest { // -------------- Implementations for abstract methods // ----------------------- /** Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { return new BinomialDistribution(10, 0.70); } /** Creates the default probability density test input values */ @Override public int[] makeDensityTestPoints() { return new int[] { -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; } /** Creates the default probability density test expected values */ @Override public double[] makeDensityTestValues() { return new double[] { 0d, 0.0000059049d, 0.000137781d, 0.0014467d, 0.00900169d, 0.0367569d, 0.102919d, 0.200121d, 0.266828d, 0.233474d, 0.121061d, 0.0282475d, 0d }; } /** Creates the default cumulative probability density test input values */ @Override public int[] makeCumulativeTestPoints() { return makeDensityTestPoints(); } /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] { 0d, 0.0000d, 0.0001d, 0.0016d, 0.0106d, 0.0473d, 0.1503d, 0.3504d, 0.6172d, 0.8507d, 0.9718d, 1d, 1d }; } /** Creates the default inverse cumulative probability test input values */ @Override public double[] makeInverseCumulativeTestPoints() { return new double[] { 0, 0.001d, 0.010d, 0.025d, 0.050d, 0.100d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d, 1 }; } /** * Creates the default inverse cumulative probability density test expected * values */ @Override public int[] makeInverseCumulativeTestValues() { return new int[] { 0, 2, 3, 4, 5, 5, 10, 10, 10, 9, 9, 10 }; } // ----------------- Additional test cases --------------------------------- /** Test degenerate case p = 0 */ @Test public void testDegenerate0() throws Exception { BinomialDistribution dist = new BinomialDistribution(5, 0.0d); setDistribution(dist); setCumulativeTestPoints(new int[] { -1, 0, 1, 5, 10 }); setCumulativeTestValues(new double[] { 0d, 1d, 1d, 1d, 1d }); setDensityTestPoints(new int[] { -1, 0, 1, 10, 11 }); setDensityTestValues(new double[] { 0d, 1d, 0d, 0d, 0d }); setInverseCumulativeTestPoints(new double[] { 0.1d, 0.5d }); setInverseCumulativeTestValues(new int[] { 0, 0 }); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 0); Assert.assertEquals(dist.getSupportUpperBound(), 0); } /** Test degenerate case p = 1 */ @Test public void testDegenerate1() throws Exception { BinomialDistribution dist = new BinomialDistribution(5, 1.0d); setDistribution(dist); setCumulativeTestPoints(new int[] { -1, 0, 1, 2, 5, 10 }); setCumulativeTestValues(new double[] { 0d, 0d, 0d, 0d, 1d, 1d }); setDensityTestPoints(new int[] { -1, 0, 1, 2, 5, 10 }); setDensityTestValues(new double[] { 0d, 0d, 0d, 0d, 1d, 0d }); setInverseCumulativeTestPoints(new double[] { 0.1d, 0.5d }); setInverseCumulativeTestValues(new int[] { 5, 5 }); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 5); Assert.assertEquals(dist.getSupportUpperBound(), 5); } @Test public void testMoments() { final double tol = 1e-9; BinomialDistribution dist; dist = new BinomialDistribution(10, 0.5); Assert.assertEquals(dist.getNumericalMean(), 10d * 0.5d, tol); Assert.assertEquals(dist.getNumericalVariance(), 10d * 0.5d * 0.5d, tol); dist = new BinomialDistribution(30, 0.3); Assert.assertEquals(dist.getNumericalMean(), 30d * 0.3d, tol); Assert.assertEquals(dist.getNumericalVariance(), 30d * 0.3d * (1d - 0.3d), tol); } @Test public void testMath718() { // for large trials the evaluation of ContinuedFraction was inaccurate // do a sweep over several large trials to test if the current implementation is // numerically stable. for (int trials = 500000; trials < 20000000; trials += 100000) { BinomialDistribution dist = new BinomialDistribution(trials, 0.5); int p = dist.inverseCumulativeProbability(0.5); Assert.assertEquals(trials / 2, p); } } }
// You are a professional Java test case writer, please create a test case named `testMath718` for the issue `Math-MATH-718`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-718 // // ## Issue-Title: // inverseCumulativeProbability of BinomialDistribution returns wrong value for large trials. // // ## Issue-Description: // // The inverseCumulativeProbability method of the BinomialDistributionImpl class returns wrong value for large trials. Following code will be reproduce the problem. // // // System.out.println(new BinomialDistributionImpl(1000000, 0.5).inverseCumulativeProbability(0.5)); // // // This returns 499525, though it should be 499999. // // // I'm not sure how it should be fixed, but the cause is that the cumulativeProbability method returns Infinity, not NaN. As the result the checkedCumulativeProbability method doesn't work as expected. // // // // // @Test public void testMath718() {
143
31
131
src/test/java/org/apache/commons/math3/distribution/BinomialDistributionTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-718 ## Issue-Title: inverseCumulativeProbability of BinomialDistribution returns wrong value for large trials. ## Issue-Description: The inverseCumulativeProbability method of the BinomialDistributionImpl class returns wrong value for large trials. Following code will be reproduce the problem. System.out.println(new BinomialDistributionImpl(1000000, 0.5).inverseCumulativeProbability(0.5)); This returns 499525, though it should be 499999. I'm not sure how it should be fixed, but the cause is that the cumulativeProbability method returns Infinity, not NaN. As the result the checkedCumulativeProbability method doesn't work as expected. ``` You are a professional Java test case writer, please create a test case named `testMath718` for the issue `Math-MATH-718`, utilizing the provided issue report information and the following function signature. ```java @Test public void testMath718() { ```
131
[ "org.apache.commons.math3.util.ContinuedFraction" ]
0eceeb94c3061dbedfb0f08ec976aea989d49d3dba7c81e628fb8d65f1136578
@Test public void testMath718()
// You are a professional Java test case writer, please create a test case named `testMath718` for the issue `Math-MATH-718`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-718 // // ## Issue-Title: // inverseCumulativeProbability of BinomialDistribution returns wrong value for large trials. // // ## Issue-Description: // // The inverseCumulativeProbability method of the BinomialDistributionImpl class returns wrong value for large trials. Following code will be reproduce the problem. // // // System.out.println(new BinomialDistributionImpl(1000000, 0.5).inverseCumulativeProbability(0.5)); // // // This returns 499525, though it should be 499999. // // // I'm not sure how it should be fixed, but the cause is that the cumulativeProbability method returns Infinity, not NaN. As the result the checkedCumulativeProbability method doesn't work as expected. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.apache.commons.math3.distribution; import org.junit.Assert; import org.junit.Test; /** * Test cases for BinomialDistribution. Extends IntegerDistributionAbstractTest. * See class javadoc for IntegerDistributionAbstractTest for details. * * @version $Id$ * 2009) $ */ public class BinomialDistributionTest extends IntegerDistributionAbstractTest { // -------------- Implementations for abstract methods // ----------------------- /** Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { return new BinomialDistribution(10, 0.70); } /** Creates the default probability density test input values */ @Override public int[] makeDensityTestPoints() { return new int[] { -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; } /** Creates the default probability density test expected values */ @Override public double[] makeDensityTestValues() { return new double[] { 0d, 0.0000059049d, 0.000137781d, 0.0014467d, 0.00900169d, 0.0367569d, 0.102919d, 0.200121d, 0.266828d, 0.233474d, 0.121061d, 0.0282475d, 0d }; } /** Creates the default cumulative probability density test input values */ @Override public int[] makeCumulativeTestPoints() { return makeDensityTestPoints(); } /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] { 0d, 0.0000d, 0.0001d, 0.0016d, 0.0106d, 0.0473d, 0.1503d, 0.3504d, 0.6172d, 0.8507d, 0.9718d, 1d, 1d }; } /** Creates the default inverse cumulative probability test input values */ @Override public double[] makeInverseCumulativeTestPoints() { return new double[] { 0, 0.001d, 0.010d, 0.025d, 0.050d, 0.100d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d, 1 }; } /** * Creates the default inverse cumulative probability density test expected * values */ @Override public int[] makeInverseCumulativeTestValues() { return new int[] { 0, 2, 3, 4, 5, 5, 10, 10, 10, 9, 9, 10 }; } // ----------------- Additional test cases --------------------------------- /** Test degenerate case p = 0 */ @Test public void testDegenerate0() throws Exception { BinomialDistribution dist = new BinomialDistribution(5, 0.0d); setDistribution(dist); setCumulativeTestPoints(new int[] { -1, 0, 1, 5, 10 }); setCumulativeTestValues(new double[] { 0d, 1d, 1d, 1d, 1d }); setDensityTestPoints(new int[] { -1, 0, 1, 10, 11 }); setDensityTestValues(new double[] { 0d, 1d, 0d, 0d, 0d }); setInverseCumulativeTestPoints(new double[] { 0.1d, 0.5d }); setInverseCumulativeTestValues(new int[] { 0, 0 }); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 0); Assert.assertEquals(dist.getSupportUpperBound(), 0); } /** Test degenerate case p = 1 */ @Test public void testDegenerate1() throws Exception { BinomialDistribution dist = new BinomialDistribution(5, 1.0d); setDistribution(dist); setCumulativeTestPoints(new int[] { -1, 0, 1, 2, 5, 10 }); setCumulativeTestValues(new double[] { 0d, 0d, 0d, 0d, 1d, 1d }); setDensityTestPoints(new int[] { -1, 0, 1, 2, 5, 10 }); setDensityTestValues(new double[] { 0d, 0d, 0d, 0d, 1d, 0d }); setInverseCumulativeTestPoints(new double[] { 0.1d, 0.5d }); setInverseCumulativeTestValues(new int[] { 5, 5 }); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 5); Assert.assertEquals(dist.getSupportUpperBound(), 5); } @Test public void testMoments() { final double tol = 1e-9; BinomialDistribution dist; dist = new BinomialDistribution(10, 0.5); Assert.assertEquals(dist.getNumericalMean(), 10d * 0.5d, tol); Assert.assertEquals(dist.getNumericalVariance(), 10d * 0.5d * 0.5d, tol); dist = new BinomialDistribution(30, 0.3); Assert.assertEquals(dist.getNumericalMean(), 30d * 0.3d, tol); Assert.assertEquals(dist.getNumericalVariance(), 30d * 0.3d * (1d - 0.3d), tol); } @Test public void testMath718() { // for large trials the evaluation of ContinuedFraction was inaccurate // do a sweep over several large trials to test if the current implementation is // numerically stable. for (int trials = 500000; trials < 20000000; trials += 100000) { BinomialDistribution dist = new BinomialDistribution(trials, 0.5); int p = dist.inverseCumulativeProbability(0.5); Assert.assertEquals(trials / 2, p); } } }
@Test public void discardsSpuriousByteOrderMarkWhenNoCharsetSet() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, null, "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); assertEquals("UTF-8", doc.outputSettings().charset().displayName()); }
org.jsoup.helper.DataUtilTest::discardsSpuriousByteOrderMarkWhenNoCharsetSet
src/test/java/org/jsoup/helper/DataUtilTest.java
43
src/test/java/org/jsoup/helper/DataUtilTest.java
discardsSpuriousByteOrderMarkWhenNoCharsetSet
package org.jsoup.helper; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import org.junit.Test; import java.nio.ByteBuffer; import java.nio.charset.Charset; import static org.junit.Assert.assertEquals; public class DataUtilTest { @Test public void testCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); assertEquals(null, DataUtil.getCharsetFromContentType("text/html;charset=Unknown")); } @Test public void testQuotedCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html; charset=\"utf-8\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=\"UTF-8\"")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=\"ISO-8859-1\"")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=\"Unsupported\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset='UTF-8'")); } @Test public void discardsSpuriousByteOrderMark() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, "UTF-8", "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); } @Test public void discardsSpuriousByteOrderMarkWhenNoCharsetSet() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, null, "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); assertEquals("UTF-8", doc.outputSettings().charset().displayName()); } @Test public void shouldNotThrowExceptionOnEmptyCharset() { assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=;")); } @Test public void shouldSelectFirstCharsetOnWeirdMultileCharsetsInMetaTags() { assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1, charset=1251")); } @Test public void shouldCorrectCharsetForDuplicateCharsetString() { assertEquals("iso-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=charset=iso-8859-1")); } @Test public void shouldReturnNullForIllegalCharsetNames() { assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=$HJKDF§$/(")); } }
// You are a professional Java test case writer, please create a test case named `discardsSpuriousByteOrderMarkWhenNoCharsetSet` for the issue `Jsoup-348`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-348 // // ## Issue-Title: // JSoup incorrectly moves content from the <head> section into <body> for sample URL // // ## Issue-Description: // If you load the following URL: // // // // ``` // http://jornutzon.sydneyoperahouse.com/home.htm // // ``` // // into: // // // // ``` // http://try.jsoup.org/ // // ``` // // then it will move the content from the "head" section into the "body" section. The URL // // being parsed validates using the W3C validator: // // // <http://validator.w3.org/check?uri=http%3A%2F%2Fjornutzon.sydneyoperahouse.com%2Fhome.htm&charset=%28detect+automatically%29&doctype=Inline&ss=1&group=0&user-agent=W3C_Validator%2F1.3+http%3A%2F%2Fvalidator.w3.org%2Fservices> // // // We are using JSoup 1.7.2 // // // // @Test public void discardsSpuriousByteOrderMarkWhenNoCharsetSet() {
43
39
37
src/test/java/org/jsoup/helper/DataUtilTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-348 ## Issue-Title: JSoup incorrectly moves content from the <head> section into <body> for sample URL ## Issue-Description: If you load the following URL: ``` http://jornutzon.sydneyoperahouse.com/home.htm ``` into: ``` http://try.jsoup.org/ ``` then it will move the content from the "head" section into the "body" section. The URL being parsed validates using the W3C validator: <http://validator.w3.org/check?uri=http%3A%2F%2Fjornutzon.sydneyoperahouse.com%2Fhome.htm&charset=%28detect+automatically%29&doctype=Inline&ss=1&group=0&user-agent=W3C_Validator%2F1.3+http%3A%2F%2Fvalidator.w3.org%2Fservices> We are using JSoup 1.7.2 ``` You are a professional Java test case writer, please create a test case named `discardsSpuriousByteOrderMarkWhenNoCharsetSet` for the issue `Jsoup-348`, utilizing the provided issue report information and the following function signature. ```java @Test public void discardsSpuriousByteOrderMarkWhenNoCharsetSet() { ```
37
[ "org.jsoup.helper.DataUtil" ]
0ef1d441e2b50fd5fd41ba1f387a6759a0f1a35b65ab93fdb57319f26803b6c5
@Test public void discardsSpuriousByteOrderMarkWhenNoCharsetSet()
// You are a professional Java test case writer, please create a test case named `discardsSpuriousByteOrderMarkWhenNoCharsetSet` for the issue `Jsoup-348`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-348 // // ## Issue-Title: // JSoup incorrectly moves content from the <head> section into <body> for sample URL // // ## Issue-Description: // If you load the following URL: // // // // ``` // http://jornutzon.sydneyoperahouse.com/home.htm // // ``` // // into: // // // // ``` // http://try.jsoup.org/ // // ``` // // then it will move the content from the "head" section into the "body" section. The URL // // being parsed validates using the W3C validator: // // // <http://validator.w3.org/check?uri=http%3A%2F%2Fjornutzon.sydneyoperahouse.com%2Fhome.htm&charset=%28detect+automatically%29&doctype=Inline&ss=1&group=0&user-agent=W3C_Validator%2F1.3+http%3A%2F%2Fvalidator.w3.org%2Fservices> // // // We are using JSoup 1.7.2 // // // //
Jsoup
package org.jsoup.helper; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import org.junit.Test; import java.nio.ByteBuffer; import java.nio.charset.Charset; import static org.junit.Assert.assertEquals; public class DataUtilTest { @Test public void testCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); assertEquals(null, DataUtil.getCharsetFromContentType("text/html;charset=Unknown")); } @Test public void testQuotedCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html; charset=\"utf-8\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=\"UTF-8\"")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=\"ISO-8859-1\"")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=\"Unsupported\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset='UTF-8'")); } @Test public void discardsSpuriousByteOrderMark() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, "UTF-8", "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); } @Test public void discardsSpuriousByteOrderMarkWhenNoCharsetSet() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, null, "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); assertEquals("UTF-8", doc.outputSettings().charset().displayName()); } @Test public void shouldNotThrowExceptionOnEmptyCharset() { assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=;")); } @Test public void shouldSelectFirstCharsetOnWeirdMultileCharsetsInMetaTags() { assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1, charset=1251")); } @Test public void shouldCorrectCharsetForDuplicateCharsetString() { assertEquals("iso-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=charset=iso-8859-1")); } @Test public void shouldReturnNullForIllegalCharsetNames() { assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=$HJKDF§$/(")); } }
public void testNullSafeBugDeserialize() throws Exception { Device device = gson.fromJson("{'id':'ec57803e2'}", Device.class); assertEquals("ec57803e2", device.id); }
com.google.gson.regression.JsonAdapterNullSafeTest::testNullSafeBugDeserialize
gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java
36
gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java
testNullSafeBugDeserialize
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.regression; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.JsonAdapter; import com.google.gson.reflect.TypeToken; import junit.framework.TestCase; public class JsonAdapterNullSafeTest extends TestCase { private final Gson gson = new Gson(); public void testNullSafeBugSerialize() throws Exception { Device device = new Device("ec57803e"); gson.toJson(device); } public void testNullSafeBugDeserialize() throws Exception { Device device = gson.fromJson("{'id':'ec57803e2'}", Device.class); assertEquals("ec57803e2", device.id); } @JsonAdapter(Device.JsonAdapterFactory.class) private static final class Device { String id; Device(String id) { this.id = id; } static final class JsonAdapterFactory implements TypeAdapterFactory { // The recursiveCall in {@link Device.JsonAdapterFactory} is the source of this bug // because we use it to return a null type adapter on a recursive call. private static final ThreadLocal<Boolean> recursiveCall = new ThreadLocal<Boolean>(); @SuppressWarnings({"unchecked", "rawtypes"}) @Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { if (type.getRawType() != Device.class || recursiveCall.get() != null) { recursiveCall.set(null); // clear for subsequent use return null; } recursiveCall.set(Boolean.TRUE); return (TypeAdapter) gson.getDelegateAdapter(this, type); } } } }
// You are a professional Java test case writer, please create a test case named `testNullSafeBugDeserialize` for the issue `Gson-800`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-800 // // ## Issue-Title: // Fixed a regression in Gson 2.6 where Gson caused NPE if the TypeAdapt… // // ## Issue-Description: // …erFactory.create() returned null. // // // // public void testNullSafeBugDeserialize() throws Exception {
36
6
33
gson/src/test/java/com/google/gson/regression/JsonAdapterNullSafeTest.java
gson/src/test/java
```markdown ## Issue-ID: Gson-800 ## Issue-Title: Fixed a regression in Gson 2.6 where Gson caused NPE if the TypeAdapt… ## Issue-Description: …erFactory.create() returned null. ``` You are a professional Java test case writer, please create a test case named `testNullSafeBugDeserialize` for the issue `Gson-800`, utilizing the provided issue report information and the following function signature. ```java public void testNullSafeBugDeserialize() throws Exception { ```
33
[ "com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory" ]
0fe67d3707dfee04d2a96e1ee61958f0026324d109d4fb0a6db95de64330b511
public void testNullSafeBugDeserialize() throws Exception
// You are a professional Java test case writer, please create a test case named `testNullSafeBugDeserialize` for the issue `Gson-800`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-800 // // ## Issue-Title: // Fixed a regression in Gson 2.6 where Gson caused NPE if the TypeAdapt… // // ## Issue-Description: // …erFactory.create() returned null. // // // //
Gson
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.regression; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.JsonAdapter; import com.google.gson.reflect.TypeToken; import junit.framework.TestCase; public class JsonAdapterNullSafeTest extends TestCase { private final Gson gson = new Gson(); public void testNullSafeBugSerialize() throws Exception { Device device = new Device("ec57803e"); gson.toJson(device); } public void testNullSafeBugDeserialize() throws Exception { Device device = gson.fromJson("{'id':'ec57803e2'}", Device.class); assertEquals("ec57803e2", device.id); } @JsonAdapter(Device.JsonAdapterFactory.class) private static final class Device { String id; Device(String id) { this.id = id; } static final class JsonAdapterFactory implements TypeAdapterFactory { // The recursiveCall in {@link Device.JsonAdapterFactory} is the source of this bug // because we use it to return a null type adapter on a recursive call. private static final ThreadLocal<Boolean> recursiveCall = new ThreadLocal<Boolean>(); @SuppressWarnings({"unchecked", "rawtypes"}) @Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { if (type.getRawType() != Device.class || recursiveCall.get() != null) { recursiveCall.set(null); // clear for subsequent use return null; } recursiveCall.set(Boolean.TRUE); return (TypeAdapter) gson.getDelegateAdapter(this, type); } } } }
@Test public void testUnivariateDistribution() { final double[] mu = { -1.5 }; final double[][] sigma = { { 1 } }; final MultivariateNormalDistribution multi = new MultivariateNormalDistribution(mu, sigma); final NormalDistribution uni = new NormalDistribution(mu[0], sigma[0][0]); final Random rng = new Random(); final int numCases = 100; final double tol = Math.ulp(1d); for (int i = 0; i < numCases; i++) { final double v = rng.nextDouble() * 10 - 5; Assert.assertEquals(uni.density(v), multi.density(new double[] { v }), tol); } }
org.apache.commons.math3.distribution.MultivariateNormalDistributionTest::testUnivariateDistribution
src/test/java/org/apache/commons/math3/distribution/MultivariateNormalDistributionTest.java
152
src/test/java/org/apache/commons/math3/distribution/MultivariateNormalDistributionTest.java
testUnivariateDistribution
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.distribution; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.linear.RealMatrix; import java.util.Random; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Test cases for {@link MultivariateNormalDistribution}. */ public class MultivariateNormalDistributionTest { /** * Test the ability of the distribution to report its mean value parameter. */ @Test public void testGetMean() { final double[] mu = { -1.5, 2 }; final double[][] sigma = { { 2, -1.1 }, { -1.1, 2 } }; final MultivariateNormalDistribution d = new MultivariateNormalDistribution(mu, sigma); final double[] m = d.getMeans(); for (int i = 0; i < m.length; i++) { Assert.assertEquals(mu[i], m[i], 0); } } /** * Test the ability of the distribution to report its covariance matrix parameter. */ @Test public void testGetCovarianceMatrix() { final double[] mu = { -1.5, 2 }; final double[][] sigma = { { 2, -1.1 }, { -1.1, 2 } }; final MultivariateNormalDistribution d = new MultivariateNormalDistribution(mu, sigma); final RealMatrix s = d.getCovariances(); final int dim = d.getDimension(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { Assert.assertEquals(sigma[i][j], s.getEntry(i, j), 0); } } } /** * Test the accuracy of sampling from the distribution. */ @Test public void testSampling() { final double[] mu = { -1.5, 2 }; final double[][] sigma = { { 2, -1.1 }, { -1.1, 2 } }; final MultivariateNormalDistribution d = new MultivariateNormalDistribution(mu, sigma); d.reseedRandomGenerator(50); final int n = 500000; final double[][] samples = d.sample(n); final int dim = d.getDimension(); final double[] sampleMeans = new double[dim]; for (int i = 0; i < samples.length; i++) { for (int j = 0; j < dim; j++) { sampleMeans[j] += samples[i][j]; } } final double sampledValueTolerance = 1e-2; for (int j = 0; j < dim; j++) { sampleMeans[j] /= samples.length; Assert.assertEquals(mu[j], sampleMeans[j], sampledValueTolerance); } final double[][] sampleSigma = new Covariance(samples).getCovarianceMatrix().getData(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { Assert.assertEquals(sigma[i][j], sampleSigma[i][j], sampledValueTolerance); } } } /** * Test the accuracy of the distribution when calculating densities. */ @Test public void testDensities() { final double[] mu = { -1.5, 2 }; final double[][] sigma = { { 2, -1.1 }, { -1.1, 2 } }; final MultivariateNormalDistribution d = new MultivariateNormalDistribution(mu, sigma); final double[][] testValues = { { -1.5, 2 }, { 4, 4 }, { 1.5, -2 }, { 0, 0 } }; final double[] densities = new double[testValues.length]; for (int i = 0; i < densities.length; i++) { densities[i] = d.density(testValues[i]); } // From dmvnorm function in R 2.15 CRAN package Mixtools v0.4.5 final double[] correctDensities = { 0.09528357207691344, 5.80932710124009e-09, 0.001387448895173267, 0.03309922090210541 }; for (int i = 0; i < testValues.length; i++) { Assert.assertEquals(correctDensities[i], densities[i], 1e-16); } } /** * Test the accuracy of the distribution when calculating densities. */ @Test public void testUnivariateDistribution() { final double[] mu = { -1.5 }; final double[][] sigma = { { 1 } }; final MultivariateNormalDistribution multi = new MultivariateNormalDistribution(mu, sigma); final NormalDistribution uni = new NormalDistribution(mu[0], sigma[0][0]); final Random rng = new Random(); final int numCases = 100; final double tol = Math.ulp(1d); for (int i = 0; i < numCases; i++) { final double v = rng.nextDouble() * 10 - 5; Assert.assertEquals(uni.density(v), multi.density(new double[] { v }), tol); } } }
// You are a professional Java test case writer, please create a test case named `testUnivariateDistribution` for the issue `Math-MATH-929`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-929 // // ## Issue-Title: // MultivariateNormalDistribution.density(double[]) returns wrong value when the dimension is odd // // ## Issue-Description: // // To reproduce: // // // // // ``` // Assert.assertEquals(0.398942280401433, new MultivariateNormalDistribution(new double[]{0}, new double[][]{{1}}).density(new double[]{0}), 1e-15); // // ``` // // // // // @Test public void testUnivariateDistribution() {
152
/** * Test the accuracy of the distribution when calculating densities. */
11
137
src/test/java/org/apache/commons/math3/distribution/MultivariateNormalDistributionTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-929 ## Issue-Title: MultivariateNormalDistribution.density(double[]) returns wrong value when the dimension is odd ## Issue-Description: To reproduce: ``` Assert.assertEquals(0.398942280401433, new MultivariateNormalDistribution(new double[]{0}, new double[][]{{1}}).density(new double[]{0}), 1e-15); ``` ``` You are a professional Java test case writer, please create a test case named `testUnivariateDistribution` for the issue `Math-MATH-929`, utilizing the provided issue report information and the following function signature. ```java @Test public void testUnivariateDistribution() { ```
137
[ "org.apache.commons.math3.distribution.MultivariateNormalDistribution" ]
10242451b83c50d9aa25fb2900dbbdaf211cead024c525cac6dba584fadc8d1e
@Test public void testUnivariateDistribution()
// You are a professional Java test case writer, please create a test case named `testUnivariateDistribution` for the issue `Math-MATH-929`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-929 // // ## Issue-Title: // MultivariateNormalDistribution.density(double[]) returns wrong value when the dimension is odd // // ## Issue-Description: // // To reproduce: // // // // // ``` // Assert.assertEquals(0.398942280401433, new MultivariateNormalDistribution(new double[]{0}, new double[][]{{1}}).density(new double[]{0}), 1e-15); // // ``` // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.distribution; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.linear.RealMatrix; import java.util.Random; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Test cases for {@link MultivariateNormalDistribution}. */ public class MultivariateNormalDistributionTest { /** * Test the ability of the distribution to report its mean value parameter. */ @Test public void testGetMean() { final double[] mu = { -1.5, 2 }; final double[][] sigma = { { 2, -1.1 }, { -1.1, 2 } }; final MultivariateNormalDistribution d = new MultivariateNormalDistribution(mu, sigma); final double[] m = d.getMeans(); for (int i = 0; i < m.length; i++) { Assert.assertEquals(mu[i], m[i], 0); } } /** * Test the ability of the distribution to report its covariance matrix parameter. */ @Test public void testGetCovarianceMatrix() { final double[] mu = { -1.5, 2 }; final double[][] sigma = { { 2, -1.1 }, { -1.1, 2 } }; final MultivariateNormalDistribution d = new MultivariateNormalDistribution(mu, sigma); final RealMatrix s = d.getCovariances(); final int dim = d.getDimension(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { Assert.assertEquals(sigma[i][j], s.getEntry(i, j), 0); } } } /** * Test the accuracy of sampling from the distribution. */ @Test public void testSampling() { final double[] mu = { -1.5, 2 }; final double[][] sigma = { { 2, -1.1 }, { -1.1, 2 } }; final MultivariateNormalDistribution d = new MultivariateNormalDistribution(mu, sigma); d.reseedRandomGenerator(50); final int n = 500000; final double[][] samples = d.sample(n); final int dim = d.getDimension(); final double[] sampleMeans = new double[dim]; for (int i = 0; i < samples.length; i++) { for (int j = 0; j < dim; j++) { sampleMeans[j] += samples[i][j]; } } final double sampledValueTolerance = 1e-2; for (int j = 0; j < dim; j++) { sampleMeans[j] /= samples.length; Assert.assertEquals(mu[j], sampleMeans[j], sampledValueTolerance); } final double[][] sampleSigma = new Covariance(samples).getCovarianceMatrix().getData(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { Assert.assertEquals(sigma[i][j], sampleSigma[i][j], sampledValueTolerance); } } } /** * Test the accuracy of the distribution when calculating densities. */ @Test public void testDensities() { final double[] mu = { -1.5, 2 }; final double[][] sigma = { { 2, -1.1 }, { -1.1, 2 } }; final MultivariateNormalDistribution d = new MultivariateNormalDistribution(mu, sigma); final double[][] testValues = { { -1.5, 2 }, { 4, 4 }, { 1.5, -2 }, { 0, 0 } }; final double[] densities = new double[testValues.length]; for (int i = 0; i < densities.length; i++) { densities[i] = d.density(testValues[i]); } // From dmvnorm function in R 2.15 CRAN package Mixtools v0.4.5 final double[] correctDensities = { 0.09528357207691344, 5.80932710124009e-09, 0.001387448895173267, 0.03309922090210541 }; for (int i = 0; i < testValues.length; i++) { Assert.assertEquals(correctDensities[i], densities[i], 1e-16); } } /** * Test the accuracy of the distribution when calculating densities. */ @Test public void testUnivariateDistribution() { final double[] mu = { -1.5 }; final double[][] sigma = { { 1 } }; final MultivariateNormalDistribution multi = new MultivariateNormalDistribution(mu, sigma); final NormalDistribution uni = new NormalDistribution(mu[0], sigma[0][0]); final Random rng = new Random(); final int numCases = 100; final double tol = Math.ulp(1d); for (int i = 0; i < numCases; i++) { final double v = rng.nextDouble() * 10 - 5; Assert.assertEquals(uni.density(v), multi.density(new double[] { v }), tol); } } }
@Test public void readOfLength0ShouldReturn0() throws Exception { // Create a big random piece of data byte[] rawData = new byte[1048576]; for (int i=0; i < rawData.length; ++i) { rawData[i] = (byte) Math.floor(Math.random()*256); } // Compress it ByteArrayOutputStream baos = new ByteArrayOutputStream(); BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos); bzipOut.write(rawData); bzipOut.flush(); bzipOut.close(); baos.flush(); baos.close(); // Try to read it back in ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais); byte[] buffer = new byte[1024]; Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0)); Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); bzipIn.close(); }
org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStreamTest::readOfLength0ShouldReturn0
src/test/java/org/apache/commons/compress/compressors/bzip2/BZip2CompressorInputStreamTest.java
69
src/test/java/org/apache/commons/compress/compressors/bzip2/BZip2CompressorInputStreamTest.java
readOfLength0ShouldReturn0
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.compress.compressors.bzip2; import static org.apache.commons.compress.AbstractTestCase.getFile; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class BZip2CompressorInputStreamTest { @Test(expected = IOException.class) public void shouldThrowAnIOExceptionWhenAppliedToAZipFile() throws Exception { FileInputStream in = new FileInputStream(getFile("bla.zip")); try { new BZip2CompressorInputStream(in); } finally { in.close(); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-309" */ @Test public void readOfLength0ShouldReturn0() throws Exception { // Create a big random piece of data byte[] rawData = new byte[1048576]; for (int i=0; i < rawData.length; ++i) { rawData[i] = (byte) Math.floor(Math.random()*256); } // Compress it ByteArrayOutputStream baos = new ByteArrayOutputStream(); BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos); bzipOut.write(rawData); bzipOut.flush(); bzipOut.close(); baos.flush(); baos.close(); // Try to read it back in ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais); byte[] buffer = new byte[1024]; Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0)); Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); bzipIn.close(); } }
// You are a professional Java test case writer, please create a test case named `readOfLength0ShouldReturn0` for the issue `Compress-COMPRESS-309`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-309 // // ## Issue-Title: // BZip2CompressorInputStream return value wrong when told to read to a full buffer. // // ## Issue-Description: // // BZip2CompressorInputStream.read(buffer, offset, length) returns -1 when given an offset equal to the length of the buffer. // // // This indicates, not that the buffer was full, but that the stream was finished. // // // It seems like a pretty stupid thing to do - but I'm getting this when trying to use Kryo serialization (which is probably a bug on their part, too), so it does occur and has negative affects. // // // Here's a JUnit test that shows the problem specifically: // // // // // ``` // @Test // public void testApacheCommonsBZipUncompression () throws Exception { // // Create a big random piece of data // byte[] rawData = new byte[1048576]; // for (int i=0; i<rawData.length; ++i) { // rawData[i] = (byte) Math.floor(Math.random()*256); // } // // // Compress it // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos); // bzipOut.write(rawData); // bzipOut.flush(); // bzipOut.close(); // baos.flush(); // baos.close(); // // // Try to read it back in // ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais); // byte[] buffer = new byte[1024]; // // Works fine // Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); // // Fails, returns -1 (indicating the stream is complete rather than that the buffer // // was full) // Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0)); // // But if you change the above expected value to -1, the following line still works // Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); // bzipIn.close(); // } // // ``` // // // // // @Test public void readOfLength0ShouldReturn0() throws Exception {
69
/** * @see "https://issues.apache.org/jira/browse/COMPRESS-309" */
30
44
src/test/java/org/apache/commons/compress/compressors/bzip2/BZip2CompressorInputStreamTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-309 ## Issue-Title: BZip2CompressorInputStream return value wrong when told to read to a full buffer. ## Issue-Description: BZip2CompressorInputStream.read(buffer, offset, length) returns -1 when given an offset equal to the length of the buffer. This indicates, not that the buffer was full, but that the stream was finished. It seems like a pretty stupid thing to do - but I'm getting this when trying to use Kryo serialization (which is probably a bug on their part, too), so it does occur and has negative affects. Here's a JUnit test that shows the problem specifically: ``` @Test public void testApacheCommonsBZipUncompression () throws Exception { // Create a big random piece of data byte[] rawData = new byte[1048576]; for (int i=0; i<rawData.length; ++i) { rawData[i] = (byte) Math.floor(Math.random()*256); } // Compress it ByteArrayOutputStream baos = new ByteArrayOutputStream(); BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos); bzipOut.write(rawData); bzipOut.flush(); bzipOut.close(); baos.flush(); baos.close(); // Try to read it back in ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais); byte[] buffer = new byte[1024]; // Works fine Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); // Fails, returns -1 (indicating the stream is complete rather than that the buffer // was full) Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0)); // But if you change the above expected value to -1, the following line still works Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); bzipIn.close(); } ``` ``` You are a professional Java test case writer, please create a test case named `readOfLength0ShouldReturn0` for the issue `Compress-COMPRESS-309`, utilizing the provided issue report information and the following function signature. ```java @Test public void readOfLength0ShouldReturn0() throws Exception { ```
44
[ "org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream" ]
108d2f37ad1c176b66edf107c27b8bda3a7ef20b2351330d43624fb1a40dff5f
@Test public void readOfLength0ShouldReturn0() throws Exception
// You are a professional Java test case writer, please create a test case named `readOfLength0ShouldReturn0` for the issue `Compress-COMPRESS-309`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-309 // // ## Issue-Title: // BZip2CompressorInputStream return value wrong when told to read to a full buffer. // // ## Issue-Description: // // BZip2CompressorInputStream.read(buffer, offset, length) returns -1 when given an offset equal to the length of the buffer. // // // This indicates, not that the buffer was full, but that the stream was finished. // // // It seems like a pretty stupid thing to do - but I'm getting this when trying to use Kryo serialization (which is probably a bug on their part, too), so it does occur and has negative affects. // // // Here's a JUnit test that shows the problem specifically: // // // // // ``` // @Test // public void testApacheCommonsBZipUncompression () throws Exception { // // Create a big random piece of data // byte[] rawData = new byte[1048576]; // for (int i=0; i<rawData.length; ++i) { // rawData[i] = (byte) Math.floor(Math.random()*256); // } // // // Compress it // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos); // bzipOut.write(rawData); // bzipOut.flush(); // bzipOut.close(); // baos.flush(); // baos.close(); // // // Try to read it back in // ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais); // byte[] buffer = new byte[1024]; // // Works fine // Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); // // Fails, returns -1 (indicating the stream is complete rather than that the buffer // // was full) // Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0)); // // But if you change the above expected value to -1, the following line still works // Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); // bzipIn.close(); // } // // ``` // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.compress.compressors.bzip2; import static org.apache.commons.compress.AbstractTestCase.getFile; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class BZip2CompressorInputStreamTest { @Test(expected = IOException.class) public void shouldThrowAnIOExceptionWhenAppliedToAZipFile() throws Exception { FileInputStream in = new FileInputStream(getFile("bla.zip")); try { new BZip2CompressorInputStream(in); } finally { in.close(); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-309" */ @Test public void readOfLength0ShouldReturn0() throws Exception { // Create a big random piece of data byte[] rawData = new byte[1048576]; for (int i=0; i < rawData.length; ++i) { rawData[i] = (byte) Math.floor(Math.random()*256); } // Compress it ByteArrayOutputStream baos = new ByteArrayOutputStream(); BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos); bzipOut.write(rawData); bzipOut.flush(); bzipOut.close(); baos.flush(); baos.close(); // Try to read it back in ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais); byte[] buffer = new byte[1024]; Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0)); Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024)); bzipIn.close(); } }
@Test public void shouldStubbingWork() { Mockito.when(iterable.iterator()).thenReturn(myIterator); Assert.assertNotNull(((Iterable) iterable).iterator()); Assert.assertNotNull(iterable.iterator()); }
org.mockitousage.bugs.InheritedGenericsPolimorphicCallTest::shouldStubbingWork
test/org/mockitousage/bugs/InheritedGenericsPolimorphicCallTest.java
40
test/org/mockitousage/bugs/InheritedGenericsPolimorphicCallTest.java
shouldStubbingWork
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.bugs; import static org.mockito.Mockito.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.mockitoutil.TestBase; @SuppressWarnings("unchecked") //see issue 200 public class InheritedGenericsPolimorphicCallTest extends TestBase { protected interface MyIterable<T> extends Iterable<T> { public MyIterator<T> iterator(); } protected interface MyIterator<T> extends Iterator<T> { // adds nothing here } MyIterator<String> myIterator = Mockito.mock(MyIterator.class); MyIterable<String> iterable = Mockito.mock(MyIterable.class); @Test public void shouldStubbingWork() { Mockito.when(iterable.iterator()).thenReturn(myIterator); Assert.assertNotNull(((Iterable) iterable).iterator()); Assert.assertNotNull(iterable.iterator()); } @Test public void shouldVerificationWorks() { iterable.iterator(); verify(iterable).iterator(); verify((Iterable) iterable).iterator(); } @Test public void shouldWorkExactlyAsJavaProxyWould() { //given final List<Method> methods = new LinkedList<Method>(); InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { methods.add(method); return null; }}; iterable = (MyIterable) Proxy.newProxyInstance( this.getClass().getClassLoader(), new Class[] { MyIterable.class }, handler); //when iterable.iterator(); ((Iterable) iterable).iterator(); //then assertEquals(2, methods.size()); assertEquals(methods.get(0), methods.get(1)); } }
// You are a professional Java test case writer, please create a test case named `shouldStubbingWork` for the issue `Mockito-200`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-200 // // ## Issue-Title: // ArgumentCaptor.fromClass's return type should match a parameterized type // // ## Issue-Description: // `ArgumentCaptor.fromClass`'s return type should match a parameterized type. I.e. the expression `ArgumentCaptor.fromClass(Class<S>)` should be of type `ArgumentCaptor<U>` where `S` is a subtype of `U`. // // // For example: // // // // ``` // ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.fromClass(Consumer.class) // // ``` // // does not type check (i.e. it is a compile time error). It should type check. // // // The reasons that it is desirable for `ArgumentCaptor.fromClass` to allow expressions such as the example above to type check are: // // // 1. `ArgumentCaptor.fromClass` is intended to be a convenience method to allow the user to construct an ArgumentCaptor without casting the returned value. // // // Currently, the user can devise a workaround such as: // // // // ``` // ArgumentCaptor<? extends Consumer<String>> captor // = ArgumentCaptor.fromClass(Consumer.class) // // ``` // // This workaround is inconvenient, and so contrary to `ArgumentCaptor.fromClass` being a convenience method. // // // 2. It is inconsistent with `@Captor`, which can be applied to a field with a paramterized type. I.e. // // // // ``` // @Captor ArgumentCaptor<Consumer<String>> captor // // ``` // // type checks. // // // // @Test public void shouldStubbingWork() {
40
33
35
test/org/mockitousage/bugs/InheritedGenericsPolimorphicCallTest.java
test
```markdown ## Issue-ID: Mockito-200 ## Issue-Title: ArgumentCaptor.fromClass's return type should match a parameterized type ## Issue-Description: `ArgumentCaptor.fromClass`'s return type should match a parameterized type. I.e. the expression `ArgumentCaptor.fromClass(Class<S>)` should be of type `ArgumentCaptor<U>` where `S` is a subtype of `U`. For example: ``` ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.fromClass(Consumer.class) ``` does not type check (i.e. it is a compile time error). It should type check. The reasons that it is desirable for `ArgumentCaptor.fromClass` to allow expressions such as the example above to type check are: 1. `ArgumentCaptor.fromClass` is intended to be a convenience method to allow the user to construct an ArgumentCaptor without casting the returned value. Currently, the user can devise a workaround such as: ``` ArgumentCaptor<? extends Consumer<String>> captor = ArgumentCaptor.fromClass(Consumer.class) ``` This workaround is inconvenient, and so contrary to `ArgumentCaptor.fromClass` being a convenience method. 2. It is inconsistent with `@Captor`, which can be applied to a field with a paramterized type. I.e. ``` @Captor ArgumentCaptor<Consumer<String>> captor ``` type checks. ``` You are a professional Java test case writer, please create a test case named `shouldStubbingWork` for the issue `Mockito-200`, utilizing the provided issue report information and the following function signature. ```java @Test public void shouldStubbingWork() { ```
35
[ "org.mockito.internal.invocation.InvocationMatcher" ]
10c7e110d2b238047b73953054906e4d0ab2403bc092e28ef69199c0888709c3
@Test public void shouldStubbingWork()
// You are a professional Java test case writer, please create a test case named `shouldStubbingWork` for the issue `Mockito-200`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-200 // // ## Issue-Title: // ArgumentCaptor.fromClass's return type should match a parameterized type // // ## Issue-Description: // `ArgumentCaptor.fromClass`'s return type should match a parameterized type. I.e. the expression `ArgumentCaptor.fromClass(Class<S>)` should be of type `ArgumentCaptor<U>` where `S` is a subtype of `U`. // // // For example: // // // // ``` // ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.fromClass(Consumer.class) // // ``` // // does not type check (i.e. it is a compile time error). It should type check. // // // The reasons that it is desirable for `ArgumentCaptor.fromClass` to allow expressions such as the example above to type check are: // // // 1. `ArgumentCaptor.fromClass` is intended to be a convenience method to allow the user to construct an ArgumentCaptor without casting the returned value. // // // Currently, the user can devise a workaround such as: // // // // ``` // ArgumentCaptor<? extends Consumer<String>> captor // = ArgumentCaptor.fromClass(Consumer.class) // // ``` // // This workaround is inconvenient, and so contrary to `ArgumentCaptor.fromClass` being a convenience method. // // // 2. It is inconsistent with `@Captor`, which can be applied to a field with a paramterized type. I.e. // // // // ``` // @Captor ArgumentCaptor<Consumer<String>> captor // // ``` // // type checks. // // // //
Mockito
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.bugs; import static org.mockito.Mockito.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.mockitoutil.TestBase; @SuppressWarnings("unchecked") //see issue 200 public class InheritedGenericsPolimorphicCallTest extends TestBase { protected interface MyIterable<T> extends Iterable<T> { public MyIterator<T> iterator(); } protected interface MyIterator<T> extends Iterator<T> { // adds nothing here } MyIterator<String> myIterator = Mockito.mock(MyIterator.class); MyIterable<String> iterable = Mockito.mock(MyIterable.class); @Test public void shouldStubbingWork() { Mockito.when(iterable.iterator()).thenReturn(myIterator); Assert.assertNotNull(((Iterable) iterable).iterator()); Assert.assertNotNull(iterable.iterator()); } @Test public void shouldVerificationWorks() { iterable.iterator(); verify(iterable).iterator(); verify((Iterable) iterable).iterator(); } @Test public void shouldWorkExactlyAsJavaProxyWould() { //given final List<Method> methods = new LinkedList<Method>(); InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { methods.add(method); return null; }}; iterable = (MyIterable) Proxy.newProxyInstance( this.getClass().getClassLoader(), new Class[] { MyIterable.class }, handler); //when iterable.iterator(); ((Iterable) iterable).iterator(); //then assertEquals(2, methods.size()); assertEquals(methods.get(0), methods.get(1)); } }
public void testBug1955483() { XYSeries series = new XYSeries("Series", true, true); series.addOrUpdate(1.0, 1.0); series.addOrUpdate(1.0, 2.0); assertEquals(new Double(1.0), series.getY(0)); assertEquals(new Double(2.0), series.getY(1)); assertEquals(2, series.getItemCount()); }
org.jfree.data.xy.junit.XYSeriesTests::testBug1955483
tests/org/jfree/data/xy/junit/XYSeriesTests.java
482
tests/org/jfree/data/xy/junit/XYSeriesTests.java
testBug1955483
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * XYSeriesTests.java * ------------------ * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 23-Dec-2003 : Version 1 (DG); * 15-Jan-2007 : Added tests for new toArray() method (DG); * 30-Jan-2007 : Fixed some code that won't compile with Java 1.4 (DG); * 31-Oct-2007 : New hashCode() test (DG); * 01-May-2008 : Added testAddOrUpdate3() (DG); * 24-Nov-2008 : Added testBug1955483() (DG); * */ package org.jfree.data.xy.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.general.SeriesException; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; /** * Tests for the {@link XYSeries} class. */ public class XYSeriesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(XYSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public XYSeriesTests(String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeries s2 = new XYSeries("Series"); s2.add(1.0, 1.1); assertTrue(s1.equals(s2)); assertTrue(s2.equals(s1)); s1.setKey("Series X"); assertFalse(s1.equals(s2)); s2.setKey("Series X"); assertTrue(s1.equals(s2)); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { XYSeries s1 = new XYSeries("Test"); XYSeries s2 = new XYSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(1.0, 500.0); s2.add(1.0, 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(2.0, null); s2.add(2.0, null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(5.0, 111.0); s2.add(5.0, 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(9.0, 1.0); s2.add(9.0, 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } /** * Confirm that cloning works. */ public void testCloning() { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeries s2 = null; try { s2 = (XYSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); } /** * Another test of the clone() method. */ public void testCloning2() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 100.0); s1.add(2.0, null); s1.add(3.0, 200.0); XYSeries s2 = null; try { s2 = (XYSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.add(4.0, 300.0); assertFalse(s1.equals(s2)); s1.add(4.0, 300.0); assertTrue(s1.equals(s2)); } /** * Another test of the clone() method. */ public void testCloning3() { XYSeries s1 = new XYSeries("S1"); XYSeries s2 = null; try { s2 = (XYSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.add(4.0, 300.0); assertFalse(s1.equals(s2)); s1.add(4.0, 300.0); assertTrue(s1.equals(s2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); s2 = (XYSeries) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(s1, s2); } /** * Simple test for the indexOf() method. */ public void testIndexOf() { XYSeries s1 = new XYSeries("Series 1"); s1.add(1.0, 1.0); s1.add(2.0, 2.0); s1.add(3.0, 3.0); assertEquals(0, s1.indexOf(new Double(1.0))); } /** * A check for the indexOf() method for an unsorted series. */ public void testIndexOf2() { XYSeries s1 = new XYSeries("Series 1", false, true); s1.add(1.0, 1.0); s1.add(3.0, 3.0); s1.add(2.0, 2.0); assertEquals(0, s1.indexOf(new Double(1.0))); assertEquals(1, s1.indexOf(new Double(3.0))); assertEquals(2, s1.indexOf(new Double(2.0))); } /** * Simple test for the remove() method. */ public void testRemove() { XYSeries s1 = new XYSeries("Series 1"); s1.add(1.0, 1.0); s1.add(2.0, 2.0); s1.add(3.0, 3.0); assertEquals(3, s1.getItemCount()); s1.remove(new Double(2.0)); assertEquals(new Double(3.0), s1.getX(1)); s1.remove(0); assertEquals(new Double(3.0), s1.getX(0)); } private static final double EPSILON = 0.0000000001; /** * When items are added with duplicate x-values, we expect them to remain * in the order they were added. */ public void testAdditionOfDuplicateXValues() { XYSeries s1 = new XYSeries("Series 1"); s1.add(1.0, 1.0); s1.add(2.0, 2.0); s1.add(2.0, 3.0); s1.add(2.0, 4.0); s1.add(3.0, 5.0); assertEquals(1.0, s1.getY(0).doubleValue(), EPSILON); assertEquals(2.0, s1.getY(1).doubleValue(), EPSILON); assertEquals(3.0, s1.getY(2).doubleValue(), EPSILON); assertEquals(4.0, s1.getY(3).doubleValue(), EPSILON); assertEquals(5.0, s1.getY(4).doubleValue(), EPSILON); } /** * Some checks for the update(Number, Number) method. */ public void testUpdate() { XYSeries series = new XYSeries("S1"); series.add(new Integer(1), new Integer(2)); assertEquals(new Integer(2), series.getY(0)); series.update(new Integer(1), new Integer(3)); assertEquals(new Integer(3), series.getY(0)); try { series.update(new Integer(2), new Integer(99)); assertTrue(false); } catch (SeriesException e) { // got the required exception } } /** * Some checks for the update() method for an unsorted series. */ public void testUpdate2() { XYSeries series = new XYSeries("Series", false, true); series.add(5.0, 55.0); series.add(4.0, 44.0); series.add(6.0, 66.0); series.update(new Double(4.0), new Double(99.0)); assertEquals(new Double(99.0), series.getY(1)); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { XYSeries series = new XYSeries("S1", true, false); XYDataItem old = series.addOrUpdate(new Long(1), new Long(2)); assertTrue(old == null); assertEquals(1, series.getItemCount()); assertEquals(new Long(2), series.getY(0)); old = series.addOrUpdate(new Long(2), new Long(3)); assertTrue(old == null); assertEquals(2, series.getItemCount()); assertEquals(new Long(3), series.getY(1)); old = series.addOrUpdate(new Long(1), new Long(99)); assertEquals(new XYDataItem(new Long(1), new Long(2)), old); assertEquals(2, series.getItemCount()); assertEquals(new Long(99), series.getY(0)); assertEquals(new Long(3), series.getY(1)); } /** * Some checks for the addOrUpdate() method for an UNSORTED series. */ public void testAddOrUpdate2() { XYSeries series = new XYSeries("Series", false, false); series.add(5.0, 5.5); series.add(6.0, 6.6); series.add(3.0, 3.3); series.add(4.0, 4.4); series.add(2.0, 2.2); series.add(1.0, 1.1); series.addOrUpdate(new Double(3.0), new Double(33.3)); series.addOrUpdate(new Double(2.0), new Double(22.2)); assertEquals(33.3, series.getY(2).doubleValue(), EPSILON); assertEquals(22.2, series.getY(4).doubleValue(), EPSILON); } /** * Another test for the addOrUpdate() method. */ public void testAddOrUpdate3() { XYSeries series = new XYSeries("Series", false, true); series.addOrUpdate(1.0, 1.0); series.addOrUpdate(1.0, 2.0); series.addOrUpdate(1.0, 3.0); assertEquals(new Double(1.0), series.getY(0)); assertEquals(new Double(2.0), series.getY(1)); assertEquals(new Double(3.0), series.getY(2)); assertEquals(3, series.getItemCount()); } /** * Some checks for the add() method for an UNSORTED series. */ public void testAdd() { XYSeries series = new XYSeries("Series", false, true); series.add(5.0, 5.50); series.add(5.1, 5.51); series.add(6.0, 6.6); series.add(3.0, 3.3); series.add(4.0, 4.4); series.add(2.0, 2.2); series.add(1.0, 1.1); assertEquals(5.5, series.getY(0).doubleValue(), EPSILON); assertEquals(5.51, series.getY(1).doubleValue(), EPSILON); assertEquals(6.6, series.getY(2).doubleValue(), EPSILON); assertEquals(3.3, series.getY(3).doubleValue(), EPSILON); assertEquals(4.4, series.getY(4).doubleValue(), EPSILON); assertEquals(2.2, series.getY(5).doubleValue(), EPSILON); assertEquals(1.1, series.getY(6).doubleValue(), EPSILON); } /** * A simple check that the maximumItemCount attribute is working. */ public void testSetMaximumItemCount() { XYSeries s1 = new XYSeries("S1"); assertEquals(Integer.MAX_VALUE, s1.getMaximumItemCount()); s1.setMaximumItemCount(2); assertEquals(2, s1.getMaximumItemCount()); s1.add(1.0, 1.1); s1.add(2.0, 2.2); s1.add(3.0, 3.3); assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON); assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON); } /** * Check that the maximum item count can be applied retrospectively. */ public void testSetMaximumItemCount2() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 1.1); s1.add(2.0, 2.2); s1.add(3.0, 3.3); s1.setMaximumItemCount(2); assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON); assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON); } /** * Some checks for the toArray() method. */ public void testToArray() { XYSeries s = new XYSeries("S1"); double[][] array = s.toArray(); assertEquals(2, array.length); assertEquals(0, array[0].length); assertEquals(0, array[1].length); s.add(1.0, 2.0); array = s.toArray(); assertEquals(1, array[0].length); assertEquals(1, array[1].length); assertEquals(2, array.length); assertEquals(1.0, array[0][0], EPSILON); assertEquals(2.0, array[1][0], EPSILON); s.add(2.0, null); array = s.toArray(); assertEquals(2, array.length); assertEquals(2, array[0].length); assertEquals(2, array[1].length); assertEquals(2.0, array[0][1], EPSILON); assertTrue(Double.isNaN(array[1][1])); } /** * Some checks for an example using the toArray() method. */ public void testToArrayExample() { XYSeries s = new XYSeries("S"); s.add(1.0, 11.0); s.add(2.0, 22.0); s.add(3.5, 35.0); s.add(5.0, null); DefaultXYDataset dataset = new DefaultXYDataset(); dataset.addSeries("S", s.toArray()); assertEquals(1, dataset.getSeriesCount()); assertEquals(4, dataset.getItemCount(0)); assertEquals("S", dataset.getSeriesKey(0)); assertEquals(1.0, dataset.getXValue(0, 0), EPSILON); assertEquals(2.0, dataset.getXValue(0, 1), EPSILON); assertEquals(3.5, dataset.getXValue(0, 2), EPSILON); assertEquals(5.0, dataset.getXValue(0, 3), EPSILON); assertEquals(11.0, dataset.getYValue(0, 0), EPSILON); assertEquals(22.0, dataset.getYValue(0, 1), EPSILON); assertEquals(35.0, dataset.getYValue(0, 2), EPSILON); assertTrue(Double.isNaN(dataset.getYValue(0, 3))); } /** * Another test for the addOrUpdate() method. */ public void testBug1955483() { XYSeries series = new XYSeries("Series", true, true); series.addOrUpdate(1.0, 1.0); series.addOrUpdate(1.0, 2.0); assertEquals(new Double(1.0), series.getY(0)); assertEquals(new Double(2.0), series.getY(1)); assertEquals(2, series.getItemCount()); } }
// You are a professional Java test case writer, please create a test case named `testBug1955483` for the issue `Chart-862`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-862 // // ## Issue-Title: // #862 XYSeries.addOrUpdate() should add if duplicates are allowed // // // // // // ## Issue-Description: // Copied from this post (by Ted Schwartz) in the forum: // // // <http://www.jfree.org/phpBB2/viewtopic.php?t=24523> // // // I've found a bug in jfreechart-1.0.9 code for org.jfree.data.xy.XYSeries. There was a change some time ago which introduced the notion of allowing duplicate X values in XYSeries data. The method addOrUpdate(Number x, Number y) was never modified to support this, and therefore duplicate data were overwriting existing data. This is the fix I've made, but I don't know how to submit a patch... // // // $ diff original/jfreechart-1.0.9/source/org/jfree/data/xy/XYSeries.java fixed/org/jfree/data/xy/XYSeries.java // // 537c537 // // < if (index >= 0) { // // --- // // > if (index >= 0 && !allowDuplicateXValues) { // // 545a546,559 // // > } else if (index >= 0){ // // > XYDataItem item = new XYDataItem(x, y); // // > // need to make sure we are adding \*after\* any duplicates // // > int size = this.data.size(); // // > while (index < size // // > && item.compareTo(this.data.get(index)) == 0) { // // > index++; // // > } // // > if (index < this.data.size()) { // // > this.data.add(index, item); // // > } // // > else { // // > this.data.add(item); // // > } // // 558,561d571 // // < // check if this addition will exceed the maximum item count... // // < if (getItemCount() > this.maximumItemCount) { // // < this.data.remove(0); // // < } // // 562a573,576 // // > // check if this addition will exceed the maximum item count... // // > if (getItemCount() > this.maximumItemCount) { // // > this.data.remove(0); // // > } // // // // public void testBug1955483() {
482
/** * Another test for the addOrUpdate() method. */
5
475
tests/org/jfree/data/xy/junit/XYSeriesTests.java
tests
```markdown ## Issue-ID: Chart-862 ## Issue-Title: #862 XYSeries.addOrUpdate() should add if duplicates are allowed ## Issue-Description: Copied from this post (by Ted Schwartz) in the forum: <http://www.jfree.org/phpBB2/viewtopic.php?t=24523> I've found a bug in jfreechart-1.0.9 code for org.jfree.data.xy.XYSeries. There was a change some time ago which introduced the notion of allowing duplicate X values in XYSeries data. The method addOrUpdate(Number x, Number y) was never modified to support this, and therefore duplicate data were overwriting existing data. This is the fix I've made, but I don't know how to submit a patch... $ diff original/jfreechart-1.0.9/source/org/jfree/data/xy/XYSeries.java fixed/org/jfree/data/xy/XYSeries.java 537c537 < if (index >= 0) { --- > if (index >= 0 && !allowDuplicateXValues) { 545a546,559 > } else if (index >= 0){ > XYDataItem item = new XYDataItem(x, y); > // need to make sure we are adding \*after\* any duplicates > int size = this.data.size(); > while (index < size > && item.compareTo(this.data.get(index)) == 0) { > index++; > } > if (index < this.data.size()) { > this.data.add(index, item); > } > else { > this.data.add(item); > } 558,561d571 < // check if this addition will exceed the maximum item count... < if (getItemCount() > this.maximumItemCount) { < this.data.remove(0); < } 562a573,576 > // check if this addition will exceed the maximum item count... > if (getItemCount() > this.maximumItemCount) { > this.data.remove(0); > } ``` You are a professional Java test case writer, please create a test case named `testBug1955483` for the issue `Chart-862`, utilizing the provided issue report information and the following function signature. ```java public void testBug1955483() { ```
475
[ "org.jfree.data.xy.XYSeries" ]
10dc7c852f4654a2d3a8d795bdafb0279c7ee6ddc3e5bf6415a6b52c06fc188f
public void testBug1955483()
// You are a professional Java test case writer, please create a test case named `testBug1955483` for the issue `Chart-862`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-862 // // ## Issue-Title: // #862 XYSeries.addOrUpdate() should add if duplicates are allowed // // // // // // ## Issue-Description: // Copied from this post (by Ted Schwartz) in the forum: // // // <http://www.jfree.org/phpBB2/viewtopic.php?t=24523> // // // I've found a bug in jfreechart-1.0.9 code for org.jfree.data.xy.XYSeries. There was a change some time ago which introduced the notion of allowing duplicate X values in XYSeries data. The method addOrUpdate(Number x, Number y) was never modified to support this, and therefore duplicate data were overwriting existing data. This is the fix I've made, but I don't know how to submit a patch... // // // $ diff original/jfreechart-1.0.9/source/org/jfree/data/xy/XYSeries.java fixed/org/jfree/data/xy/XYSeries.java // // 537c537 // // < if (index >= 0) { // // --- // // > if (index >= 0 && !allowDuplicateXValues) { // // 545a546,559 // // > } else if (index >= 0){ // // > XYDataItem item = new XYDataItem(x, y); // // > // need to make sure we are adding \*after\* any duplicates // // > int size = this.data.size(); // // > while (index < size // // > && item.compareTo(this.data.get(index)) == 0) { // // > index++; // // > } // // > if (index < this.data.size()) { // // > this.data.add(index, item); // // > } // // > else { // // > this.data.add(item); // // > } // // 558,561d571 // // < // check if this addition will exceed the maximum item count... // // < if (getItemCount() > this.maximumItemCount) { // // < this.data.remove(0); // // < } // // 562a573,576 // // > // check if this addition will exceed the maximum item count... // // > if (getItemCount() > this.maximumItemCount) { // // > this.data.remove(0); // // > } // // // //
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * XYSeriesTests.java * ------------------ * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 23-Dec-2003 : Version 1 (DG); * 15-Jan-2007 : Added tests for new toArray() method (DG); * 30-Jan-2007 : Fixed some code that won't compile with Java 1.4 (DG); * 31-Oct-2007 : New hashCode() test (DG); * 01-May-2008 : Added testAddOrUpdate3() (DG); * 24-Nov-2008 : Added testBug1955483() (DG); * */ package org.jfree.data.xy.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.general.SeriesException; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; /** * Tests for the {@link XYSeries} class. */ public class XYSeriesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(XYSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public XYSeriesTests(String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeries s2 = new XYSeries("Series"); s2.add(1.0, 1.1); assertTrue(s1.equals(s2)); assertTrue(s2.equals(s1)); s1.setKey("Series X"); assertFalse(s1.equals(s2)); s2.setKey("Series X"); assertTrue(s1.equals(s2)); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { XYSeries s1 = new XYSeries("Test"); XYSeries s2 = new XYSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(1.0, 500.0); s2.add(1.0, 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(2.0, null); s2.add(2.0, null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(5.0, 111.0); s2.add(5.0, 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(9.0, 1.0); s2.add(9.0, 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } /** * Confirm that cloning works. */ public void testCloning() { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeries s2 = null; try { s2 = (XYSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); } /** * Another test of the clone() method. */ public void testCloning2() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 100.0); s1.add(2.0, null); s1.add(3.0, 200.0); XYSeries s2 = null; try { s2 = (XYSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.add(4.0, 300.0); assertFalse(s1.equals(s2)); s1.add(4.0, 300.0); assertTrue(s1.equals(s2)); } /** * Another test of the clone() method. */ public void testCloning3() { XYSeries s1 = new XYSeries("S1"); XYSeries s2 = null; try { s2 = (XYSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.add(4.0, 300.0); assertFalse(s1.equals(s2)); s1.add(4.0, 300.0); assertTrue(s1.equals(s2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { XYSeries s1 = new XYSeries("Series"); s1.add(1.0, 1.1); XYSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); s2 = (XYSeries) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(s1, s2); } /** * Simple test for the indexOf() method. */ public void testIndexOf() { XYSeries s1 = new XYSeries("Series 1"); s1.add(1.0, 1.0); s1.add(2.0, 2.0); s1.add(3.0, 3.0); assertEquals(0, s1.indexOf(new Double(1.0))); } /** * A check for the indexOf() method for an unsorted series. */ public void testIndexOf2() { XYSeries s1 = new XYSeries("Series 1", false, true); s1.add(1.0, 1.0); s1.add(3.0, 3.0); s1.add(2.0, 2.0); assertEquals(0, s1.indexOf(new Double(1.0))); assertEquals(1, s1.indexOf(new Double(3.0))); assertEquals(2, s1.indexOf(new Double(2.0))); } /** * Simple test for the remove() method. */ public void testRemove() { XYSeries s1 = new XYSeries("Series 1"); s1.add(1.0, 1.0); s1.add(2.0, 2.0); s1.add(3.0, 3.0); assertEquals(3, s1.getItemCount()); s1.remove(new Double(2.0)); assertEquals(new Double(3.0), s1.getX(1)); s1.remove(0); assertEquals(new Double(3.0), s1.getX(0)); } private static final double EPSILON = 0.0000000001; /** * When items are added with duplicate x-values, we expect them to remain * in the order they were added. */ public void testAdditionOfDuplicateXValues() { XYSeries s1 = new XYSeries("Series 1"); s1.add(1.0, 1.0); s1.add(2.0, 2.0); s1.add(2.0, 3.0); s1.add(2.0, 4.0); s1.add(3.0, 5.0); assertEquals(1.0, s1.getY(0).doubleValue(), EPSILON); assertEquals(2.0, s1.getY(1).doubleValue(), EPSILON); assertEquals(3.0, s1.getY(2).doubleValue(), EPSILON); assertEquals(4.0, s1.getY(3).doubleValue(), EPSILON); assertEquals(5.0, s1.getY(4).doubleValue(), EPSILON); } /** * Some checks for the update(Number, Number) method. */ public void testUpdate() { XYSeries series = new XYSeries("S1"); series.add(new Integer(1), new Integer(2)); assertEquals(new Integer(2), series.getY(0)); series.update(new Integer(1), new Integer(3)); assertEquals(new Integer(3), series.getY(0)); try { series.update(new Integer(2), new Integer(99)); assertTrue(false); } catch (SeriesException e) { // got the required exception } } /** * Some checks for the update() method for an unsorted series. */ public void testUpdate2() { XYSeries series = new XYSeries("Series", false, true); series.add(5.0, 55.0); series.add(4.0, 44.0); series.add(6.0, 66.0); series.update(new Double(4.0), new Double(99.0)); assertEquals(new Double(99.0), series.getY(1)); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { XYSeries series = new XYSeries("S1", true, false); XYDataItem old = series.addOrUpdate(new Long(1), new Long(2)); assertTrue(old == null); assertEquals(1, series.getItemCount()); assertEquals(new Long(2), series.getY(0)); old = series.addOrUpdate(new Long(2), new Long(3)); assertTrue(old == null); assertEquals(2, series.getItemCount()); assertEquals(new Long(3), series.getY(1)); old = series.addOrUpdate(new Long(1), new Long(99)); assertEquals(new XYDataItem(new Long(1), new Long(2)), old); assertEquals(2, series.getItemCount()); assertEquals(new Long(99), series.getY(0)); assertEquals(new Long(3), series.getY(1)); } /** * Some checks for the addOrUpdate() method for an UNSORTED series. */ public void testAddOrUpdate2() { XYSeries series = new XYSeries("Series", false, false); series.add(5.0, 5.5); series.add(6.0, 6.6); series.add(3.0, 3.3); series.add(4.0, 4.4); series.add(2.0, 2.2); series.add(1.0, 1.1); series.addOrUpdate(new Double(3.0), new Double(33.3)); series.addOrUpdate(new Double(2.0), new Double(22.2)); assertEquals(33.3, series.getY(2).doubleValue(), EPSILON); assertEquals(22.2, series.getY(4).doubleValue(), EPSILON); } /** * Another test for the addOrUpdate() method. */ public void testAddOrUpdate3() { XYSeries series = new XYSeries("Series", false, true); series.addOrUpdate(1.0, 1.0); series.addOrUpdate(1.0, 2.0); series.addOrUpdate(1.0, 3.0); assertEquals(new Double(1.0), series.getY(0)); assertEquals(new Double(2.0), series.getY(1)); assertEquals(new Double(3.0), series.getY(2)); assertEquals(3, series.getItemCount()); } /** * Some checks for the add() method for an UNSORTED series. */ public void testAdd() { XYSeries series = new XYSeries("Series", false, true); series.add(5.0, 5.50); series.add(5.1, 5.51); series.add(6.0, 6.6); series.add(3.0, 3.3); series.add(4.0, 4.4); series.add(2.0, 2.2); series.add(1.0, 1.1); assertEquals(5.5, series.getY(0).doubleValue(), EPSILON); assertEquals(5.51, series.getY(1).doubleValue(), EPSILON); assertEquals(6.6, series.getY(2).doubleValue(), EPSILON); assertEquals(3.3, series.getY(3).doubleValue(), EPSILON); assertEquals(4.4, series.getY(4).doubleValue(), EPSILON); assertEquals(2.2, series.getY(5).doubleValue(), EPSILON); assertEquals(1.1, series.getY(6).doubleValue(), EPSILON); } /** * A simple check that the maximumItemCount attribute is working. */ public void testSetMaximumItemCount() { XYSeries s1 = new XYSeries("S1"); assertEquals(Integer.MAX_VALUE, s1.getMaximumItemCount()); s1.setMaximumItemCount(2); assertEquals(2, s1.getMaximumItemCount()); s1.add(1.0, 1.1); s1.add(2.0, 2.2); s1.add(3.0, 3.3); assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON); assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON); } /** * Check that the maximum item count can be applied retrospectively. */ public void testSetMaximumItemCount2() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 1.1); s1.add(2.0, 2.2); s1.add(3.0, 3.3); s1.setMaximumItemCount(2); assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON); assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON); } /** * Some checks for the toArray() method. */ public void testToArray() { XYSeries s = new XYSeries("S1"); double[][] array = s.toArray(); assertEquals(2, array.length); assertEquals(0, array[0].length); assertEquals(0, array[1].length); s.add(1.0, 2.0); array = s.toArray(); assertEquals(1, array[0].length); assertEquals(1, array[1].length); assertEquals(2, array.length); assertEquals(1.0, array[0][0], EPSILON); assertEquals(2.0, array[1][0], EPSILON); s.add(2.0, null); array = s.toArray(); assertEquals(2, array.length); assertEquals(2, array[0].length); assertEquals(2, array[1].length); assertEquals(2.0, array[0][1], EPSILON); assertTrue(Double.isNaN(array[1][1])); } /** * Some checks for an example using the toArray() method. */ public void testToArrayExample() { XYSeries s = new XYSeries("S"); s.add(1.0, 11.0); s.add(2.0, 22.0); s.add(3.5, 35.0); s.add(5.0, null); DefaultXYDataset dataset = new DefaultXYDataset(); dataset.addSeries("S", s.toArray()); assertEquals(1, dataset.getSeriesCount()); assertEquals(4, dataset.getItemCount(0)); assertEquals("S", dataset.getSeriesKey(0)); assertEquals(1.0, dataset.getXValue(0, 0), EPSILON); assertEquals(2.0, dataset.getXValue(0, 1), EPSILON); assertEquals(3.5, dataset.getXValue(0, 2), EPSILON); assertEquals(5.0, dataset.getXValue(0, 3), EPSILON); assertEquals(11.0, dataset.getYValue(0, 0), EPSILON); assertEquals(22.0, dataset.getYValue(0, 1), EPSILON); assertEquals(35.0, dataset.getYValue(0, 2), EPSILON); assertTrue(Double.isNaN(dataset.getYValue(0, 3))); } /** * Another test for the addOrUpdate() method. */ public void testBug1955483() { XYSeries series = new XYSeries("Series", true, true); series.addOrUpdate(1.0, 1.0); series.addOrUpdate(1.0, 2.0); assertEquals(new Double(1.0), series.getY(0)); assertEquals(new Double(2.0), series.getY(1)); assertEquals(2, series.getItemCount()); } }
public void testCheckGlobalThisOff() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); }
com.google.javascript.jscomp.CommandLineRunnerTest::testCheckGlobalThisOff
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
160
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
testCheckGlobalThisOff
/* * Copyright 2009 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; /** * Tests for {@link CommandLineRunner}. * * @author nicksantos@google.com (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; private CommandLineRunner lastCommandLineRunner = null; private List<Integer> exitCodes = null; private ByteArrayOutputStream outReader = null; private ByteArrayOutputStream errReader = null; // If set, this will be appended to the end of the args list. // For testing args parsing. private String lastArg = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private ModulePattern useModules = ModulePattern.NONE; private enum ModulePattern { NONE, CHAIN, STAR } private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final List<JSSourceFile> DEFAULT_EXTERNS = ImmutableList.of( JSSourceFile.fromCode("externs", "var arguments;" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " */\n" + "function Function(var_args) {}\n" + "/**\n" + " * @param {...*} var_args\n" + " * @return {*}\n" + " */\n" + "Function.prototype.call = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @return {!Array}\n" + " */\n" + "function Array(var_args) {}" + "/**\n" + " * @param {*=} opt_begin\n" + " * @param {*=} opt_end\n" + " * @return {!Array}\n" + " * @this {Object}\n" + " */\n" + "Array.prototype.slice = function(opt_begin, opt_end) {};" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @nosideeffects */ function noSideEffects() {}") ); private List<JSSourceFile> externs; @Override public void setUp() throws Exception { super.setUp(); externs = DEFAULT_EXTERNS; lastCompiler = null; lastArg = null; outReader = new ByteArrayOutputStream(); errReader = new ByteArrayOutputStream(); useStringComparison = false; useModules = ModulePattern.NONE; args.clear(); exitCodes = Lists.newArrayList(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testWarningGuardOrdering1() { args.add("--jscomp_error=globalThis"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testWarningGuardOrdering2() { args.add("--jscomp_off=globalThis"); args.add("--jscomp_error=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testWarningGuardOrdering3() { args.add("--jscomp_warning=globalThis"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testWarningGuardOrdering4() { args.add("--jscomp_off=globalThis"); args.add("--jscomp_warning=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOffByDefault() { testSame("function f() { this.a = 3; }"); } public void testCheckGlobalThisOnWithAdvancedMode() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOnWithErrorFlag() { args.add("--jscomp_error=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOff() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testTypeCheckingOffByDefault() { test("function f(x) { return x; } f();", "function f(a) { return a; } f();"); } public void testReflectedMethods() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test( "/** @constructor */" + "function Foo() {}" + "Foo.prototype.handle = function(x, y) { alert(y); };" + "var x = goog.reflect.object(Foo, {handle: 1});" + "for (var i in x) { x[i].call(x); }" + "window['Foo'] = Foo;", "function a() {}" + "a.prototype.a = function(e, d) { alert(d); };" + "var b = goog.c.b(a, {a: 1}),c;" + "for (c in b) { b[c].call(b); }" + "window.Foo = a;"); } public void testTypeCheckingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testTypeParsingOffByDefault() { testSame("/** @return {number */ function f(a) { return a; }"); } public void testTypeParsingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @return {number */ function f(a) { return a; }", RhinoErrorReporter.TYPE_PARSE_ERROR); test("/** @return {n} */ function f(a) { return a; }", RhinoErrorReporter.TYPE_PARSE_ERROR); } public void testTypeCheckOverride1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=checkTypes"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); } public void testTypeCheckOverride2() { args.add("--warning_level=DEFAULT"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); args.add("--jscomp_warning=checkTypes"); test("var x = x || {}; x.f = function() {}; x.f(3);", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testCheckSymbolsOffForDefault() { args.add("--warning_level=DEFAULT"); test("x = 3; var y; var y;", "x=3; var y;"); } public void testCheckSymbolsOnForVerbose() { args.add("--warning_level=VERBOSE"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); test("var y; var y;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testCheckSymbolsOverrideForVerbose() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=undefinedVars"); testSame("x = 3;"); } public void testCheckSymbolsOverrideForQuiet() { args.add("--warning_level=QUIET"); args.add("--jscomp_error=undefinedVars"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); } public void testCheckUndefinedProperties1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testCheckUndefinedProperties2() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=missingProperties"); test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testCheckUndefinedProperties3() { args.add("--warning_level=VERBOSE"); test("function f() {var x = {}; var y = x.bar;}", TypeCheck.INEXISTENT_PROPERTY); } public void testDuplicateParams() { test("function f(a, a) {}", RhinoErrorReporter.DUPLICATE_PARAM); assertTrue(lastCompiler.hasHaltingErrors()); } public void testDefineFlag() { args.add("--define=FOO"); args.add("--define=\"BAR=5\""); args.add("--D"); args.add("CCC"); args.add("-D"); args.add("DDD"); test("/** @define {boolean} */ var FOO = false;" + "/** @define {number} */ var BAR = 3;" + "/** @define {boolean} */ var CCC = false;" + "/** @define {boolean} */ var DDD = false;", "var FOO = !0, BAR = 5, CCC = !0, DDD = !0;"); } public void testDefineFlag2() { args.add("--define=FOO='x\"'"); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x\\\"\";"); } public void testDefineFlag3() { args.add("--define=FOO=\"x'\""); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x'\";"); } public void testScriptStrictModeNoWarning() { test("'use strict';", ""); test("'no use strict';", CheckSideEffects.USELESS_CODE_ERROR); } public void testFunctionStrictModeNoWarning() { test("function f() {'use strict';}", "function f() {}"); test("function f() {'no use strict';}", CheckSideEffects.USELESS_CODE_ERROR); } public void testQuietMode() { args.add("--warning_level=DEFAULT"); test("/** @const \n * @const */ var x;", RhinoErrorReporter.PARSE_ERROR); args.add("--warning_level=QUIET"); testSame("/** @const \n * @const */ var x;"); } public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {dom:{}};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); } public void testCssNameWiring() throws Exception { test("var goog = {}; goog.getCssName = function() {};" + "goog.setCssNameMapping = function() {};" + "goog.setCssNameMapping({'goog': 'a', 'button': 'b'});" + "var a = goog.getCssName('goog-button');" + "var b = goog.getCssName('css-button');" + "var c = goog.getCssName('goog-menu');" + "var d = goog.getCssName('css-menu');", "var goog = { getCssName: function() {}," + " setCssNameMapping: function() {} }," + " a = 'a-b'," + " b = 'css-b'," + " c = 'a-menu'," + " d = 'css-menu';"); } ////////////////////////////////////////////////////////////////////////////// // Integration tests public void testIssue70() { test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue81() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); useStringComparison = true; test("eval('1'); var x = eval; x('2');", "eval(\"1\");(0,eval)(\"2\");"); } public void testIssue115() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--jscomp_off=es5Strict"); args.add("--warning_level=VERBOSE"); test("function f() { " + " var arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}", "function f() { " + " arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}"); } public void testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);" + "}"); } public void testIssue504() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("void function() { alert('hi'); }();", "alert('hi');", CheckSideEffects.USELESS_CODE_ERROR); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); test("function foo(a) {}", "function foo() {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testDebugFlag3() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=false"); test("function Foo() {}" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "throw (new function() {}).a;"); } public void testDebugFlag4() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=true"); test("function Foo() {}" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "throw (new function Foo() {}).$x$;"); } public void testBooleanFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testBooleanFlag2() { args.add("--debug"); args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testHelpFlag() { args.add("--help"); assertFalse( createCommandLineRunner( new String[] {"function f() {}"}).shouldRunCompiler()); } public void testExternsLifting1() throws Exception{ String code = "/** @externs */ function f() {}"; test(new String[] {code}, new String[] {}); assertEquals(2, lastCompiler.getExternsForTesting().size()); CompilerInput extern = lastCompiler.getExternsForTesting().get(1); assertNull(extern.getModule()); assertTrue(extern.isExtern()); assertEquals(code, extern.getCode()); assertEquals(1, lastCompiler.getInputsForTesting().size()); CompilerInput input = lastCompiler.getInputsForTesting().get(0); assertNotNull(input.getModule()); assertFalse(input.isExtern()); assertEquals("", input.getCode()); } public void testExternsLifting2() { args.add("--warning_level=VERBOSE"); test(new String[] {"/** @externs */ function f() {}", "f(3);"}, new String[] {"f(3);"}, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testSourceSortingOff() { test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, ProcessClosurePrimitives.LATE_PROVIDE_ERROR); } public void testSourceSortingOn() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, new String[] { "var beer = {};", "" }); } public void testSourceSortingCircularDeps1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourceSortingCircularDeps2() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('roses.lime.juice');", "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');", "goog.provide('gimlet');" + " goog.require('gin'); goog.require('roses.lime.juice');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourcePruningOn1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "" }); } public void testSourcePruningOn2() { args.add("--closure_entry_point=guinness"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var guinness = {};" }); } public void testSourcePruningOn3() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var scotch = {}, x = 3;", }); } public void testSourcePruningOn4() { args.add("--closure_entry_point=scotch"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn5() { args.add("--closure_entry_point=shiraz"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, Compiler.MISSING_ENTRY_ERROR); } public void testSourcePruningOn6() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "", "var scotch = {}, x = 3;", }); } public void testForwardDeclareDroppedTypes() { args.add("--manage_closure_dependencies=true"); args.add("--warning_level=VERBOSE"); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}", "goog.provide('Scotch'); var x = 3;" }, new String[] { "var beer = {}; function f() {}", "" }); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}" }, new String[] { "var beer = {}; function f() {}", "" }, RhinoErrorReporter.TYPE_PARSE_ERROR); } public void testSourceMapExpansion1() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--create_source_map=%outname%.map"); testSame("var x = 3;"); assertEquals("/path/to/out.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion2() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion3() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo_"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo_m0.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootModule())); } public void testSourceMapFormat1() { args.add("--js_output_file"); args.add("/path/to/out.js"); testSame("var x = 3;"); assertEquals(SourceMap.Format.DEFAULT, lastCompiler.getOptions().sourceMapFormat); } public void testSourceMapFormat2() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--source_map_format=V3"); testSame("var x = 3;"); assertEquals(SourceMap.Format.V3, lastCompiler.getOptions().sourceMapFormat); } public void testCharSetExpansion() { testSame(""); assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset); args.add("--charset=UTF-8"); testSame(""); assertEquals("UTF-8", lastCompiler.getOptions().outputCharset); } public void testChainModuleManifest() throws Exception { useModules = ModulePattern.CHAIN; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestOrBundleTo( lastCompiler.getModuleGraph(), builder, true); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m1}\n" + "i2\n" + "\n" + "{m3:m2}\n" + "i3\n", builder.toString()); } public void testStarModuleManifest() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestOrBundleTo( lastCompiler.getModuleGraph(), builder, true); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m0}\n" + "i2\n" + "\n" + "{m3:m0}\n" + "i3\n", builder.toString()); } public void testVersionFlag() { args.add("--version"); testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testVersionFlag2() { lastArg = "--version"; testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testPrintAstFlag() { args.add("--print_ast=true"); testSame(""); assertEquals( "digraph AST {\n" + " node [color=lightblue2, style=filled];\n" + " node0 [label=\"BLOCK\"];\n" + " node1 [label=\"SCRIPT\"];\n" + " node0 -> node1 [weight=1];\n" + " node1 -> RETURN [label=\"UNCOND\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> RETURN [label=\"SYN_BLOCK\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> node1 [label=\"UNCOND\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + "}\n\n", new String(outReader.toByteArray())); } public void testSyntheticExterns() { externs = ImmutableList.of( JSSourceFile.fromCode("externs", "myVar.property;")); test("var theirVar = {}; var myVar = {}; var yourVar = {};", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var yourVar = {};", "var theirVar={},myVar={},yourVar={};"); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var myVar = {};", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testGoogAssertStripping() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("goog.asserts.assert(false)", ""); args.add("--debug"); test("goog.asserts.assert(false)", "goog.$asserts$.$assert$(!1)"); } public void testMissingReturnCheckOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @return {number} */ function f() {f()} f();", CheckMissingReturn.MISSING_RETURN_STATEMENT); } public void testGenerateExports() { args.add("--generate_exports=true"); test("/** @export */ foo.prototype.x = function() {};", "foo.prototype.x=function(){};"+ "goog.exportSymbol(\"foo.prototype.x\",foo.prototype.x);"); } public void testDepreciationWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @deprecated */ function f() {}; f()", CheckAccessControls.DEPRECATED_NAME); } public void testTwoParseErrors() { // If parse errors are reported in different files, make // sure all of them are reported. Compiler compiler = compile(new String[] { "var a b;", "var b c;" }); assertEquals(2, compiler.getErrors().length); } public void testES3ByDefault() { test("var x = f.function", RhinoErrorReporter.PARSE_ERROR); } public void testES5() { args.add("--language_in=ECMASCRIPT5"); test("var x = f.function", "var x = f.function"); test("var let", "var let"); } public void testES5Strict() { args.add("--language_in=ECMASCRIPT5_STRICT"); test("var x = f.function", "'use strict';var x = f.function"); test("var let", RhinoErrorReporter.PARSE_ERROR); } public void testES5StrictUseStrict() { args.add("--language_in=ECMASCRIPT5_STRICT"); Compiler compiler = compile(new String[] {"var x = f.function"}); String outputSource = compiler.toSource(); assertEquals("'use strict'", outputSource.substring(0, 12)); } public void testES5StrictUseStrictMultipleInputs() { args.add("--language_in=ECMASCRIPT5_STRICT"); Compiler compiler = compile(new String[] {"var x = f.function", "var y = f.function", "var z = f.function"}); String outputSource = compiler.toSource(); assertEquals("'use strict'", outputSource.substring(0, 12)); assertEquals(outputSource.substring(13).indexOf("'use strict'"), -1); } /* Helper functions */ private void testSame(String original) { testSame(new String[] { original }); } private void testSame(String[] original) { test(original, original); } private void test(String original, String compiled) { test(new String[] { original }, new String[] { compiled }); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(String[] original, String[] compiled) { test(original, compiled, null); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. * If {@code warning} is non-null, we will also check if the given * warning type was emitted. */ private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); if (warning == null) { assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); } Node root = compiler.getRoot().getLastChild(); if (useStringComparison) { assertEquals(Joiner.on("").join(compiled), compiler.toSource()); } else { Node expectedRoot = parse(compiled); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } /** * Asserts that when compiling, there is an error or warning. */ private void test(String original, DiagnosticType warning) { test(new String[] { original }, warning); } private void test(String original, String expected, DiagnosticType warning) { test(new String[] { original }, new String[] { expected }, warning); } /** * Asserts that when compiling, there is an error or warning. */ private void test(String[] original, DiagnosticType warning) { Compiler compiler = compile(original); assertEquals("Expected exactly one warning or error " + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 1, compiler.getErrors().length + compiler.getWarnings().length); assertTrue(exitCodes.size() > 0); int lastExitCode = exitCodes.get(exitCodes.size() - 1); if (compiler.getErrors().length > 0) { assertEquals(1, compiler.getErrors().length); assertEquals(warning, compiler.getErrors()[0].getType()); assertEquals(1, lastExitCode); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); assertEquals(0, lastExitCode); } } private CommandLineRunner createCommandLineRunner(String[] original) { for (int i = 0; i < original.length; i++) { args.add("--js"); args.add("/path/to/input" + i + ".js"); if (useModules == ModulePattern.CHAIN) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? (":mod" + (i - 1)) : "")); } else if (useModules == ModulePattern.STAR) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? ":mod0" : "")); } } if (lastArg != null) { args.add(lastArg); } String[] argStrings = args.toArray(new String[] {}); return new CommandLineRunner( argStrings, new PrintStream(outReader), new PrintStream(errReader)); } private Compiler compile(String[] original) { CommandLineRunner runner = createCommandLineRunner(original); assertTrue(runner.shouldRunCompiler()); Supplier<List<JSSourceFile>> inputsSupplier = null; Supplier<List<JSModule>> modulesSupplier = null; if (useModules == ModulePattern.NONE) { List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } inputsSupplier = Suppliers.ofInstance(inputs); } else if (useModules == ModulePattern.STAR) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleStar(original))); } else if (useModules == ModulePattern.CHAIN) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleChain(original))); } else { throw new IllegalArgumentException("Unknown module type: " + useModules); } runner.enableTestMode( Suppliers.<List<JSSourceFile>>ofInstance(externs), inputsSupplier, modulesSupplier, new Function<Integer, Boolean>() { @Override public Boolean apply(Integer code) { return exitCodes.add(code); } }); runner.run(); lastCompiler = runner.getCompiler(); lastCommandLineRunner = runner; return lastCompiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = new CommandLineRunner(argStrings); Compiler compiler = runner.createCompiler(); List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } CompilerOptions options = new CompilerOptions(); // ECMASCRIPT5 is the most forgiving. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.init(externs, inputs, options); Node all = compiler.parseInputs(); Preconditions.checkState(compiler.getErrorCount() == 0); Preconditions.checkNotNull(all); Node n = all.getLastChild(); return n; } }
// You are a professional Java test case writer, please create a test case named `testCheckGlobalThisOff` for the issue `Closure-521`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-521 // // ## Issue-Title: // Cannot exclude globalThis checks through command line // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Run command line utility // 2. Supply flags --warning\_level VERBOSE --jscomp\_off globalThis --jscomp\_off nonStandardJsDocs // // **What is the expected output? What do you see instead?** // I expect that globalThis and nonStandardJsDocs warnings will be ignored. Only nonStandardJsDocs warnings are ignored. // // **What version of the product are you using? On what operating system?** // Version 1180 // Sun OS 5.10 // // **Please provide any additional information below.** // --jscomp\_error also doesn't work with globalThis (works with nonStandardJSDocs). // // public void testCheckGlobalThisOff() {
160
59
156
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
test
```markdown ## Issue-ID: Closure-521 ## Issue-Title: Cannot exclude globalThis checks through command line ## Issue-Description: **What steps will reproduce the problem?** 1. Run command line utility 2. Supply flags --warning\_level VERBOSE --jscomp\_off globalThis --jscomp\_off nonStandardJsDocs **What is the expected output? What do you see instead?** I expect that globalThis and nonStandardJsDocs warnings will be ignored. Only nonStandardJsDocs warnings are ignored. **What version of the product are you using? On what operating system?** Version 1180 Sun OS 5.10 **Please provide any additional information below.** --jscomp\_error also doesn't work with globalThis (works with nonStandardJSDocs). ``` You are a professional Java test case writer, please create a test case named `testCheckGlobalThisOff` for the issue `Closure-521`, utilizing the provided issue report information and the following function signature. ```java public void testCheckGlobalThisOff() { ```
156
[ "com.google.javascript.jscomp.Compiler" ]
12f30b16a8c5b8d4120b385b1791f80f2776d1638d08f71db98c57eb1d84b33d
public void testCheckGlobalThisOff()
// You are a professional Java test case writer, please create a test case named `testCheckGlobalThisOff` for the issue `Closure-521`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-521 // // ## Issue-Title: // Cannot exclude globalThis checks through command line // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Run command line utility // 2. Supply flags --warning\_level VERBOSE --jscomp\_off globalThis --jscomp\_off nonStandardJsDocs // // **What is the expected output? What do you see instead?** // I expect that globalThis and nonStandardJsDocs warnings will be ignored. Only nonStandardJsDocs warnings are ignored. // // **What version of the product are you using? On what operating system?** // Version 1180 // Sun OS 5.10 // // **Please provide any additional information below.** // --jscomp\_error also doesn't work with globalThis (works with nonStandardJSDocs). // //
Closure
/* * Copyright 2009 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; /** * Tests for {@link CommandLineRunner}. * * @author nicksantos@google.com (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; private CommandLineRunner lastCommandLineRunner = null; private List<Integer> exitCodes = null; private ByteArrayOutputStream outReader = null; private ByteArrayOutputStream errReader = null; // If set, this will be appended to the end of the args list. // For testing args parsing. private String lastArg = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private ModulePattern useModules = ModulePattern.NONE; private enum ModulePattern { NONE, CHAIN, STAR } private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final List<JSSourceFile> DEFAULT_EXTERNS = ImmutableList.of( JSSourceFile.fromCode("externs", "var arguments;" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " */\n" + "function Function(var_args) {}\n" + "/**\n" + " * @param {...*} var_args\n" + " * @return {*}\n" + " */\n" + "Function.prototype.call = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @return {!Array}\n" + " */\n" + "function Array(var_args) {}" + "/**\n" + " * @param {*=} opt_begin\n" + " * @param {*=} opt_end\n" + " * @return {!Array}\n" + " * @this {Object}\n" + " */\n" + "Array.prototype.slice = function(opt_begin, opt_end) {};" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @nosideeffects */ function noSideEffects() {}") ); private List<JSSourceFile> externs; @Override public void setUp() throws Exception { super.setUp(); externs = DEFAULT_EXTERNS; lastCompiler = null; lastArg = null; outReader = new ByteArrayOutputStream(); errReader = new ByteArrayOutputStream(); useStringComparison = false; useModules = ModulePattern.NONE; args.clear(); exitCodes = Lists.newArrayList(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testWarningGuardOrdering1() { args.add("--jscomp_error=globalThis"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testWarningGuardOrdering2() { args.add("--jscomp_off=globalThis"); args.add("--jscomp_error=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testWarningGuardOrdering3() { args.add("--jscomp_warning=globalThis"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testWarningGuardOrdering4() { args.add("--jscomp_off=globalThis"); args.add("--jscomp_warning=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOffByDefault() { testSame("function f() { this.a = 3; }"); } public void testCheckGlobalThisOnWithAdvancedMode() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOnWithErrorFlag() { args.add("--jscomp_error=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOff() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testTypeCheckingOffByDefault() { test("function f(x) { return x; } f();", "function f(a) { return a; } f();"); } public void testReflectedMethods() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test( "/** @constructor */" + "function Foo() {}" + "Foo.prototype.handle = function(x, y) { alert(y); };" + "var x = goog.reflect.object(Foo, {handle: 1});" + "for (var i in x) { x[i].call(x); }" + "window['Foo'] = Foo;", "function a() {}" + "a.prototype.a = function(e, d) { alert(d); };" + "var b = goog.c.b(a, {a: 1}),c;" + "for (c in b) { b[c].call(b); }" + "window.Foo = a;"); } public void testTypeCheckingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testTypeParsingOffByDefault() { testSame("/** @return {number */ function f(a) { return a; }"); } public void testTypeParsingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @return {number */ function f(a) { return a; }", RhinoErrorReporter.TYPE_PARSE_ERROR); test("/** @return {n} */ function f(a) { return a; }", RhinoErrorReporter.TYPE_PARSE_ERROR); } public void testTypeCheckOverride1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=checkTypes"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); } public void testTypeCheckOverride2() { args.add("--warning_level=DEFAULT"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); args.add("--jscomp_warning=checkTypes"); test("var x = x || {}; x.f = function() {}; x.f(3);", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testCheckSymbolsOffForDefault() { args.add("--warning_level=DEFAULT"); test("x = 3; var y; var y;", "x=3; var y;"); } public void testCheckSymbolsOnForVerbose() { args.add("--warning_level=VERBOSE"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); test("var y; var y;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testCheckSymbolsOverrideForVerbose() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=undefinedVars"); testSame("x = 3;"); } public void testCheckSymbolsOverrideForQuiet() { args.add("--warning_level=QUIET"); args.add("--jscomp_error=undefinedVars"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); } public void testCheckUndefinedProperties1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testCheckUndefinedProperties2() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=missingProperties"); test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testCheckUndefinedProperties3() { args.add("--warning_level=VERBOSE"); test("function f() {var x = {}; var y = x.bar;}", TypeCheck.INEXISTENT_PROPERTY); } public void testDuplicateParams() { test("function f(a, a) {}", RhinoErrorReporter.DUPLICATE_PARAM); assertTrue(lastCompiler.hasHaltingErrors()); } public void testDefineFlag() { args.add("--define=FOO"); args.add("--define=\"BAR=5\""); args.add("--D"); args.add("CCC"); args.add("-D"); args.add("DDD"); test("/** @define {boolean} */ var FOO = false;" + "/** @define {number} */ var BAR = 3;" + "/** @define {boolean} */ var CCC = false;" + "/** @define {boolean} */ var DDD = false;", "var FOO = !0, BAR = 5, CCC = !0, DDD = !0;"); } public void testDefineFlag2() { args.add("--define=FOO='x\"'"); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x\\\"\";"); } public void testDefineFlag3() { args.add("--define=FOO=\"x'\""); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x'\";"); } public void testScriptStrictModeNoWarning() { test("'use strict';", ""); test("'no use strict';", CheckSideEffects.USELESS_CODE_ERROR); } public void testFunctionStrictModeNoWarning() { test("function f() {'use strict';}", "function f() {}"); test("function f() {'no use strict';}", CheckSideEffects.USELESS_CODE_ERROR); } public void testQuietMode() { args.add("--warning_level=DEFAULT"); test("/** @const \n * @const */ var x;", RhinoErrorReporter.PARSE_ERROR); args.add("--warning_level=QUIET"); testSame("/** @const \n * @const */ var x;"); } public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {dom:{}};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); } public void testCssNameWiring() throws Exception { test("var goog = {}; goog.getCssName = function() {};" + "goog.setCssNameMapping = function() {};" + "goog.setCssNameMapping({'goog': 'a', 'button': 'b'});" + "var a = goog.getCssName('goog-button');" + "var b = goog.getCssName('css-button');" + "var c = goog.getCssName('goog-menu');" + "var d = goog.getCssName('css-menu');", "var goog = { getCssName: function() {}," + " setCssNameMapping: function() {} }," + " a = 'a-b'," + " b = 'css-b'," + " c = 'a-menu'," + " d = 'css-menu';"); } ////////////////////////////////////////////////////////////////////////////// // Integration tests public void testIssue70() { test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue81() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); useStringComparison = true; test("eval('1'); var x = eval; x('2');", "eval(\"1\");(0,eval)(\"2\");"); } public void testIssue115() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--jscomp_off=es5Strict"); args.add("--warning_level=VERBOSE"); test("function f() { " + " var arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}", "function f() { " + " arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}"); } public void testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);" + "}"); } public void testIssue504() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("void function() { alert('hi'); }();", "alert('hi');", CheckSideEffects.USELESS_CODE_ERROR); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); test("function foo(a) {}", "function foo() {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testDebugFlag3() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=false"); test("function Foo() {}" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "throw (new function() {}).a;"); } public void testDebugFlag4() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=true"); test("function Foo() {}" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "throw (new function Foo() {}).$x$;"); } public void testBooleanFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testBooleanFlag2() { args.add("--debug"); args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testHelpFlag() { args.add("--help"); assertFalse( createCommandLineRunner( new String[] {"function f() {}"}).shouldRunCompiler()); } public void testExternsLifting1() throws Exception{ String code = "/** @externs */ function f() {}"; test(new String[] {code}, new String[] {}); assertEquals(2, lastCompiler.getExternsForTesting().size()); CompilerInput extern = lastCompiler.getExternsForTesting().get(1); assertNull(extern.getModule()); assertTrue(extern.isExtern()); assertEquals(code, extern.getCode()); assertEquals(1, lastCompiler.getInputsForTesting().size()); CompilerInput input = lastCompiler.getInputsForTesting().get(0); assertNotNull(input.getModule()); assertFalse(input.isExtern()); assertEquals("", input.getCode()); } public void testExternsLifting2() { args.add("--warning_level=VERBOSE"); test(new String[] {"/** @externs */ function f() {}", "f(3);"}, new String[] {"f(3);"}, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testSourceSortingOff() { test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, ProcessClosurePrimitives.LATE_PROVIDE_ERROR); } public void testSourceSortingOn() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, new String[] { "var beer = {};", "" }); } public void testSourceSortingCircularDeps1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourceSortingCircularDeps2() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('roses.lime.juice');", "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');", "goog.provide('gimlet');" + " goog.require('gin'); goog.require('roses.lime.juice');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourcePruningOn1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "" }); } public void testSourcePruningOn2() { args.add("--closure_entry_point=guinness"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var guinness = {};" }); } public void testSourcePruningOn3() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var scotch = {}, x = 3;", }); } public void testSourcePruningOn4() { args.add("--closure_entry_point=scotch"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn5() { args.add("--closure_entry_point=shiraz"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, Compiler.MISSING_ENTRY_ERROR); } public void testSourcePruningOn6() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "", "var scotch = {}, x = 3;", }); } public void testForwardDeclareDroppedTypes() { args.add("--manage_closure_dependencies=true"); args.add("--warning_level=VERBOSE"); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}", "goog.provide('Scotch'); var x = 3;" }, new String[] { "var beer = {}; function f() {}", "" }); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}" }, new String[] { "var beer = {}; function f() {}", "" }, RhinoErrorReporter.TYPE_PARSE_ERROR); } public void testSourceMapExpansion1() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--create_source_map=%outname%.map"); testSame("var x = 3;"); assertEquals("/path/to/out.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion2() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion3() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo_"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo_m0.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootModule())); } public void testSourceMapFormat1() { args.add("--js_output_file"); args.add("/path/to/out.js"); testSame("var x = 3;"); assertEquals(SourceMap.Format.DEFAULT, lastCompiler.getOptions().sourceMapFormat); } public void testSourceMapFormat2() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--source_map_format=V3"); testSame("var x = 3;"); assertEquals(SourceMap.Format.V3, lastCompiler.getOptions().sourceMapFormat); } public void testCharSetExpansion() { testSame(""); assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset); args.add("--charset=UTF-8"); testSame(""); assertEquals("UTF-8", lastCompiler.getOptions().outputCharset); } public void testChainModuleManifest() throws Exception { useModules = ModulePattern.CHAIN; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestOrBundleTo( lastCompiler.getModuleGraph(), builder, true); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m1}\n" + "i2\n" + "\n" + "{m3:m2}\n" + "i3\n", builder.toString()); } public void testStarModuleManifest() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestOrBundleTo( lastCompiler.getModuleGraph(), builder, true); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m0}\n" + "i2\n" + "\n" + "{m3:m0}\n" + "i3\n", builder.toString()); } public void testVersionFlag() { args.add("--version"); testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testVersionFlag2() { lastArg = "--version"; testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testPrintAstFlag() { args.add("--print_ast=true"); testSame(""); assertEquals( "digraph AST {\n" + " node [color=lightblue2, style=filled];\n" + " node0 [label=\"BLOCK\"];\n" + " node1 [label=\"SCRIPT\"];\n" + " node0 -> node1 [weight=1];\n" + " node1 -> RETURN [label=\"UNCOND\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> RETURN [label=\"SYN_BLOCK\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> node1 [label=\"UNCOND\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + "}\n\n", new String(outReader.toByteArray())); } public void testSyntheticExterns() { externs = ImmutableList.of( JSSourceFile.fromCode("externs", "myVar.property;")); test("var theirVar = {}; var myVar = {}; var yourVar = {};", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var yourVar = {};", "var theirVar={},myVar={},yourVar={};"); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var myVar = {};", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testGoogAssertStripping() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("goog.asserts.assert(false)", ""); args.add("--debug"); test("goog.asserts.assert(false)", "goog.$asserts$.$assert$(!1)"); } public void testMissingReturnCheckOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @return {number} */ function f() {f()} f();", CheckMissingReturn.MISSING_RETURN_STATEMENT); } public void testGenerateExports() { args.add("--generate_exports=true"); test("/** @export */ foo.prototype.x = function() {};", "foo.prototype.x=function(){};"+ "goog.exportSymbol(\"foo.prototype.x\",foo.prototype.x);"); } public void testDepreciationWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @deprecated */ function f() {}; f()", CheckAccessControls.DEPRECATED_NAME); } public void testTwoParseErrors() { // If parse errors are reported in different files, make // sure all of them are reported. Compiler compiler = compile(new String[] { "var a b;", "var b c;" }); assertEquals(2, compiler.getErrors().length); } public void testES3ByDefault() { test("var x = f.function", RhinoErrorReporter.PARSE_ERROR); } public void testES5() { args.add("--language_in=ECMASCRIPT5"); test("var x = f.function", "var x = f.function"); test("var let", "var let"); } public void testES5Strict() { args.add("--language_in=ECMASCRIPT5_STRICT"); test("var x = f.function", "'use strict';var x = f.function"); test("var let", RhinoErrorReporter.PARSE_ERROR); } public void testES5StrictUseStrict() { args.add("--language_in=ECMASCRIPT5_STRICT"); Compiler compiler = compile(new String[] {"var x = f.function"}); String outputSource = compiler.toSource(); assertEquals("'use strict'", outputSource.substring(0, 12)); } public void testES5StrictUseStrictMultipleInputs() { args.add("--language_in=ECMASCRIPT5_STRICT"); Compiler compiler = compile(new String[] {"var x = f.function", "var y = f.function", "var z = f.function"}); String outputSource = compiler.toSource(); assertEquals("'use strict'", outputSource.substring(0, 12)); assertEquals(outputSource.substring(13).indexOf("'use strict'"), -1); } /* Helper functions */ private void testSame(String original) { testSame(new String[] { original }); } private void testSame(String[] original) { test(original, original); } private void test(String original, String compiled) { test(new String[] { original }, new String[] { compiled }); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(String[] original, String[] compiled) { test(original, compiled, null); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. * If {@code warning} is non-null, we will also check if the given * warning type was emitted. */ private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); if (warning == null) { assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); } Node root = compiler.getRoot().getLastChild(); if (useStringComparison) { assertEquals(Joiner.on("").join(compiled), compiler.toSource()); } else { Node expectedRoot = parse(compiled); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } /** * Asserts that when compiling, there is an error or warning. */ private void test(String original, DiagnosticType warning) { test(new String[] { original }, warning); } private void test(String original, String expected, DiagnosticType warning) { test(new String[] { original }, new String[] { expected }, warning); } /** * Asserts that when compiling, there is an error or warning. */ private void test(String[] original, DiagnosticType warning) { Compiler compiler = compile(original); assertEquals("Expected exactly one warning or error " + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 1, compiler.getErrors().length + compiler.getWarnings().length); assertTrue(exitCodes.size() > 0); int lastExitCode = exitCodes.get(exitCodes.size() - 1); if (compiler.getErrors().length > 0) { assertEquals(1, compiler.getErrors().length); assertEquals(warning, compiler.getErrors()[0].getType()); assertEquals(1, lastExitCode); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); assertEquals(0, lastExitCode); } } private CommandLineRunner createCommandLineRunner(String[] original) { for (int i = 0; i < original.length; i++) { args.add("--js"); args.add("/path/to/input" + i + ".js"); if (useModules == ModulePattern.CHAIN) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? (":mod" + (i - 1)) : "")); } else if (useModules == ModulePattern.STAR) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? ":mod0" : "")); } } if (lastArg != null) { args.add(lastArg); } String[] argStrings = args.toArray(new String[] {}); return new CommandLineRunner( argStrings, new PrintStream(outReader), new PrintStream(errReader)); } private Compiler compile(String[] original) { CommandLineRunner runner = createCommandLineRunner(original); assertTrue(runner.shouldRunCompiler()); Supplier<List<JSSourceFile>> inputsSupplier = null; Supplier<List<JSModule>> modulesSupplier = null; if (useModules == ModulePattern.NONE) { List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } inputsSupplier = Suppliers.ofInstance(inputs); } else if (useModules == ModulePattern.STAR) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleStar(original))); } else if (useModules == ModulePattern.CHAIN) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleChain(original))); } else { throw new IllegalArgumentException("Unknown module type: " + useModules); } runner.enableTestMode( Suppliers.<List<JSSourceFile>>ofInstance(externs), inputsSupplier, modulesSupplier, new Function<Integer, Boolean>() { @Override public Boolean apply(Integer code) { return exitCodes.add(code); } }); runner.run(); lastCompiler = runner.getCompiler(); lastCommandLineRunner = runner; return lastCompiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = new CommandLineRunner(argStrings); Compiler compiler = runner.createCompiler(); List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } CompilerOptions options = new CompilerOptions(); // ECMASCRIPT5 is the most forgiving. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.init(externs, inputs, options); Node all = compiler.parseInputs(); Preconditions.checkState(compiler.getErrorCount() == 0); Preconditions.checkNotNull(all); Node n = all.getLastChild(); return n; } }
public void testBrokenAnnotation() throws Exception { try { serializeAsString(MAPPER, new BrokenClass()); } catch (Exception e) { verifyException(e, "types not related"); } }
com.fasterxml.jackson.databind.ser.TestJsonSerialize::testBrokenAnnotation
src/test/java/com/fasterxml/jackson/databind/ser/TestJsonSerialize.java
153
src/test/java/com/fasterxml/jackson/databind/ser/TestJsonSerialize.java
testBrokenAnnotation
package com.fasterxml.jackson.databind.ser; import java.io.IOException; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * This unit test suite tests use of @JsonClass Annotation * with bean serialization. */ public class TestJsonSerialize extends BaseMapTest { /* /********************************************************** /* Annotated helper classes /********************************************************** */ interface ValueInterface { public int getX(); } static class ValueClass implements ValueInterface { @Override public int getX() { return 3; } public int getY() { return 5; } } /** * Test class to verify that <code>JsonSerialize.as</code> * works as expected */ static class WrapperClassForAs { @JsonSerialize(as=ValueInterface.class) public ValueClass getValue() { return new ValueClass(); } } // This should indicate that static type be used for all fields @JsonSerialize(typing=JsonSerialize.Typing.STATIC) static class WrapperClassForStaticTyping { public ValueInterface getValue() { return new ValueClass(); } } static class WrapperClassForStaticTyping2 { @JsonSerialize(typing=JsonSerialize.Typing.STATIC) public ValueInterface getStaticValue() { return new ValueClass(); } @JsonSerialize(typing=JsonSerialize.Typing.DYNAMIC) public ValueInterface getDynamicValue() { return new ValueClass(); } } /** * Test bean that has an invalid {@link JsonSerialize} annotation. */ static class BrokenClass { // invalid annotation: String not a supertype of Long @JsonSerialize(as=String.class) public Long getValue() { return Long.valueOf(4L); } } @SuppressWarnings("serial") static class ValueMap extends HashMap<String,ValueInterface> { } @SuppressWarnings("serial") static class ValueList extends ArrayList<ValueInterface> { } @SuppressWarnings("serial") static class ValueLinkedList extends LinkedList<ValueInterface> { } // Classes for [JACKSON-294] static class Foo294 { @JsonProperty private String id; @JsonSerialize(using = Bar294Serializer.class) private Bar294 bar; public Foo294() { } public Foo294(String id, String id2) { this.id = id; bar = new Bar294(id2); } } static class Bar294{ @JsonProperty protected String id; @JsonProperty protected String name; public Bar294() { } public Bar294(String id) { this.id = id; } public String getId() { return id; } public String getName() { return name; } } static class Bar294Serializer extends JsonSerializer<Bar294> { @Override public void serialize(Bar294 bar, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeString(bar.id); } } /* /********************************************************** /* Main tests /********************************************************** */ final ObjectMapper MAPPER = objectMapper(); @SuppressWarnings("unchecked") public void testSimpleValueDefinition() throws Exception { Map<String,Object> result = writeAndMap(MAPPER, new WrapperClassForAs()); assertEquals(1, result.size()); Object ob = result.get("value"); // Should see only "x", not "y" result = (Map<String,Object>) ob; assertEquals(1, result.size()); assertEquals(Integer.valueOf(3), result.get("x")); } public void testBrokenAnnotation() throws Exception { try { serializeAsString(MAPPER, new BrokenClass()); } catch (Exception e) { verifyException(e, "types not related"); } } @SuppressWarnings("unchecked") public void testStaticTypingForClass() throws Exception { Map<String,Object> result = writeAndMap(MAPPER, new WrapperClassForStaticTyping()); assertEquals(1, result.size()); Object ob = result.get("value"); // Should see only "x", not "y" result = (Map<String,Object>) ob; assertEquals(1, result.size()); assertEquals(Integer.valueOf(3), result.get("x")); } @SuppressWarnings("unchecked") public void testMixedTypingForClass() throws Exception { Map<String,Object> result = writeAndMap(MAPPER, new WrapperClassForStaticTyping2()); assertEquals(2, result.size()); Object obStatic = result.get("staticValue"); // Should see only "x", not "y" Map<String,Object> stat = (Map<String,Object>) obStatic; assertEquals(1, stat.size()); assertEquals(Integer.valueOf(3), stat.get("x")); Object obDynamic = result.get("dynamicValue"); // Should see both Map<String,Object> dyn = (Map<String,Object>) obDynamic; assertEquals(2, dyn.size()); assertEquals(Integer.valueOf(3), dyn.get("x")); assertEquals(Integer.valueOf(5), dyn.get("y")); } public void testStaticTypingWithMap() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(MapperFeature.USE_STATIC_TYPING, true); ValueMap map = new ValueMap(); map.put("a", new ValueClass()); assertEquals("{\"a\":{\"x\":3}}", serializeAsString(m, map)); } public void testStaticTypingWithArrayList() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(MapperFeature.USE_STATIC_TYPING, true); ValueList list = new ValueList(); list.add(new ValueClass()); assertEquals("[{\"x\":3}]", m.writeValueAsString(list)); } public void testStaticTypingWithLinkedList() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(MapperFeature.USE_STATIC_TYPING, true); ValueLinkedList list = new ValueLinkedList(); list.add(new ValueClass()); assertEquals("[{\"x\":3}]", serializeAsString(m, list)); } public void testStaticTypingWithArray() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(MapperFeature.USE_STATIC_TYPING, true); ValueInterface[] array = new ValueInterface[] { new ValueClass() }; assertEquals("[{\"x\":3}]", serializeAsString(m, array)); } public void testIssue294() throws Exception { assertEquals("{\"id\":\"fooId\",\"bar\":\"barId\"}", MAPPER.writeValueAsString(new Foo294("fooId", "barId"))); } @JsonPropertyOrder({ "a", "something" }) static class Response { public String a = "x"; @JsonProperty //does not show up public boolean isSomething() { return true; } } public void testWithIsGetter() throws Exception { ObjectMapper m = new ObjectMapper(); m.setVisibility(PropertyAccessor.GETTER, Visibility.NONE) .setVisibility(PropertyAccessor.FIELD, Visibility.ANY) .setVisibility(PropertyAccessor.CREATOR, Visibility.NONE) .setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE) .setVisibility(PropertyAccessor.SETTER, Visibility.NONE); final String JSON = m.writeValueAsString(new Response()); assertEquals(aposToQuotes("{'a':'x','something':true}"), JSON); } }
// You are a professional Java test case writer, please create a test case named `testBrokenAnnotation` for the issue `JacksonDatabind-1231`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1231 // // ## Issue-Title: // @JsonSerialize(as=superType) behavior disallowed in 2.7.4 // // ## Issue-Description: // [#1178](https://github.com/FasterXML/jackson-databind/issues/1178) fixed the problem with collections, but I'm seeing a problem with individual objects. // // // I'm getting: // // // // ``` // com.fasterxml.jackson.databind.JsonMappingException: Failed to widen type [simple type, class org.pharmgkb.model.AccessionIdentifier] with annotation (value org.pharmgkb.model.BaseAccessionIdentifier), from 'getReference': Class org.pharmgkb.model.BaseAccessionIdentifier not a super-type of [simple type, class org.pharmgkb.model.AccessionIdentifier] // // at com.fasterxml.jackson.databind.AnnotationIntrospector.refineSerializationType(AnnotationIntrospector.java:821) // at com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair.refineSerializationType(AnnotationIntrospectorPair.java:488) // at com.fasterxml.jackson.databind.ser.PropertyBuilder.findSerializationType(PropertyBuilder.java:194) // at com.fasterxml.jackson.databind.ser.PropertyBuilder.buildWriter(PropertyBuilder.java:73) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._constructWriter(BeanSerializerFactory.java:805) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanProperties(BeanSerializerFactory.java:608) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.constructBeanSerializer(BeanSerializerFactory.java:388) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanSerializer(BeanSerializerFactory.java:271) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._createSerializer2(BeanSerializerFactory.java:223) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:157) // at com.fasterxml.jackson.databind.SerializerProvider._createUntypedSerializer(SerializerProvider.java:1215) // at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1167) // at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:490) // at com.fasterxml.jackson.databind.SerializerProvider.findTypedValueSerializer(SerializerProvider.java:688) // at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:107) // at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1428) // at com.fasterxml.jackson.databind.ObjectWriter._configAndWriteValue(ObjectWriter.java:1129) // at com.fasterxml.jackson.databind.ObjectWriter.writeValueAsString(ObjectWriter.java:1001) // at org.pharmgkb.jackson.JacksonTest.testModelObjects(JacksonTest.java:48) // // ``` // // On something like: // // // // ``` // public class Foo { // @JsonSerialize(as = BaseAccessionIdentifier.class) // @JsonDeserialize(as = BaseAccessionIdentifier.class) // public AccessionIdentifier getReference() { // } // } // // ``` // // // ``` // public interface Access public void testBrokenAnnotation() throws Exception {
153
47
146
src/test/java/com/fasterxml/jackson/databind/ser/TestJsonSerialize.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1231 ## Issue-Title: @JsonSerialize(as=superType) behavior disallowed in 2.7.4 ## Issue-Description: [#1178](https://github.com/FasterXML/jackson-databind/issues/1178) fixed the problem with collections, but I'm seeing a problem with individual objects. I'm getting: ``` com.fasterxml.jackson.databind.JsonMappingException: Failed to widen type [simple type, class org.pharmgkb.model.AccessionIdentifier] with annotation (value org.pharmgkb.model.BaseAccessionIdentifier), from 'getReference': Class org.pharmgkb.model.BaseAccessionIdentifier not a super-type of [simple type, class org.pharmgkb.model.AccessionIdentifier] at com.fasterxml.jackson.databind.AnnotationIntrospector.refineSerializationType(AnnotationIntrospector.java:821) at com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair.refineSerializationType(AnnotationIntrospectorPair.java:488) at com.fasterxml.jackson.databind.ser.PropertyBuilder.findSerializationType(PropertyBuilder.java:194) at com.fasterxml.jackson.databind.ser.PropertyBuilder.buildWriter(PropertyBuilder.java:73) at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._constructWriter(BeanSerializerFactory.java:805) at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanProperties(BeanSerializerFactory.java:608) at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.constructBeanSerializer(BeanSerializerFactory.java:388) at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanSerializer(BeanSerializerFactory.java:271) at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._createSerializer2(BeanSerializerFactory.java:223) at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:157) at com.fasterxml.jackson.databind.SerializerProvider._createUntypedSerializer(SerializerProvider.java:1215) at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1167) at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:490) at com.fasterxml.jackson.databind.SerializerProvider.findTypedValueSerializer(SerializerProvider.java:688) at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:107) at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1428) at com.fasterxml.jackson.databind.ObjectWriter._configAndWriteValue(ObjectWriter.java:1129) at com.fasterxml.jackson.databind.ObjectWriter.writeValueAsString(ObjectWriter.java:1001) at org.pharmgkb.jackson.JacksonTest.testModelObjects(JacksonTest.java:48) ``` On something like: ``` public class Foo { @JsonSerialize(as = BaseAccessionIdentifier.class) @JsonDeserialize(as = BaseAccessionIdentifier.class) public AccessionIdentifier getReference() { } } ``` ``` public interface Access ``` You are a professional Java test case writer, please create a test case named `testBrokenAnnotation` for the issue `JacksonDatabind-1231`, utilizing the provided issue report information and the following function signature. ```java public void testBrokenAnnotation() throws Exception { ```
146
[ "com.fasterxml.jackson.databind.AnnotationIntrospector" ]
1499e12d0c8376f9d50aff4fadc8681d6c6cb744170331913fc44d7e9938fd34
public void testBrokenAnnotation() throws Exception
// You are a professional Java test case writer, please create a test case named `testBrokenAnnotation` for the issue `JacksonDatabind-1231`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1231 // // ## Issue-Title: // @JsonSerialize(as=superType) behavior disallowed in 2.7.4 // // ## Issue-Description: // [#1178](https://github.com/FasterXML/jackson-databind/issues/1178) fixed the problem with collections, but I'm seeing a problem with individual objects. // // // I'm getting: // // // // ``` // com.fasterxml.jackson.databind.JsonMappingException: Failed to widen type [simple type, class org.pharmgkb.model.AccessionIdentifier] with annotation (value org.pharmgkb.model.BaseAccessionIdentifier), from 'getReference': Class org.pharmgkb.model.BaseAccessionIdentifier not a super-type of [simple type, class org.pharmgkb.model.AccessionIdentifier] // // at com.fasterxml.jackson.databind.AnnotationIntrospector.refineSerializationType(AnnotationIntrospector.java:821) // at com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair.refineSerializationType(AnnotationIntrospectorPair.java:488) // at com.fasterxml.jackson.databind.ser.PropertyBuilder.findSerializationType(PropertyBuilder.java:194) // at com.fasterxml.jackson.databind.ser.PropertyBuilder.buildWriter(PropertyBuilder.java:73) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._constructWriter(BeanSerializerFactory.java:805) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanProperties(BeanSerializerFactory.java:608) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.constructBeanSerializer(BeanSerializerFactory.java:388) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanSerializer(BeanSerializerFactory.java:271) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._createSerializer2(BeanSerializerFactory.java:223) // at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:157) // at com.fasterxml.jackson.databind.SerializerProvider._createUntypedSerializer(SerializerProvider.java:1215) // at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1167) // at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:490) // at com.fasterxml.jackson.databind.SerializerProvider.findTypedValueSerializer(SerializerProvider.java:688) // at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:107) // at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1428) // at com.fasterxml.jackson.databind.ObjectWriter._configAndWriteValue(ObjectWriter.java:1129) // at com.fasterxml.jackson.databind.ObjectWriter.writeValueAsString(ObjectWriter.java:1001) // at org.pharmgkb.jackson.JacksonTest.testModelObjects(JacksonTest.java:48) // // ``` // // On something like: // // // // ``` // public class Foo { // @JsonSerialize(as = BaseAccessionIdentifier.class) // @JsonDeserialize(as = BaseAccessionIdentifier.class) // public AccessionIdentifier getReference() { // } // } // // ``` // // // ``` // public interface Access
JacksonDatabind
package com.fasterxml.jackson.databind.ser; import java.io.IOException; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * This unit test suite tests use of @JsonClass Annotation * with bean serialization. */ public class TestJsonSerialize extends BaseMapTest { /* /********************************************************** /* Annotated helper classes /********************************************************** */ interface ValueInterface { public int getX(); } static class ValueClass implements ValueInterface { @Override public int getX() { return 3; } public int getY() { return 5; } } /** * Test class to verify that <code>JsonSerialize.as</code> * works as expected */ static class WrapperClassForAs { @JsonSerialize(as=ValueInterface.class) public ValueClass getValue() { return new ValueClass(); } } // This should indicate that static type be used for all fields @JsonSerialize(typing=JsonSerialize.Typing.STATIC) static class WrapperClassForStaticTyping { public ValueInterface getValue() { return new ValueClass(); } } static class WrapperClassForStaticTyping2 { @JsonSerialize(typing=JsonSerialize.Typing.STATIC) public ValueInterface getStaticValue() { return new ValueClass(); } @JsonSerialize(typing=JsonSerialize.Typing.DYNAMIC) public ValueInterface getDynamicValue() { return new ValueClass(); } } /** * Test bean that has an invalid {@link JsonSerialize} annotation. */ static class BrokenClass { // invalid annotation: String not a supertype of Long @JsonSerialize(as=String.class) public Long getValue() { return Long.valueOf(4L); } } @SuppressWarnings("serial") static class ValueMap extends HashMap<String,ValueInterface> { } @SuppressWarnings("serial") static class ValueList extends ArrayList<ValueInterface> { } @SuppressWarnings("serial") static class ValueLinkedList extends LinkedList<ValueInterface> { } // Classes for [JACKSON-294] static class Foo294 { @JsonProperty private String id; @JsonSerialize(using = Bar294Serializer.class) private Bar294 bar; public Foo294() { } public Foo294(String id, String id2) { this.id = id; bar = new Bar294(id2); } } static class Bar294{ @JsonProperty protected String id; @JsonProperty protected String name; public Bar294() { } public Bar294(String id) { this.id = id; } public String getId() { return id; } public String getName() { return name; } } static class Bar294Serializer extends JsonSerializer<Bar294> { @Override public void serialize(Bar294 bar, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeString(bar.id); } } /* /********************************************************** /* Main tests /********************************************************** */ final ObjectMapper MAPPER = objectMapper(); @SuppressWarnings("unchecked") public void testSimpleValueDefinition() throws Exception { Map<String,Object> result = writeAndMap(MAPPER, new WrapperClassForAs()); assertEquals(1, result.size()); Object ob = result.get("value"); // Should see only "x", not "y" result = (Map<String,Object>) ob; assertEquals(1, result.size()); assertEquals(Integer.valueOf(3), result.get("x")); } public void testBrokenAnnotation() throws Exception { try { serializeAsString(MAPPER, new BrokenClass()); } catch (Exception e) { verifyException(e, "types not related"); } } @SuppressWarnings("unchecked") public void testStaticTypingForClass() throws Exception { Map<String,Object> result = writeAndMap(MAPPER, new WrapperClassForStaticTyping()); assertEquals(1, result.size()); Object ob = result.get("value"); // Should see only "x", not "y" result = (Map<String,Object>) ob; assertEquals(1, result.size()); assertEquals(Integer.valueOf(3), result.get("x")); } @SuppressWarnings("unchecked") public void testMixedTypingForClass() throws Exception { Map<String,Object> result = writeAndMap(MAPPER, new WrapperClassForStaticTyping2()); assertEquals(2, result.size()); Object obStatic = result.get("staticValue"); // Should see only "x", not "y" Map<String,Object> stat = (Map<String,Object>) obStatic; assertEquals(1, stat.size()); assertEquals(Integer.valueOf(3), stat.get("x")); Object obDynamic = result.get("dynamicValue"); // Should see both Map<String,Object> dyn = (Map<String,Object>) obDynamic; assertEquals(2, dyn.size()); assertEquals(Integer.valueOf(3), dyn.get("x")); assertEquals(Integer.valueOf(5), dyn.get("y")); } public void testStaticTypingWithMap() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(MapperFeature.USE_STATIC_TYPING, true); ValueMap map = new ValueMap(); map.put("a", new ValueClass()); assertEquals("{\"a\":{\"x\":3}}", serializeAsString(m, map)); } public void testStaticTypingWithArrayList() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(MapperFeature.USE_STATIC_TYPING, true); ValueList list = new ValueList(); list.add(new ValueClass()); assertEquals("[{\"x\":3}]", m.writeValueAsString(list)); } public void testStaticTypingWithLinkedList() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(MapperFeature.USE_STATIC_TYPING, true); ValueLinkedList list = new ValueLinkedList(); list.add(new ValueClass()); assertEquals("[{\"x\":3}]", serializeAsString(m, list)); } public void testStaticTypingWithArray() throws Exception { ObjectMapper m = new ObjectMapper(); m.configure(MapperFeature.USE_STATIC_TYPING, true); ValueInterface[] array = new ValueInterface[] { new ValueClass() }; assertEquals("[{\"x\":3}]", serializeAsString(m, array)); } public void testIssue294() throws Exception { assertEquals("{\"id\":\"fooId\",\"bar\":\"barId\"}", MAPPER.writeValueAsString(new Foo294("fooId", "barId"))); } @JsonPropertyOrder({ "a", "something" }) static class Response { public String a = "x"; @JsonProperty //does not show up public boolean isSomething() { return true; } } public void testWithIsGetter() throws Exception { ObjectMapper m = new ObjectMapper(); m.setVisibility(PropertyAccessor.GETTER, Visibility.NONE) .setVisibility(PropertyAccessor.FIELD, Visibility.ANY) .setVisibility(PropertyAccessor.CREATOR, Visibility.NONE) .setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE) .setVisibility(PropertyAccessor.SETTER, Visibility.NONE); final String JSON = m.writeValueAsString(new Response()); assertEquals(aposToQuotes("{'a':'x','something':true}"), JSON); } }
public void testStringJoinAdd() { fold("x = ['a', 'b', 'c'].join('')", "x = \"abc\""); fold("x = [].join(',')", "x = \"\""); fold("x = ['a'].join(',')", "x = \"a\""); fold("x = ['a', 'b', 'c'].join(',')", "x = \"a,b,c\""); fold("x = ['a', foo, 'b', 'c'].join(',')", "x = [\"a\",foo,\"b,c\"].join()"); fold("x = [foo, 'a', 'b', 'c'].join(',')", "x = [foo,\"a,b,c\"].join()"); fold("x = ['a', 'b', 'c', foo].join(',')", "x = [\"a,b,c\",foo].join()"); // Works with numbers fold("x = ['a=', 5].join('')", "x = \"a=5\""); fold("x = ['a', '5'].join(7)", "x = \"a75\""); // Works on boolean fold("x = ['a=', false].join('')", "x = \"a=false\""); fold("x = ['a', '5'].join(true)", "x = \"atrue5\""); fold("x = ['a', '5'].join(false)", "x = \"afalse5\""); // Only optimize if it's a size win. fold("x = ['a', '5', 'c'].join('a very very very long chain')", "x = [\"a\",\"5\",\"c\"].join(\"a very very very long chain\")"); // TODO(user): Its possible to fold this better. foldSame("x = ['', foo].join('-')"); foldSame("x = ['', foo, ''].join()"); fold("x = ['', '', foo, ''].join(',')", "x = [',', foo, ''].join()"); fold("x = ['', '', foo, '', ''].join(',')", "x = [',', foo, ','].join()"); fold("x = ['', '', foo, '', '', bar].join(',')", "x = [',', foo, ',', bar].join()"); fold("x = [1,2,3].join('abcdef')", "x = '1abcdef2abcdef3'"); fold("x = [1,2].join()", "x = '1,2'"); fold("x = [null,undefined,''].join(',')", "x = ',,'"); fold("x = [null,undefined,0].join(',')", "x = ',,0'"); // This can be folded but we don't currently. foldSame("x = [[1,2],[3,4]].join()"); // would like: "x = '1,2,3,4'" }
com.google.javascript.jscomp.PeepholeReplaceKnownMethodsTest::testStringJoinAdd
test/com/google/javascript/jscomp/PeepholeReplaceKnownMethodsTest.java
126
test/com/google/javascript/jscomp/PeepholeReplaceKnownMethodsTest.java
testStringJoinAdd
/* * Copyright 2011 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Unit tests for {#link {@link PeepholeReplaceKnownMethods} * */ public class PeepholeReplaceKnownMethodsTest extends CompilerTestCase { public PeepholeReplaceKnownMethodsTest() { super(""); } @Override public void setUp() { enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeReplaceKnownMethods()); return peepholePass; } public void testStringIndexOf() { fold("x = 'abcdef'.indexOf('b')", "x = 1"); fold("x = 'abcdefbe'.indexOf('b', 2)", "x = 6"); fold("x = 'abcdef'.indexOf('bcd')", "x = 1"); fold("x = 'abcdefsdfasdfbcdassd'.indexOf('bcd', 4)", "x = 13"); fold("x = 'abcdef'.lastIndexOf('b')", "x = 1"); fold("x = 'abcdefbe'.lastIndexOf('b')", "x = 6"); fold("x = 'abcdefbe'.lastIndexOf('b', 5)", "x = 1"); // Both elements must be string. Dont do anything if either one is not // string. fold("x = 'abc1def'.indexOf(1)", "x = 3"); fold("x = 'abcNaNdef'.indexOf(NaN)", "x = 3"); fold("x = 'abcundefineddef'.indexOf(undefined)", "x = 3"); fold("x = 'abcnulldef'.indexOf(null)", "x = 3"); fold("x = 'abctruedef'.indexOf(true)", "x = 3"); // The following testcase fails with JSC_PARSE_ERROR. Hence omitted. // foldSame("x = 1.indexOf('bcd');"); foldSame("x = NaN.indexOf('bcd')"); foldSame("x = undefined.indexOf('bcd')"); foldSame("x = null.indexOf('bcd')"); foldSame("x = true.indexOf('bcd')"); foldSame("x = false.indexOf('bcd')"); // Avoid dealing with regex or other types. foldSame("x = 'abcdef'.indexOf(/b./)"); foldSame("x = 'abcdef'.indexOf({a:2})"); foldSame("x = 'abcdef'.indexOf([1,2])"); } public void testStringJoinAddSparse() { fold("x = [,,'a'].join(',')", "x = ',,a'"); } public void testNoStringJoin() { foldSame("x = [].join(',',2)"); foldSame("x = [].join(f)"); } public void testStringJoinAdd() { fold("x = ['a', 'b', 'c'].join('')", "x = \"abc\""); fold("x = [].join(',')", "x = \"\""); fold("x = ['a'].join(',')", "x = \"a\""); fold("x = ['a', 'b', 'c'].join(',')", "x = \"a,b,c\""); fold("x = ['a', foo, 'b', 'c'].join(',')", "x = [\"a\",foo,\"b,c\"].join()"); fold("x = [foo, 'a', 'b', 'c'].join(',')", "x = [foo,\"a,b,c\"].join()"); fold("x = ['a', 'b', 'c', foo].join(',')", "x = [\"a,b,c\",foo].join()"); // Works with numbers fold("x = ['a=', 5].join('')", "x = \"a=5\""); fold("x = ['a', '5'].join(7)", "x = \"a75\""); // Works on boolean fold("x = ['a=', false].join('')", "x = \"a=false\""); fold("x = ['a', '5'].join(true)", "x = \"atrue5\""); fold("x = ['a', '5'].join(false)", "x = \"afalse5\""); // Only optimize if it's a size win. fold("x = ['a', '5', 'c'].join('a very very very long chain')", "x = [\"a\",\"5\",\"c\"].join(\"a very very very long chain\")"); // TODO(user): Its possible to fold this better. foldSame("x = ['', foo].join('-')"); foldSame("x = ['', foo, ''].join()"); fold("x = ['', '', foo, ''].join(',')", "x = [',', foo, ''].join()"); fold("x = ['', '', foo, '', ''].join(',')", "x = [',', foo, ','].join()"); fold("x = ['', '', foo, '', '', bar].join(',')", "x = [',', foo, ',', bar].join()"); fold("x = [1,2,3].join('abcdef')", "x = '1abcdef2abcdef3'"); fold("x = [1,2].join()", "x = '1,2'"); fold("x = [null,undefined,''].join(',')", "x = ',,'"); fold("x = [null,undefined,0].join(',')", "x = ',,0'"); // This can be folded but we don't currently. foldSame("x = [[1,2],[3,4]].join()"); // would like: "x = '1,2,3,4'" } public void testStringJoinAdd_b1992789() { fold("x = ['a'].join('')", "x = \"a\""); fold("x = [foo()].join('')", "x = '' + foo()"); fold("[foo()].join('')", "'' + foo()"); } public void testFoldStringSubstr() { fold("x = 'abcde'.substr(0,2)", "x = 'ab'"); fold("x = 'abcde'.substr(1,2)", "x = 'bc'"); fold("x = 'abcde'['substr'](1,3)", "x = 'bcd'"); fold("x = 'abcde'.substr(2)", "x = 'cde'"); // we should be leaving negative indexes alone for now foldSame("x = 'abcde'.substr(-1)"); foldSame("x = 'abcde'.substr(1, -2)"); foldSame("x = 'abcde'.substr(1, 2, 3)"); foldSame("x = 'a'.substr(0, 2)"); } public void testFoldStringSubstring() { fold("x = 'abcde'.substring(0,2)", "x = 'ab'"); fold("x = 'abcde'.substring(1,2)", "x = 'b'"); fold("x = 'abcde'['substring'](1,3)", "x = 'bc'"); fold("x = 'abcde'.substring(2)", "x = 'cde'"); // we should be leaving negative indexes alone for now foldSame("x = 'abcde'.substring(-1)"); foldSame("x = 'abcde'.substring(1, -2)"); foldSame("x = 'abcde'.substring(1, 2, 3)"); foldSame("x = 'a'.substring(0, 2)"); } public void testFoldStringCharAt() { fold("x = 'abcde'.charAt(0)", "x = 'a'"); fold("x = 'abcde'.charAt(1)", "x = 'b'"); fold("x = 'abcde'.charAt(2)", "x = 'c'"); fold("x = 'abcde'.charAt(3)", "x = 'd'"); fold("x = 'abcde'.charAt(4)", "x = 'e'"); foldSame("x = 'abcde'.charAt(5)"); // or x = '' foldSame("x = 'abcde'.charAt(-1)"); // or x = '' foldSame("x = 'abcde'.charAt(y)"); foldSame("x = 'abcde'.charAt()"); // or x = 'a' foldSame("x = 'abcde'.charAt(0, ++z)"); // or (++z, 'a') foldSame("x = 'abcde'.charAt(null)"); // or x = 'a' foldSame("x = 'abcde'.charAt(true)"); // or x = 'b' fold("x = '\\ud834\udd1e'.charAt(0)", "x = '\\ud834'"); fold("x = '\\ud834\udd1e'.charAt(1)", "x = '\\udd1e'"); } public void testFoldStringCharCodeAt() { fold("x = 'abcde'.charCodeAt(0)", "x = 97"); fold("x = 'abcde'.charCodeAt(1)", "x = 98"); fold("x = 'abcde'.charCodeAt(2)", "x = 99"); fold("x = 'abcde'.charCodeAt(3)", "x = 100"); fold("x = 'abcde'.charCodeAt(4)", "x = 101"); foldSame("x = 'abcde'.charCodeAt(5)"); // or x = (0/0) foldSame("x = 'abcde'.charCodeAt(-1)"); // or x = (0/0) foldSame("x = 'abcde'.charCodeAt(y)"); foldSame("x = 'abcde'.charCodeAt()"); // or x = 97 foldSame("x = 'abcde'.charCodeAt(0, ++z)"); // or (++z, 97) foldSame("x = 'abcde'.charCodeAt(null)"); // or x = 97 foldSame("x = 'abcde'.charCodeAt(true)"); // or x = 98 fold("x = '\\ud834\udd1e'.charCodeAt(0)", "x = 55348"); fold("x = '\\ud834\udd1e'.charCodeAt(1)", "x = 56606"); } public void testJoinBug() { fold("var x = [].join();", "var x = '';"); fold("var x = [x].join();", "var x = '' + x;"); foldSame("var x = [x,y].join();"); foldSame("var x = [x,y,z].join();"); foldSame("shape['matrix'] = [\n" + " Number(headingCos2).toFixed(4),\n" + " Number(-headingSin2).toFixed(4),\n" + " Number(headingSin2 * yScale).toFixed(4),\n" + " Number(headingCos2 * yScale).toFixed(4),\n" + " 0,\n" + " 0\n" + " ].join()"); } public void testToUpper() { fold("'a'.toUpperCase()", "'A'"); fold("'A'.toUpperCase()", "'A'"); fold("'aBcDe'.toUpperCase()", "'ABCDE'"); } public void testToLower() { fold("'A'.toLowerCase()", "'a'"); fold("'a'.toLowerCase()", "'a'"); fold("'aBcDe'.toLowerCase()", "'abcde'"); } public void testFoldParseNumbers() { enableNormalize(); enableEcmaScript5(true); fold("x = parseInt('123')", "x = 123"); fold("x = parseInt(' 123')", "x = 123"); fold("x = parseInt('123', 10)", "x = 123"); fold("x = parseInt('0xA')", "x = 10"); fold("x = parseInt('0xA', 16)", "x = 10"); fold("x = parseInt('07', 8)", "x = 7"); fold("x = parseInt('08')", "x = 8"); fold("x = parseFloat('1.23')", "x = 1.23"); fold("x = parseFloat('1.2300')", "x = 1.23"); fold("x = parseFloat(' 0.3333')", "x = 0.3333"); //Mozilla Dev Center test cases fold("x = parseInt(' 0xF', 16)", "x = 15"); fold("x = parseInt(' F', 16)", "x = 15"); fold("x = parseInt('17', 8)", "x = 15"); fold("x = parseInt('015', 10)", "x = 15"); fold("x = parseInt('1111', 2)", "x = 15"); fold("x = parseInt('12', 13)", "x = 15"); fold("x = parseInt(021, 8)", "x = 15"); fold("x = parseInt(15.99, 10)", "x = 15"); fold("x = parseFloat('3.14')", "x = 3.14"); fold("x = parseFloat(3.14)", "x = 3.14"); //Valid calls - unable to fold foldSame("x = parseInt('FXX123', 16)"); foldSame("x = parseInt('15*3', 10)"); foldSame("x = parseInt('15e2', 10)"); foldSame("x = parseInt('15px', 10)"); foldSame("x = parseInt('-0x08')"); foldSame("x = parseInt('1', -1)"); foldSame("x = parseFloat('3.14more non-digit characters')"); foldSame("x = parseFloat('314e-2')"); foldSame("x = parseFloat('0.0314E+2')"); foldSame("x = parseFloat('3.333333333333333333333333')"); //Invalid calls foldSame("x = parseInt('0xa', 10)"); enableEcmaScript5(false); foldSame("x = parseInt('08')"); } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } }
// You are a professional Java test case writer, please create a test case named `testStringJoinAdd` for the issue `Closure-558`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-558 // // ## Issue-Title: // Optimisation: convert array.join(",") to array.join() // // ## Issue-Description: // **What steps will reproduce the problem?** // // Compile this code: // // var variable = confirm("value from user"); // var array = [ "constant", variable ]; // alert( array.join(",") ); // // // **What is the expected output? What do you see instead?** // // $ java -jar /usr/local/slando/lib/Google/compiler.jar --compilation\_level ADVANCED\_OPTIMIZATIONS --js foo.js // var a=["constant",confirm("value from user")];alert(a.join(",")); // // We could save three bytes here by producing: // // var a=["constant",confirm("value from user")];alert(a.join()); // // // **What version of the product are you using? On what operating system?** // // $ java -jar /usr/local/slando/lib/Google/compiler.jar --version // Closure Compiler (http://code.google.com/closure/compiler) // Version: 1180 // Built on: 2011/06/15 21:40 // // Running on Linux 2.6.18 // // // **Please provide any additional information below.** // // Here's a common pattern this would be useful in: // // var my\_jquery\_selectors = []; // // ... append to my\_jquery\_selectors from various parts of the codebase ... // $(my\_jquery\_selectors.join(",")).html("the code is more readable with the comma left in place"); // // public void testStringJoinAdd() {
126
50
81
test/com/google/javascript/jscomp/PeepholeReplaceKnownMethodsTest.java
test
```markdown ## Issue-ID: Closure-558 ## Issue-Title: Optimisation: convert array.join(",") to array.join() ## Issue-Description: **What steps will reproduce the problem?** Compile this code: var variable = confirm("value from user"); var array = [ "constant", variable ]; alert( array.join(",") ); **What is the expected output? What do you see instead?** $ java -jar /usr/local/slando/lib/Google/compiler.jar --compilation\_level ADVANCED\_OPTIMIZATIONS --js foo.js var a=["constant",confirm("value from user")];alert(a.join(",")); We could save three bytes here by producing: var a=["constant",confirm("value from user")];alert(a.join()); **What version of the product are you using? On what operating system?** $ java -jar /usr/local/slando/lib/Google/compiler.jar --version Closure Compiler (http://code.google.com/closure/compiler) Version: 1180 Built on: 2011/06/15 21:40 Running on Linux 2.6.18 **Please provide any additional information below.** Here's a common pattern this would be useful in: var my\_jquery\_selectors = []; // ... append to my\_jquery\_selectors from various parts of the codebase ... $(my\_jquery\_selectors.join(",")).html("the code is more readable with the comma left in place"); ``` You are a professional Java test case writer, please create a test case named `testStringJoinAdd` for the issue `Closure-558`, utilizing the provided issue report information and the following function signature. ```java public void testStringJoinAdd() { ```
81
[ "com.google.javascript.jscomp.PeepholeReplaceKnownMethods" ]
14dd45fd946d71103e88a9c15e037999fc0065fb44fabea64ff230dcfa790ecc
public void testStringJoinAdd()
// You are a professional Java test case writer, please create a test case named `testStringJoinAdd` for the issue `Closure-558`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-558 // // ## Issue-Title: // Optimisation: convert array.join(",") to array.join() // // ## Issue-Description: // **What steps will reproduce the problem?** // // Compile this code: // // var variable = confirm("value from user"); // var array = [ "constant", variable ]; // alert( array.join(",") ); // // // **What is the expected output? What do you see instead?** // // $ java -jar /usr/local/slando/lib/Google/compiler.jar --compilation\_level ADVANCED\_OPTIMIZATIONS --js foo.js // var a=["constant",confirm("value from user")];alert(a.join(",")); // // We could save three bytes here by producing: // // var a=["constant",confirm("value from user")];alert(a.join()); // // // **What version of the product are you using? On what operating system?** // // $ java -jar /usr/local/slando/lib/Google/compiler.jar --version // Closure Compiler (http://code.google.com/closure/compiler) // Version: 1180 // Built on: 2011/06/15 21:40 // // Running on Linux 2.6.18 // // // **Please provide any additional information below.** // // Here's a common pattern this would be useful in: // // var my\_jquery\_selectors = []; // // ... append to my\_jquery\_selectors from various parts of the codebase ... // $(my\_jquery\_selectors.join(",")).html("the code is more readable with the comma left in place"); // //
Closure
/* * Copyright 2011 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Unit tests for {#link {@link PeepholeReplaceKnownMethods} * */ public class PeepholeReplaceKnownMethodsTest extends CompilerTestCase { public PeepholeReplaceKnownMethodsTest() { super(""); } @Override public void setUp() { enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeReplaceKnownMethods()); return peepholePass; } public void testStringIndexOf() { fold("x = 'abcdef'.indexOf('b')", "x = 1"); fold("x = 'abcdefbe'.indexOf('b', 2)", "x = 6"); fold("x = 'abcdef'.indexOf('bcd')", "x = 1"); fold("x = 'abcdefsdfasdfbcdassd'.indexOf('bcd', 4)", "x = 13"); fold("x = 'abcdef'.lastIndexOf('b')", "x = 1"); fold("x = 'abcdefbe'.lastIndexOf('b')", "x = 6"); fold("x = 'abcdefbe'.lastIndexOf('b', 5)", "x = 1"); // Both elements must be string. Dont do anything if either one is not // string. fold("x = 'abc1def'.indexOf(1)", "x = 3"); fold("x = 'abcNaNdef'.indexOf(NaN)", "x = 3"); fold("x = 'abcundefineddef'.indexOf(undefined)", "x = 3"); fold("x = 'abcnulldef'.indexOf(null)", "x = 3"); fold("x = 'abctruedef'.indexOf(true)", "x = 3"); // The following testcase fails with JSC_PARSE_ERROR. Hence omitted. // foldSame("x = 1.indexOf('bcd');"); foldSame("x = NaN.indexOf('bcd')"); foldSame("x = undefined.indexOf('bcd')"); foldSame("x = null.indexOf('bcd')"); foldSame("x = true.indexOf('bcd')"); foldSame("x = false.indexOf('bcd')"); // Avoid dealing with regex or other types. foldSame("x = 'abcdef'.indexOf(/b./)"); foldSame("x = 'abcdef'.indexOf({a:2})"); foldSame("x = 'abcdef'.indexOf([1,2])"); } public void testStringJoinAddSparse() { fold("x = [,,'a'].join(',')", "x = ',,a'"); } public void testNoStringJoin() { foldSame("x = [].join(',',2)"); foldSame("x = [].join(f)"); } public void testStringJoinAdd() { fold("x = ['a', 'b', 'c'].join('')", "x = \"abc\""); fold("x = [].join(',')", "x = \"\""); fold("x = ['a'].join(',')", "x = \"a\""); fold("x = ['a', 'b', 'c'].join(',')", "x = \"a,b,c\""); fold("x = ['a', foo, 'b', 'c'].join(',')", "x = [\"a\",foo,\"b,c\"].join()"); fold("x = [foo, 'a', 'b', 'c'].join(',')", "x = [foo,\"a,b,c\"].join()"); fold("x = ['a', 'b', 'c', foo].join(',')", "x = [\"a,b,c\",foo].join()"); // Works with numbers fold("x = ['a=', 5].join('')", "x = \"a=5\""); fold("x = ['a', '5'].join(7)", "x = \"a75\""); // Works on boolean fold("x = ['a=', false].join('')", "x = \"a=false\""); fold("x = ['a', '5'].join(true)", "x = \"atrue5\""); fold("x = ['a', '5'].join(false)", "x = \"afalse5\""); // Only optimize if it's a size win. fold("x = ['a', '5', 'c'].join('a very very very long chain')", "x = [\"a\",\"5\",\"c\"].join(\"a very very very long chain\")"); // TODO(user): Its possible to fold this better. foldSame("x = ['', foo].join('-')"); foldSame("x = ['', foo, ''].join()"); fold("x = ['', '', foo, ''].join(',')", "x = [',', foo, ''].join()"); fold("x = ['', '', foo, '', ''].join(',')", "x = [',', foo, ','].join()"); fold("x = ['', '', foo, '', '', bar].join(',')", "x = [',', foo, ',', bar].join()"); fold("x = [1,2,3].join('abcdef')", "x = '1abcdef2abcdef3'"); fold("x = [1,2].join()", "x = '1,2'"); fold("x = [null,undefined,''].join(',')", "x = ',,'"); fold("x = [null,undefined,0].join(',')", "x = ',,0'"); // This can be folded but we don't currently. foldSame("x = [[1,2],[3,4]].join()"); // would like: "x = '1,2,3,4'" } public void testStringJoinAdd_b1992789() { fold("x = ['a'].join('')", "x = \"a\""); fold("x = [foo()].join('')", "x = '' + foo()"); fold("[foo()].join('')", "'' + foo()"); } public void testFoldStringSubstr() { fold("x = 'abcde'.substr(0,2)", "x = 'ab'"); fold("x = 'abcde'.substr(1,2)", "x = 'bc'"); fold("x = 'abcde'['substr'](1,3)", "x = 'bcd'"); fold("x = 'abcde'.substr(2)", "x = 'cde'"); // we should be leaving negative indexes alone for now foldSame("x = 'abcde'.substr(-1)"); foldSame("x = 'abcde'.substr(1, -2)"); foldSame("x = 'abcde'.substr(1, 2, 3)"); foldSame("x = 'a'.substr(0, 2)"); } public void testFoldStringSubstring() { fold("x = 'abcde'.substring(0,2)", "x = 'ab'"); fold("x = 'abcde'.substring(1,2)", "x = 'b'"); fold("x = 'abcde'['substring'](1,3)", "x = 'bc'"); fold("x = 'abcde'.substring(2)", "x = 'cde'"); // we should be leaving negative indexes alone for now foldSame("x = 'abcde'.substring(-1)"); foldSame("x = 'abcde'.substring(1, -2)"); foldSame("x = 'abcde'.substring(1, 2, 3)"); foldSame("x = 'a'.substring(0, 2)"); } public void testFoldStringCharAt() { fold("x = 'abcde'.charAt(0)", "x = 'a'"); fold("x = 'abcde'.charAt(1)", "x = 'b'"); fold("x = 'abcde'.charAt(2)", "x = 'c'"); fold("x = 'abcde'.charAt(3)", "x = 'd'"); fold("x = 'abcde'.charAt(4)", "x = 'e'"); foldSame("x = 'abcde'.charAt(5)"); // or x = '' foldSame("x = 'abcde'.charAt(-1)"); // or x = '' foldSame("x = 'abcde'.charAt(y)"); foldSame("x = 'abcde'.charAt()"); // or x = 'a' foldSame("x = 'abcde'.charAt(0, ++z)"); // or (++z, 'a') foldSame("x = 'abcde'.charAt(null)"); // or x = 'a' foldSame("x = 'abcde'.charAt(true)"); // or x = 'b' fold("x = '\\ud834\udd1e'.charAt(0)", "x = '\\ud834'"); fold("x = '\\ud834\udd1e'.charAt(1)", "x = '\\udd1e'"); } public void testFoldStringCharCodeAt() { fold("x = 'abcde'.charCodeAt(0)", "x = 97"); fold("x = 'abcde'.charCodeAt(1)", "x = 98"); fold("x = 'abcde'.charCodeAt(2)", "x = 99"); fold("x = 'abcde'.charCodeAt(3)", "x = 100"); fold("x = 'abcde'.charCodeAt(4)", "x = 101"); foldSame("x = 'abcde'.charCodeAt(5)"); // or x = (0/0) foldSame("x = 'abcde'.charCodeAt(-1)"); // or x = (0/0) foldSame("x = 'abcde'.charCodeAt(y)"); foldSame("x = 'abcde'.charCodeAt()"); // or x = 97 foldSame("x = 'abcde'.charCodeAt(0, ++z)"); // or (++z, 97) foldSame("x = 'abcde'.charCodeAt(null)"); // or x = 97 foldSame("x = 'abcde'.charCodeAt(true)"); // or x = 98 fold("x = '\\ud834\udd1e'.charCodeAt(0)", "x = 55348"); fold("x = '\\ud834\udd1e'.charCodeAt(1)", "x = 56606"); } public void testJoinBug() { fold("var x = [].join();", "var x = '';"); fold("var x = [x].join();", "var x = '' + x;"); foldSame("var x = [x,y].join();"); foldSame("var x = [x,y,z].join();"); foldSame("shape['matrix'] = [\n" + " Number(headingCos2).toFixed(4),\n" + " Number(-headingSin2).toFixed(4),\n" + " Number(headingSin2 * yScale).toFixed(4),\n" + " Number(headingCos2 * yScale).toFixed(4),\n" + " 0,\n" + " 0\n" + " ].join()"); } public void testToUpper() { fold("'a'.toUpperCase()", "'A'"); fold("'A'.toUpperCase()", "'A'"); fold("'aBcDe'.toUpperCase()", "'ABCDE'"); } public void testToLower() { fold("'A'.toLowerCase()", "'a'"); fold("'a'.toLowerCase()", "'a'"); fold("'aBcDe'.toLowerCase()", "'abcde'"); } public void testFoldParseNumbers() { enableNormalize(); enableEcmaScript5(true); fold("x = parseInt('123')", "x = 123"); fold("x = parseInt(' 123')", "x = 123"); fold("x = parseInt('123', 10)", "x = 123"); fold("x = parseInt('0xA')", "x = 10"); fold("x = parseInt('0xA', 16)", "x = 10"); fold("x = parseInt('07', 8)", "x = 7"); fold("x = parseInt('08')", "x = 8"); fold("x = parseFloat('1.23')", "x = 1.23"); fold("x = parseFloat('1.2300')", "x = 1.23"); fold("x = parseFloat(' 0.3333')", "x = 0.3333"); //Mozilla Dev Center test cases fold("x = parseInt(' 0xF', 16)", "x = 15"); fold("x = parseInt(' F', 16)", "x = 15"); fold("x = parseInt('17', 8)", "x = 15"); fold("x = parseInt('015', 10)", "x = 15"); fold("x = parseInt('1111', 2)", "x = 15"); fold("x = parseInt('12', 13)", "x = 15"); fold("x = parseInt(021, 8)", "x = 15"); fold("x = parseInt(15.99, 10)", "x = 15"); fold("x = parseFloat('3.14')", "x = 3.14"); fold("x = parseFloat(3.14)", "x = 3.14"); //Valid calls - unable to fold foldSame("x = parseInt('FXX123', 16)"); foldSame("x = parseInt('15*3', 10)"); foldSame("x = parseInt('15e2', 10)"); foldSame("x = parseInt('15px', 10)"); foldSame("x = parseInt('-0x08')"); foldSame("x = parseInt('1', -1)"); foldSame("x = parseFloat('3.14more non-digit characters')"); foldSame("x = parseFloat('314e-2')"); foldSame("x = parseFloat('0.0314E+2')"); foldSame("x = parseFloat('3.333333333333333333333333')"); //Invalid calls foldSame("x = parseInt('0xa', 10)"); enableEcmaScript5(false); foldSame("x = parseInt('08')"); } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } }
public void testUselessCode() { test("function f(x) { if(x) return; }", ok); test("function f(x) { if(x); }", "function f(x) { if(x); }", e); test("if(x) x = y;", ok); test("if(x) x == bar();", "if(x) JSCOMPILER_PRESERVE(x == bar());", e); test("x = 3;", ok); test("x == 3;", "JSCOMPILER_PRESERVE(x == 3);", e); test("var x = 'test'", ok); test("var x = 'test'\n'str'", "var x = 'test'\nJSCOMPILER_PRESERVE('str')", e); test("", ok); test("foo();;;;bar();;;;", ok); test("var a, b; a = 5, b = 6", ok); test("var a, b; a = 5, b == 6", "var a, b; a = 5, JSCOMPILER_PRESERVE(b == 6)", e); test("var a, b; a = (5, 6)", "var a, b; a = (JSCOMPILER_PRESERVE(5), 6)", e); test("var a, b; a = (bar(), 6, 7)", "var a, b; a = (bar(), JSCOMPILER_PRESERVE(6), 7)", e); test("var a, b; a = (bar(), bar(), 7, 8)", "var a, b; a = (bar(), bar(), JSCOMPILER_PRESERVE(7), 8)", e); test("var a, b; a = (b = 7, 6)", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(x(), 2));", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(2, 3));", "function x(){}\nfunction f(a, b){}\n" + "f(1,(JSCOMPILER_PRESERVE(2), 3));", e); }
com.google.javascript.jscomp.CheckSideEffectsTest::testUselessCode
test/com/google/javascript/jscomp/CheckSideEffectsTest.java
79
test/com/google/javascript/jscomp/CheckSideEffectsTest.java
testUselessCode
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; public class CheckSideEffectsTest extends CompilerTestCase { public CheckSideEffectsTest() { this.parseTypeInfo = true; allowExternsChanges(true); } @Override protected int getNumRepetitions() { return 1; } @Override protected CompilerPass getProcessor(Compiler compiler) { return new CheckSideEffects(compiler, CheckLevel.WARNING, true); } @Override public void test(String js, String expected, DiagnosticType warning) { test(js, expected, null, warning); } public void test(String js, DiagnosticType warning) { test(js, js, null, warning); } final DiagnosticType e = CheckSideEffects.USELESS_CODE_ERROR; final DiagnosticType ok = null; // no warning public void testUselessCode() { test("function f(x) { if(x) return; }", ok); test("function f(x) { if(x); }", "function f(x) { if(x); }", e); test("if(x) x = y;", ok); test("if(x) x == bar();", "if(x) JSCOMPILER_PRESERVE(x == bar());", e); test("x = 3;", ok); test("x == 3;", "JSCOMPILER_PRESERVE(x == 3);", e); test("var x = 'test'", ok); test("var x = 'test'\n'str'", "var x = 'test'\nJSCOMPILER_PRESERVE('str')", e); test("", ok); test("foo();;;;bar();;;;", ok); test("var a, b; a = 5, b = 6", ok); test("var a, b; a = 5, b == 6", "var a, b; a = 5, JSCOMPILER_PRESERVE(b == 6)", e); test("var a, b; a = (5, 6)", "var a, b; a = (JSCOMPILER_PRESERVE(5), 6)", e); test("var a, b; a = (bar(), 6, 7)", "var a, b; a = (bar(), JSCOMPILER_PRESERVE(6), 7)", e); test("var a, b; a = (bar(), bar(), 7, 8)", "var a, b; a = (bar(), bar(), JSCOMPILER_PRESERVE(7), 8)", e); test("var a, b; a = (b = 7, 6)", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(x(), 2));", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(2, 3));", "function x(){}\nfunction f(a, b){}\n" + "f(1,(JSCOMPILER_PRESERVE(2), 3));", e); } public void testUselessCodeInFor() { test("for(var x = 0; x < 100; x++) { foo(x) }", ok); test("for(; true; ) { bar() }", ok); test("for(foo(); true; foo()) { bar() }", ok); test("for(void 0; true; foo()) { bar() }", "for(JSCOMPILER_PRESERVE(void 0); true; foo()) { bar() }", e); test("for(foo(); true; void 0) { bar() }", "for(foo(); true; JSCOMPILER_PRESERVE(void 0)) { bar() }", e); test("for(foo(); true; (1, bar())) { bar() }", "for(foo(); true; (JSCOMPILER_PRESERVE(1), bar())) { bar() }", e); test("for(foo in bar) { foo() }", ok); test("for (i = 0; el = el.previousSibling; i++) {}", ok); test("for (i = 0; el = el.previousSibling; i++);", ok); } public void testTypeAnnotations() { test("x;", "JSCOMPILER_PRESERVE(x);", e); test("a.b.c.d;", "JSCOMPILER_PRESERVE(a.b.c.d);", e); test("/** @type Number */ a.b.c.d;", ok); test("if (true) { /** @type Number */ a.b.c.d; }", ok); test("function A() { this.foo; }", "function A() { JSCOMPILER_PRESERVE(this.foo); }", e); test("function A() { /** @type Number */ this.foo; }", ok); } public void testJSDocComments() { test("function A() { /** This is a JsDoc comment */ this.foo; }", ok); test("function A() { /* This is a normal comment */ this.foo; }", "function A() { " + " /* This is a normal comment */ JSCOMPILER_PRESERVE(this.foo); }", e); } public void testIssue80() { test("(0, eval)('alert');", ok); test("(0, foo)('alert');", "(JSCOMPILER_PRESERVE(0), foo)('alert');", e); } public void testIsue504() { test("void f();", "JSCOMPILER_PRESERVE(void f());", null, e, "Suspicious code. The result of the 'void' operator is not being used."); } }
// You are a professional Java test case writer, please create a test case named `testUselessCode` for the issue `Closure-753`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-753 // // ## Issue-Title: // Classify non-rightmost expressions as problematic // // ## Issue-Description: // **Purpose of code changes:** // When it comes to an expression involving the comma operator, only the // first element of such a sequence is checked for being free of side // effects. If the element is free of side effects, it is classified as // problematic and a warning is issued. // // As other non-rightmost elements are not checked for being free of side // effects and therefore cannot be classified as problematic, this leads // to unexpected behavior: // // 1. foo((1, 2, 42)) is transformed into foo((1, 3)) and a warning is // issued only with regard to the first element. // 2. foo((bar(), 2, 42)) is transformed into foo((bar(), 3)) and no // warning is issued. // 3. foo(((1, 2, 3), (4, 5, 42))) is transformed into foo((1, 4, 42)) and // warnings are issued with regard to the first elements of inner // sequences only. // // public void testUselessCode() {
79
final DiagnosticType ok = null; // no warning
22
48
test/com/google/javascript/jscomp/CheckSideEffectsTest.java
test
```markdown ## Issue-ID: Closure-753 ## Issue-Title: Classify non-rightmost expressions as problematic ## Issue-Description: **Purpose of code changes:** When it comes to an expression involving the comma operator, only the first element of such a sequence is checked for being free of side effects. If the element is free of side effects, it is classified as problematic and a warning is issued. As other non-rightmost elements are not checked for being free of side effects and therefore cannot be classified as problematic, this leads to unexpected behavior: 1. foo((1, 2, 42)) is transformed into foo((1, 3)) and a warning is issued only with regard to the first element. 2. foo((bar(), 2, 42)) is transformed into foo((bar(), 3)) and no warning is issued. 3. foo(((1, 2, 3), (4, 5, 42))) is transformed into foo((1, 4, 42)) and warnings are issued with regard to the first elements of inner sequences only. ``` You are a professional Java test case writer, please create a test case named `testUselessCode` for the issue `Closure-753`, utilizing the provided issue report information and the following function signature. ```java public void testUselessCode() { ```
48
[ "com.google.javascript.jscomp.CheckSideEffects" ]
156bc91f96f5b059e61f1ca504b2a24ff02ea351f8b80c89a6a5730bef5b79bf
public void testUselessCode()
// You are a professional Java test case writer, please create a test case named `testUselessCode` for the issue `Closure-753`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-753 // // ## Issue-Title: // Classify non-rightmost expressions as problematic // // ## Issue-Description: // **Purpose of code changes:** // When it comes to an expression involving the comma operator, only the // first element of such a sequence is checked for being free of side // effects. If the element is free of side effects, it is classified as // problematic and a warning is issued. // // As other non-rightmost elements are not checked for being free of side // effects and therefore cannot be classified as problematic, this leads // to unexpected behavior: // // 1. foo((1, 2, 42)) is transformed into foo((1, 3)) and a warning is // issued only with regard to the first element. // 2. foo((bar(), 2, 42)) is transformed into foo((bar(), 3)) and no // warning is issued. // 3. foo(((1, 2, 3), (4, 5, 42))) is transformed into foo((1, 4, 42)) and // warnings are issued with regard to the first elements of inner // sequences only. // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; public class CheckSideEffectsTest extends CompilerTestCase { public CheckSideEffectsTest() { this.parseTypeInfo = true; allowExternsChanges(true); } @Override protected int getNumRepetitions() { return 1; } @Override protected CompilerPass getProcessor(Compiler compiler) { return new CheckSideEffects(compiler, CheckLevel.WARNING, true); } @Override public void test(String js, String expected, DiagnosticType warning) { test(js, expected, null, warning); } public void test(String js, DiagnosticType warning) { test(js, js, null, warning); } final DiagnosticType e = CheckSideEffects.USELESS_CODE_ERROR; final DiagnosticType ok = null; // no warning public void testUselessCode() { test("function f(x) { if(x) return; }", ok); test("function f(x) { if(x); }", "function f(x) { if(x); }", e); test("if(x) x = y;", ok); test("if(x) x == bar();", "if(x) JSCOMPILER_PRESERVE(x == bar());", e); test("x = 3;", ok); test("x == 3;", "JSCOMPILER_PRESERVE(x == 3);", e); test("var x = 'test'", ok); test("var x = 'test'\n'str'", "var x = 'test'\nJSCOMPILER_PRESERVE('str')", e); test("", ok); test("foo();;;;bar();;;;", ok); test("var a, b; a = 5, b = 6", ok); test("var a, b; a = 5, b == 6", "var a, b; a = 5, JSCOMPILER_PRESERVE(b == 6)", e); test("var a, b; a = (5, 6)", "var a, b; a = (JSCOMPILER_PRESERVE(5), 6)", e); test("var a, b; a = (bar(), 6, 7)", "var a, b; a = (bar(), JSCOMPILER_PRESERVE(6), 7)", e); test("var a, b; a = (bar(), bar(), 7, 8)", "var a, b; a = (bar(), bar(), JSCOMPILER_PRESERVE(7), 8)", e); test("var a, b; a = (b = 7, 6)", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(x(), 2));", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(2, 3));", "function x(){}\nfunction f(a, b){}\n" + "f(1,(JSCOMPILER_PRESERVE(2), 3));", e); } public void testUselessCodeInFor() { test("for(var x = 0; x < 100; x++) { foo(x) }", ok); test("for(; true; ) { bar() }", ok); test("for(foo(); true; foo()) { bar() }", ok); test("for(void 0; true; foo()) { bar() }", "for(JSCOMPILER_PRESERVE(void 0); true; foo()) { bar() }", e); test("for(foo(); true; void 0) { bar() }", "for(foo(); true; JSCOMPILER_PRESERVE(void 0)) { bar() }", e); test("for(foo(); true; (1, bar())) { bar() }", "for(foo(); true; (JSCOMPILER_PRESERVE(1), bar())) { bar() }", e); test("for(foo in bar) { foo() }", ok); test("for (i = 0; el = el.previousSibling; i++) {}", ok); test("for (i = 0; el = el.previousSibling; i++);", ok); } public void testTypeAnnotations() { test("x;", "JSCOMPILER_PRESERVE(x);", e); test("a.b.c.d;", "JSCOMPILER_PRESERVE(a.b.c.d);", e); test("/** @type Number */ a.b.c.d;", ok); test("if (true) { /** @type Number */ a.b.c.d; }", ok); test("function A() { this.foo; }", "function A() { JSCOMPILER_PRESERVE(this.foo); }", e); test("function A() { /** @type Number */ this.foo; }", ok); } public void testJSDocComments() { test("function A() { /** This is a JsDoc comment */ this.foo; }", ok); test("function A() { /* This is a normal comment */ this.foo; }", "function A() { " + " /* This is a normal comment */ JSCOMPILER_PRESERVE(this.foo); }", e); } public void testIssue80() { test("(0, eval)('alert');", ok); test("(0, foo)('alert');", "(JSCOMPILER_PRESERVE(0), foo)('alert');", e); } public void testIsue504() { test("void f();", "JSCOMPILER_PRESERVE(void f());", null, e, "Suspicious code. The result of the 'void' operator is not being used."); } }
public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); }
com.google.javascript.jscomp.TypeCheckTest::testIssue1002
test/com/google/javascript/jscomp/TypeCheckTest.java
6,752
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue1002
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar)['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testIssue1002` for the issue `Closure-1002`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1002 // // ## Issue-Title: // IllegalStateException at com.google.javascript.rhino.jstype.FunctionType.getInstanceType // // ## Issue-Description: // > What steps will reproduce the problem? // 1. Unpack attached test case. // 2. Ensure make, wget, unzip, and java are on your PATH // 3. make prep (or just set up the build manually, it's not complicated) // 4. make crash // // > What is the expected output? What do you see instead? // Expected output: either successful compilation, or a compilation error. // Actual output: // $ java \ // -jar ./compiler.jar \ // --js crash.js \ // --warning\_level=VERBOSE \ // --compilation\_level=SIMPLE\_OPTIMIZATIONS // java.lang.RuntimeException: java.lang.IllegalStateException // at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:715) // at com.google.javascript.jscomp.Compiler.compile(Compiler.java:647) // at com.google.javascript.jscomp.Compiler.compile(Compiler.java:603) // at com.google.javascript.jscomp.AbstractCommandLineRunner.doRun(AbstractCommandLineRunner.java:783) // at com.google.javascript.jscomp.AbstractCommandLineRunner.run(AbstractCommandLineRunner.java:379) // at com.google.javascript.jscomp.CommandLineRunner.main(CommandLineRunner.java:972) // Caused by: java.lang.IllegalStateException // at com.google.common.base.Preconditions.checkState(Preconditions.java:133) // at com.google.javascript.rhino.jstype.FunctionType.getInstanceType(FunctionType.java:1071) // at com.google.javascript.jscomp.TypeCheck.visitNew(TypeCheck.java:1567) // at com.google.javascript.jscomp.TypeCheck.visit(TypeCheck.java:569) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:534) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseFunction(NodeTraversal.java:569) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:522) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:353) // at com.google.javascript.jscomp.TypeCheck.check(TypeCheck.java:400) // at com.google.javascript.jscomp.TypeCheck.process(TypeCheck.java:371) // at com.google.javascript.jscomp.DefaultPassConfig$30$1.process(DefaultPassConfig.java:1237 public void testIssue1002() throws Exception {
6,752
125
6,739
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-1002 ## Issue-Title: IllegalStateException at com.google.javascript.rhino.jstype.FunctionType.getInstanceType ## Issue-Description: > What steps will reproduce the problem? 1. Unpack attached test case. 2. Ensure make, wget, unzip, and java are on your PATH 3. make prep (or just set up the build manually, it's not complicated) 4. make crash > What is the expected output? What do you see instead? Expected output: either successful compilation, or a compilation error. Actual output: $ java \ -jar ./compiler.jar \ --js crash.js \ --warning\_level=VERBOSE \ --compilation\_level=SIMPLE\_OPTIMIZATIONS java.lang.RuntimeException: java.lang.IllegalStateException at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:715) at com.google.javascript.jscomp.Compiler.compile(Compiler.java:647) at com.google.javascript.jscomp.Compiler.compile(Compiler.java:603) at com.google.javascript.jscomp.AbstractCommandLineRunner.doRun(AbstractCommandLineRunner.java:783) at com.google.javascript.jscomp.AbstractCommandLineRunner.run(AbstractCommandLineRunner.java:379) at com.google.javascript.jscomp.CommandLineRunner.main(CommandLineRunner.java:972) Caused by: java.lang.IllegalStateException at com.google.common.base.Preconditions.checkState(Preconditions.java:133) at com.google.javascript.rhino.jstype.FunctionType.getInstanceType(FunctionType.java:1071) at com.google.javascript.jscomp.TypeCheck.visitNew(TypeCheck.java:1567) at com.google.javascript.jscomp.TypeCheck.visit(TypeCheck.java:569) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:534) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseFunction(NodeTraversal.java:569) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:522) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:353) at com.google.javascript.jscomp.TypeCheck.check(TypeCheck.java:400) at com.google.javascript.jscomp.TypeCheck.process(TypeCheck.java:371) at com.google.javascript.jscomp.DefaultPassConfig$30$1.process(DefaultPassConfig.java:1237 ``` You are a professional Java test case writer, please create a test case named `testIssue1002` for the issue `Closure-1002`, utilizing the provided issue report information and the following function signature. ```java public void testIssue1002() throws Exception { ```
6,739
[ "com.google.javascript.jscomp.TypeCheck" ]
158898ff6d956c43d2753fa96973ca0399173d14b4d4e9e760530c998ce20a28
public void testIssue1002() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue1002` for the issue `Closure-1002`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1002 // // ## Issue-Title: // IllegalStateException at com.google.javascript.rhino.jstype.FunctionType.getInstanceType // // ## Issue-Description: // > What steps will reproduce the problem? // 1. Unpack attached test case. // 2. Ensure make, wget, unzip, and java are on your PATH // 3. make prep (or just set up the build manually, it's not complicated) // 4. make crash // // > What is the expected output? What do you see instead? // Expected output: either successful compilation, or a compilation error. // Actual output: // $ java \ // -jar ./compiler.jar \ // --js crash.js \ // --warning\_level=VERBOSE \ // --compilation\_level=SIMPLE\_OPTIMIZATIONS // java.lang.RuntimeException: java.lang.IllegalStateException // at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:715) // at com.google.javascript.jscomp.Compiler.compile(Compiler.java:647) // at com.google.javascript.jscomp.Compiler.compile(Compiler.java:603) // at com.google.javascript.jscomp.AbstractCommandLineRunner.doRun(AbstractCommandLineRunner.java:783) // at com.google.javascript.jscomp.AbstractCommandLineRunner.run(AbstractCommandLineRunner.java:379) // at com.google.javascript.jscomp.CommandLineRunner.main(CommandLineRunner.java:972) // Caused by: java.lang.IllegalStateException // at com.google.common.base.Preconditions.checkState(Preconditions.java:133) // at com.google.javascript.rhino.jstype.FunctionType.getInstanceType(FunctionType.java:1071) // at com.google.javascript.jscomp.TypeCheck.visitNew(TypeCheck.java:1567) // at com.google.javascript.jscomp.TypeCheck.visit(TypeCheck.java:569) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:534) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseFunction(NodeTraversal.java:569) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:522) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:528) // at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:353) // at com.google.javascript.jscomp.TypeCheck.check(TypeCheck.java:400) // at com.google.javascript.jscomp.TypeCheck.process(TypeCheck.java:371) // at com.google.javascript.jscomp.DefaultPassConfig$30$1.process(DefaultPassConfig.java:1237
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar)['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
public void testCopyWith() throws Exception { XmlMapper xmlMapper = newMapper(); final ObjectMapper xmlMapperNoAnno = xmlMapper.copy() .disable(MapperFeature.USE_ANNOTATIONS) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); String xml1 = xmlMapper.writeValueAsString(new Pojo282()); String xml2 = xmlMapperNoAnno.writeValueAsString(new Pojo282()); if (!xml1.contains("AnnotatedName")) { fail("Should use name 'AnnotatedName', xml = "+xml1); } if (!xml2.contains("Pojo282") || xml2.contains("AnnotatedName")) { fail("Should NOT use name 'AnnotatedName' but 'Pojo282', xml = "+xml1); } }
com.fasterxml.jackson.dataformat.xml.MapperCopyTest::testCopyWith
src/test/java/com/fasterxml/jackson/dataformat/xml/MapperCopyTest.java
90
src/test/java/com/fasterxml/jackson/dataformat/xml/MapperCopyTest.java
testCopyWith
package com.fasterxml.jackson.dataformat.xml; import java.io.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; import com.fasterxml.jackson.dataformat.xml.ser.XmlSerializerProvider; import com.fasterxml.jackson.dataformat.xml.util.XmlRootNameLookup; public class MapperCopyTest extends XmlTestBase { @JacksonXmlRootElement(localName = "AnnotatedName") static class Pojo282 { public int a = 3; } public void testMapperCopy() { XmlMapper mapper1 = new XmlMapper(); mapper1.setXMLTextElementName("foo"); mapper1.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); mapper1.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); XmlMapper mapper2 = mapper1.copy(); assertNotSame(mapper1, mapper2); XmlFactory xf1 = mapper1.getFactory(); XmlFactory xf2 = mapper2.getFactory(); assertNotSame(xf1, xf2); assertEquals(XmlFactory.class, xf2.getClass()); // and incomplete copy as well assertEquals(xf1.getXMLTextElementName(), xf2.getXMLTextElementName()); assertEquals(xf1._xmlGeneratorFeatures, xf2._xmlGeneratorFeatures); assertEquals(xf1._xmlParserFeatures, xf2._xmlParserFeatures); SerializationConfig sc1 = mapper1.getSerializationConfig(); SerializationConfig sc2 = mapper2.getSerializationConfig(); assertNotSame(sc1, sc2); assertEquals( "serialization features did not get copied", sc1.getSerializationFeatures(), sc2.getSerializationFeatures() ); } public void testSerializerProviderCopy() { DefaultSerializerProvider provider = new XmlSerializerProvider(new XmlRootNameLookup()); DefaultSerializerProvider copy = provider.copy(); assertNotSame(provider, copy); } public void testMapperSerialization() throws Exception { XmlMapper mapper1 = newMapper(); mapper1.setXMLTextElementName("foo"); assertEquals("foo", mapper1.getFactory().getXMLTextElementName()); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream objectStream = new ObjectOutputStream(bytes); objectStream.writeObject(mapper1); objectStream.close(); ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())); XmlMapper mapper2 = (XmlMapper) input.readObject(); input.close(); assertEquals("foo", mapper2.getFactory().getXMLTextElementName()); } // [dataformat-xml#282] public void testCopyWith() throws Exception { XmlMapper xmlMapper = newMapper(); final ObjectMapper xmlMapperNoAnno = xmlMapper.copy() .disable(MapperFeature.USE_ANNOTATIONS) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); String xml1 = xmlMapper.writeValueAsString(new Pojo282()); String xml2 = xmlMapperNoAnno.writeValueAsString(new Pojo282()); if (!xml1.contains("AnnotatedName")) { fail("Should use name 'AnnotatedName', xml = "+xml1); } if (!xml2.contains("Pojo282") || xml2.contains("AnnotatedName")) { fail("Should NOT use name 'AnnotatedName' but 'Pojo282', xml = "+xml1); } } }
// You are a professional Java test case writer, please create a test case named `testCopyWith` for the issue `JacksonXml-282`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonXml-282 // // ## Issue-Title: // @JacksonXmlRootElement malfunction when using it with multiple XmlMappers and disabling annotations // // ## Issue-Description: // Found this in version 2.9.4 running some tests that go back and forth serializing with an XML mapper that uses annotations, and another one that ignores them. May be related to issue [#171](https://github.com/FasterXML/jackson-dataformat-xml/issues/171) and the cache of class annotations. // // // When running this code, the second print statement should use the annotation's localName but it instead uses the class name. // // // // ``` // @JacksonXmlRootElement(localName = "myname") // public class XMLTest { // // public static void main(String[] s) throws Exception { // // final ObjectMapper xmlMapper = new XmlMapper(); // final ObjectMapper noAnnotationsXmlMapper = xmlMapper.copy() // .configure(MapperFeature.USE_ANNOTATIONS, false) // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // // System.out.println(noAnnotationsXmlMapper.writeValueAsString(new XMLTest())); // System.out.println(xmlMapper.writeValueAsString(new XMLTest())); // // } // // } // // ``` // // Output: // // // // ``` // <XMLTest/> // <XMLTest/> // // ``` // // // public void testCopyWith() throws Exception {
90
// [dataformat-xml#282]
5
73
src/test/java/com/fasterxml/jackson/dataformat/xml/MapperCopyTest.java
src/test/java
```markdown ## Issue-ID: JacksonXml-282 ## Issue-Title: @JacksonXmlRootElement malfunction when using it with multiple XmlMappers and disabling annotations ## Issue-Description: Found this in version 2.9.4 running some tests that go back and forth serializing with an XML mapper that uses annotations, and another one that ignores them. May be related to issue [#171](https://github.com/FasterXML/jackson-dataformat-xml/issues/171) and the cache of class annotations. When running this code, the second print statement should use the annotation's localName but it instead uses the class name. ``` @JacksonXmlRootElement(localName = "myname") public class XMLTest { public static void main(String[] s) throws Exception { final ObjectMapper xmlMapper = new XmlMapper(); final ObjectMapper noAnnotationsXmlMapper = xmlMapper.copy() .configure(MapperFeature.USE_ANNOTATIONS, false) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); System.out.println(noAnnotationsXmlMapper.writeValueAsString(new XMLTest())); System.out.println(xmlMapper.writeValueAsString(new XMLTest())); } } ``` Output: ``` <XMLTest/> <XMLTest/> ``` ``` You are a professional Java test case writer, please create a test case named `testCopyWith` for the issue `JacksonXml-282`, utilizing the provided issue report information and the following function signature. ```java public void testCopyWith() throws Exception { ```
73
[ "com.fasterxml.jackson.dataformat.xml.ser.XmlSerializerProvider" ]
159cf5e1205d28f2d81d0975c400bc4178e2bcc775e289e0e111d588d15d5a94
public void testCopyWith() throws Exception
// You are a professional Java test case writer, please create a test case named `testCopyWith` for the issue `JacksonXml-282`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonXml-282 // // ## Issue-Title: // @JacksonXmlRootElement malfunction when using it with multiple XmlMappers and disabling annotations // // ## Issue-Description: // Found this in version 2.9.4 running some tests that go back and forth serializing with an XML mapper that uses annotations, and another one that ignores them. May be related to issue [#171](https://github.com/FasterXML/jackson-dataformat-xml/issues/171) and the cache of class annotations. // // // When running this code, the second print statement should use the annotation's localName but it instead uses the class name. // // // // ``` // @JacksonXmlRootElement(localName = "myname") // public class XMLTest { // // public static void main(String[] s) throws Exception { // // final ObjectMapper xmlMapper = new XmlMapper(); // final ObjectMapper noAnnotationsXmlMapper = xmlMapper.copy() // .configure(MapperFeature.USE_ANNOTATIONS, false) // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // // System.out.println(noAnnotationsXmlMapper.writeValueAsString(new XMLTest())); // System.out.println(xmlMapper.writeValueAsString(new XMLTest())); // // } // // } // // ``` // // Output: // // // // ``` // <XMLTest/> // <XMLTest/> // // ``` // // //
JacksonXml
package com.fasterxml.jackson.dataformat.xml; import java.io.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; import com.fasterxml.jackson.dataformat.xml.ser.XmlSerializerProvider; import com.fasterxml.jackson.dataformat.xml.util.XmlRootNameLookup; public class MapperCopyTest extends XmlTestBase { @JacksonXmlRootElement(localName = "AnnotatedName") static class Pojo282 { public int a = 3; } public void testMapperCopy() { XmlMapper mapper1 = new XmlMapper(); mapper1.setXMLTextElementName("foo"); mapper1.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); mapper1.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); XmlMapper mapper2 = mapper1.copy(); assertNotSame(mapper1, mapper2); XmlFactory xf1 = mapper1.getFactory(); XmlFactory xf2 = mapper2.getFactory(); assertNotSame(xf1, xf2); assertEquals(XmlFactory.class, xf2.getClass()); // and incomplete copy as well assertEquals(xf1.getXMLTextElementName(), xf2.getXMLTextElementName()); assertEquals(xf1._xmlGeneratorFeatures, xf2._xmlGeneratorFeatures); assertEquals(xf1._xmlParserFeatures, xf2._xmlParserFeatures); SerializationConfig sc1 = mapper1.getSerializationConfig(); SerializationConfig sc2 = mapper2.getSerializationConfig(); assertNotSame(sc1, sc2); assertEquals( "serialization features did not get copied", sc1.getSerializationFeatures(), sc2.getSerializationFeatures() ); } public void testSerializerProviderCopy() { DefaultSerializerProvider provider = new XmlSerializerProvider(new XmlRootNameLookup()); DefaultSerializerProvider copy = provider.copy(); assertNotSame(provider, copy); } public void testMapperSerialization() throws Exception { XmlMapper mapper1 = newMapper(); mapper1.setXMLTextElementName("foo"); assertEquals("foo", mapper1.getFactory().getXMLTextElementName()); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream objectStream = new ObjectOutputStream(bytes); objectStream.writeObject(mapper1); objectStream.close(); ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())); XmlMapper mapper2 = (XmlMapper) input.readObject(); input.close(); assertEquals("foo", mapper2.getFactory().getXMLTextElementName()); } // [dataformat-xml#282] public void testCopyWith() throws Exception { XmlMapper xmlMapper = newMapper(); final ObjectMapper xmlMapperNoAnno = xmlMapper.copy() .disable(MapperFeature.USE_ANNOTATIONS) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); String xml1 = xmlMapper.writeValueAsString(new Pojo282()); String xml2 = xmlMapperNoAnno.writeValueAsString(new Pojo282()); if (!xml1.contains("AnnotatedName")) { fail("Should use name 'AnnotatedName', xml = "+xml1); } if (!xml2.contains("Pojo282") || xml2.contains("AnnotatedName")) { fail("Should NOT use name 'AnnotatedName' but 'Pojo282', xml = "+xml1); } } }
public void testIssue942() { assertPrint("var x = {0: 1};", "var x={0:1}"); }
com.google.javascript.jscomp.CodePrinterTest::testIssue942
test/com/google/javascript/jscomp/CodePrinterTest.java
1,423
test/com/google/javascript/jscomp/CodePrinterTest.java
testIssue942
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; import java.util.List; public class CodePrinterTest extends TestCase { private boolean trustedStrings = true; private Compiler lastCompiler = null; @Override public void setUp() { trustedStrings = true; lastCompiler = null; } Node parse(String js) { return parse(js, false); } Node parse(String js, boolean checkTypes) { Compiler compiler = new Compiler(); lastCompiler = compiler; CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); // Allow getters and setters. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.initOptions(options); Node n = compiler.parseTestCode(js); if (checkTypes) { DefaultPassConfig passConfig = new DefaultPassConfig(null); CompilerPass typeResolver = passConfig.resolveTypes.create(compiler); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); typeResolver.process(externs, n); CompilerPass inferTypes = passConfig.inferTypes.create(compiler); inferTypes.process(externs, n); } checkUnexpectedErrorsOrWarnings(compiler, 0); return n; } private static void checkUnexpectedErrorsOrWarnings( Compiler compiler, int expected) { int actual = compiler.getErrors().length + compiler.getWarnings().length; if (actual != expected) { String msg = ""; for (JSError err : compiler.getErrors()) { msg += "Error:" + err.toString() + "\n"; } for (JSError err : compiler.getWarnings()) { msg += "Warning:" + err.toString() + "\n"; } assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual); } } String parsePrint(String js, boolean prettyprint, int lineThreshold) { CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); return new CodePrinter.Builder(parse(js)).setCompilerOptions(options) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold) { CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); options.setLineBreak(lineBreak); return new CodePrinter.Builder(parse(js)).setCompilerOptions(options) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, boolean preferLineBreakAtEof, int lineThreshold) { CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); options.setPreferLineBreakAtEndOfFile(preferLineBreakAtEof); options.setLineBreak(lineBreak); return new CodePrinter.Builder(parse(js)).setCompilerOptions(options) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes) { Node node = parse(js, true); CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); options.setLineBreak(lineBreak); return new CodePrinter.Builder(node).setCompilerOptions(options) .setOutputTypes(outputTypes) .setTypeRegistry(lastCompiler.getTypeRegistry()) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes, boolean tagAsStrict) { Node node = parse(js, true); CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); options.setLineBreak(lineBreak); return new CodePrinter.Builder(node).setCompilerOptions(options) .setOutputTypes(outputTypes) .setTypeRegistry(lastCompiler.getTypeRegistry()) .setTagAsStrict(tagAsStrict) .build(); } String printNode(Node n) { CompilerOptions options = new CompilerOptions(); options.setLineLengthThreshold(CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD); return new CodePrinter.Builder(n).setCompilerOptions(options).build(); } void assertPrintNode(String expectedJs, Node ast) { assertEquals(expectedJs, printNode(ast)); } public void testPrint() { assertPrint("10 + a + b", "10+a+b"); assertPrint("10 + (30*50)", "10+30*50"); assertPrint("with(x) { x + 3; }", "with(x)x+3"); assertPrint("\"aa'a\"", "\"aa'a\""); assertPrint("\"aa\\\"a\"", "'aa\"a'"); assertPrint("function foo()\n{return 10;}", "function foo(){return 10}"); assertPrint("a instanceof b", "a instanceof b"); assertPrint("typeof(a)", "typeof a"); assertPrint( "var foo = x ? { a : 1 } : {a: 3, b:4, \"default\": 5, \"foo-bar\": 6}", "var foo=x?{a:1}:{a:3,b:4,\"default\":5,\"foo-bar\":6}"); // Safari: needs ';' at the end of a throw statement assertPrint("function foo(){throw 'error';}", "function foo(){throw\"error\";}"); // Safari 3 needs a "{" around a single function assertPrint("if (true) function foo(){return}", "if(true){function foo(){return}}"); assertPrint("var x = 10; { var y = 20; }", "var x=10;var y=20"); assertPrint("while (x-- > 0);", "while(x-- >0);"); assertPrint("x-- >> 1", "x-- >>1"); assertPrint("(function () {})(); ", "(function(){})()"); // Associativity assertPrint("var a,b,c,d;a || (b&& c) && (a || d)", "var a,b,c,d;a||b&&c&&(a||d)"); assertPrint("var a,b,c; a || (b || c); a * (b * c); a | (b | c)", "var a,b,c;a||b||c;a*b*c;a|b|c"); assertPrint("var a,b,c; a / b / c;a / (b / c); a - (b - c);", "var a,b,c;a/b/c;a/(b/c);a-(b-c)"); assertPrint("var a,b; a = b = 3;", "var a,b;a=b=3"); assertPrint("var a,b,c,d; a = (b = c = (d = 3));", "var a,b,c,d;a=b=c=d=3"); assertPrint("var a,b,c; a += (b = c += 3);", "var a,b,c;a+=b=c+=3"); assertPrint("var a,b,c; a *= (b -= c);", "var a,b,c;a*=b-=c"); // Precedence assertPrint("a ? delete b[0] : 3", "a?delete b[0]:3"); assertPrint("(delete a[0])/10", "delete a[0]/10"); // optional '()' for new // simple new assertPrint("new A", "new A"); assertPrint("new A()", "new A"); assertPrint("new A('x')", "new A(\"x\")"); // calling instance method directly after new assertPrint("new A().a()", "(new A).a()"); assertPrint("(new A).a()", "(new A).a()"); // this case should be fixed assertPrint("new A('y').a()", "(new A(\"y\")).a()"); // internal class assertPrint("new A.B", "new A.B"); assertPrint("new A.B()", "new A.B"); assertPrint("new A.B('z')", "new A.B(\"z\")"); // calling instance method directly after new internal class assertPrint("(new A.B).a()", "(new A.B).a()"); assertPrint("new A.B().a()", "(new A.B).a()"); // this case should be fixed assertPrint("new A.B('w').a()", "(new A.B(\"w\")).a()"); // Operators: make sure we don't convert binary + and unary + into ++ assertPrint("x + +y", "x+ +y"); assertPrint("x - (-y)", "x- -y"); assertPrint("x++ +y", "x++ +y"); assertPrint("x-- -y", "x-- -y"); assertPrint("x++ -y", "x++-y"); // Label assertPrint("foo:for(;;){break foo;}", "foo:for(;;)break foo"); assertPrint("foo:while(1){continue foo;}", "foo:while(1)continue foo"); // Object literals. assertPrint("({})", "({})"); assertPrint("var x = {};", "var x={}"); assertPrint("({}).x", "({}).x"); assertPrint("({})['x']", "({})[\"x\"]"); assertPrint("({}) instanceof Object", "({})instanceof Object"); assertPrint("({}) || 1", "({})||1"); assertPrint("1 || ({})", "1||{}"); assertPrint("({}) ? 1 : 2", "({})?1:2"); assertPrint("0 ? ({}) : 2", "0?{}:2"); assertPrint("0 ? 1 : ({})", "0?1:{}"); assertPrint("typeof ({})", "typeof{}"); assertPrint("f({})", "f({})"); // Anonymous function expressions. assertPrint("(function(){})", "(function(){})"); assertPrint("(function(){})()", "(function(){})()"); assertPrint("(function(){})instanceof Object", "(function(){})instanceof Object"); assertPrint("(function(){}).bind().call()", "(function(){}).bind().call()"); assertPrint("var x = function() { };", "var x=function(){}"); assertPrint("var x = function() { }();", "var x=function(){}()"); assertPrint("(function() {}), 2", "(function(){}),2"); // Name functions expression. assertPrint("(function f(){})", "(function f(){})"); // Function declaration. assertPrint("function f(){}", "function f(){}"); // Make sure we don't treat non-Latin character escapes as raw strings. assertPrint("({ 'a': 4, '\\u0100': 4 })", "({\"a\":4,\"\\u0100\":4})"); assertPrint("({ a: 4, '\\u0100': 4 })", "({a:4,\"\\u0100\":4})"); // Test if statement and for statements with single statements in body. assertPrint("if (true) { alert();}", "if(true)alert()"); assertPrint("if (false) {} else {alert(\"a\");}", "if(false);else alert(\"a\")"); assertPrint("for(;;) { alert();};", "for(;;)alert()"); assertPrint("do { alert(); } while(true);", "do alert();while(true)"); assertPrint("myLabel: { alert();}", "myLabel:alert()"); assertPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;)continue myLabel"); // Test nested var statement assertPrint("if (true) var x; x = 4;", "if(true)var x;x=4"); // Non-latin identifier. Make sure we keep them escaped. assertPrint("\\u00fb", "\\u00fb"); assertPrint("\\u00fa=1", "\\u00fa=1"); assertPrint("function \\u00f9(){}", "function \\u00f9(){}"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("abc\\u4e00\\u4e01jkl", "abc\\u4e00\\u4e01jkl"); // Test the right-associative unary operators for spurious parens assertPrint("! ! true", "!!true"); assertPrint("!(!(true))", "!!true"); assertPrint("typeof(void(0))", "typeof void 0"); assertPrint("typeof(void(!0))", "typeof void!0"); assertPrint("+ - + + - + 3", "+-+ +-+3"); // chained unary plus/minus assertPrint("+(--x)", "+--x"); assertPrint("-(++x)", "-++x"); // needs a space to prevent an ambiguous parse assertPrint("-(--x)", "- --x"); assertPrint("!(~~5)", "!~~5"); assertPrint("~(a/b)", "~(a/b)"); // Preserve parens to overcome greedy binding of NEW assertPrint("new (foo.bar()).factory(baz)", "new (foo.bar().factory)(baz)"); assertPrint("new (bar()).factory(baz)", "new (bar().factory)(baz)"); assertPrint("new (new foobar(x)).factory(baz)", "new (new foobar(x)).factory(baz)"); // Make sure that HOOK is right associative assertPrint("a ? b : (c ? d : e)", "a?b:c?d:e"); assertPrint("a ? (b ? c : d) : e", "a?b?c:d:e"); assertPrint("(a ? b : c) ? d : e", "(a?b:c)?d:e"); // Test nested ifs assertPrint("if (x) if (y); else;", "if(x)if(y);else;"); // Test comma. assertPrint("a,b,c", "a,b,c"); assertPrint("(a,b),c", "a,b,c"); assertPrint("a,(b,c)", "a,b,c"); assertPrint("x=a,b,c", "x=a,b,c"); assertPrint("x=(a,b),c", "x=(a,b),c"); assertPrint("x=a,(b,c)", "x=a,b,c"); assertPrint("x=a,y=b,z=c", "x=a,y=b,z=c"); assertPrint("x=(a,y=b,z=c)", "x=(a,y=b,z=c)"); assertPrint("x=[a,b,c,d]", "x=[a,b,c,d]"); assertPrint("x=[(a,b,c),d]", "x=[(a,b,c),d]"); assertPrint("x=[(a,(b,c)),d]", "x=[(a,b,c),d]"); assertPrint("x=[a,(b,c,d)]", "x=[a,(b,c,d)]"); assertPrint("var x=(a,b)", "var x=(a,b)"); assertPrint("var x=a,b,c", "var x=a,b,c"); assertPrint("var x=(a,b),c", "var x=(a,b),c"); assertPrint("var x=a,b=(c,d)", "var x=a,b=(c,d)"); assertPrint("foo(a,b,c,d)", "foo(a,b,c,d)"); assertPrint("foo((a,b,c),d)", "foo((a,b,c),d)"); assertPrint("foo((a,(b,c)),d)", "foo((a,b,c),d)"); assertPrint("f(a+b,(c,d,(e,f,g)))", "f(a+b,(c,d,e,f,g))"); assertPrint("({}) , 1 , 2", "({}),1,2"); assertPrint("({}) , {} , {}", "({}),{},{}"); // EMPTY nodes assertPrint("if (x){}", "if(x);"); assertPrint("if(x);", "if(x);"); assertPrint("if(x)if(y);", "if(x)if(y);"); assertPrint("if(x){if(y);}", "if(x)if(y);"); assertPrint("if(x){if(y){};;;}", "if(x)if(y);"); assertPrint("if(x){;;function y(){};;}", "if(x){function y(){}}"); } public void testBreakTrustedStrings() { // Break scripts assertPrint("'<script>'", "\"<script>\""); assertPrint("'</script>'", "\"\\x3c/script>\""); assertPrint("\"</script> </SCRIPT>\"", "\"\\x3c/script> \\x3c/SCRIPT>\""); assertPrint("'-->'", "\"--\\x3e\""); assertPrint("']]>'", "\"]]\\x3e\""); assertPrint("' --></script>'", "\" --\\x3e\\x3c/script>\""); assertPrint("/--> <\\/script>/g", "/--\\x3e <\\/script>/g"); // Break HTML start comments. Certain versions of WebKit // begin an HTML comment when they see this. assertPrint("'<!-- I am a string -->'", "\"\\x3c!-- I am a string --\\x3e\""); assertPrint("'<=&>'", "\"<=&>\""); } public void testBreakUntrustedStrings() { trustedStrings = false; // Break scripts assertPrint("'<script>'", "\"\\x3cscript\\x3e\""); assertPrint("'</script>'", "\"\\x3c/script\\x3e\""); assertPrint("\"</script> </SCRIPT>\"", "\"\\x3c/script\\x3e \\x3c/SCRIPT\\x3e\""); assertPrint("'-->'", "\"--\\x3e\""); assertPrint("']]>'", "\"]]\\x3e\""); assertPrint("' --></script>'", "\" --\\x3e\\x3c/script\\x3e\""); assertPrint("/--> <\\/script>/g", "/--\\x3e <\\/script>/g"); // Break HTML start comments. Certain versions of WebKit // begin an HTML comment when they see this. assertPrint("'<!-- I am a string -->'", "\"\\x3c!-- I am a string --\\x3e\""); assertPrint("'<=&>'", "\"\\x3c\\x3d\\x26\\x3e\""); assertPrint("/(?=x)/", "/(?=x)/"); } public void testPrintArray() { assertPrint("[void 0, void 0]", "[void 0,void 0]"); assertPrint("[undefined, undefined]", "[undefined,undefined]"); assertPrint("[ , , , undefined]", "[,,,undefined]"); assertPrint("[ , , , 0]", "[,,,0]"); } public void testHook() { assertPrint("a ? b = 1 : c = 2", "a?b=1:c=2"); assertPrint("x = a ? b = 1 : c = 2", "x=a?b=1:c=2"); assertPrint("(x = a) ? b = 1 : c = 2", "(x=a)?b=1:c=2"); assertPrint("x, a ? b = 1 : c = 2", "x,a?b=1:c=2"); assertPrint("x, (a ? b = 1 : c = 2)", "x,a?b=1:c=2"); assertPrint("(x, a) ? b = 1 : c = 2", "(x,a)?b=1:c=2"); assertPrint("a ? (x, b) : c = 2", "a?(x,b):c=2"); assertPrint("a ? b = 1 : (x,c)", "a?b=1:(x,c)"); assertPrint("a ? b = 1 : c = 2 + x", "a?b=1:c=2+x"); assertPrint("(a ? b = 1 : c = 2) + x", "(a?b=1:c=2)+x"); assertPrint("a ? b = 1 : (c = 2) + x", "a?b=1:(c=2)+x"); assertPrint("a ? (b?1:2) : 3", "a?b?1:2:3"); } public void testPrintInOperatorInForLoop() { // Check for in expression in for's init expression. // Check alone, with + (higher precedence), with ?: (lower precedence), // and with conditional. assertPrint("var a={}; for (var i = (\"length\" in a); i;) {}", "var a={};for(var i=(\"length\"in a);i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) ? 0 : 1; i;) {}", "var a={};for(var i=(\"length\"in a)?0:1;i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) + 1; i;) {}", "var a={};for(var i=(\"length\"in a)+1;i;);"); assertPrint("var a={};for (var i = (\"length\" in a|| \"size\" in a);;);", "var a={};for(var i=(\"length\"in a)||(\"size\"in a);;);"); assertPrint("var a={};for (var i = a || a || (\"size\" in a);;);", "var a={};for(var i=a||a||(\"size\"in a);;);"); // Test works with unary operators and calls. assertPrint("var a={}; for (var i = -(\"length\" in a); i;) {}", "var a={};for(var i=-(\"length\"in a);i;);"); assertPrint("var a={};function b_(p){ return p;};" + "for(var i=1,j=b_(\"length\" in a);;) {}", "var a={};function b_(p){return p}" + "for(var i=1,j=b_(\"length\"in a);;);"); // Test we correctly handle an in operator in the test clause. assertPrint("var a={}; for (;(\"length\" in a);) {}", "var a={};for(;\"length\"in a;);"); } public void testLiteralProperty() { assertPrint("(64).toString()", "(64).toString()"); } private void assertPrint(String js, String expected) { parse(expected); // validate the expected string is valid JS assertEquals(expected, parsePrint(js, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } private void assertPrintSame(String js) { assertPrint(js, js); } // Make sure that the code generator doesn't associate an // else clause with the wrong if clause. public void testAmbiguousElseClauses() { assertPrintNode("if(x)if(y);else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), // ELSE clause for the inner if new Node(Token.BLOCK))))); assertPrintNode("if(x){if(y);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK))), // ELSE clause for the outer if new Node(Token.BLOCK))); assertPrintNode("if(x)if(y);else{if(z);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "z"), new Node(Token.BLOCK))))), // ELSE clause for the outermost if new Node(Token.BLOCK))); } public void testLineBreak() { // line break after function if in a statement context assertLineBreak("function a() {}\n" + "function b() {}", "function a(){}\n" + "function b(){}\n"); // line break after ; after a function assertLineBreak("var a = {};\n" + "a.foo = function () {}\n" + "function b() {}", "var a={};a.foo=function(){};\n" + "function b(){}\n"); // break after comma after a function assertLineBreak("var a = {\n" + " b: function() {},\n" + " c: function() {}\n" + "};\n" + "alert(a);", "var a={b:function(){},\n" + "c:function(){}};\n" + "alert(a)"); } private void assertLineBreak(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } public void testPreferLineBreakAtEndOfFile() { // short final line, no previous break, do nothing assertLineBreakAtEndOfFile( "\"1234567890\";", "\"1234567890\"", "\"1234567890\""); // short final line, shift previous break to end assertLineBreakAtEndOfFile( "\"123456789012345678901234567890\";\"1234567890\"", "\"123456789012345678901234567890\";\n\"1234567890\"", "\"123456789012345678901234567890\"; \"1234567890\";\n"); assertLineBreakAtEndOfFile( "var12345678901234567890123456 instanceof Object;", "var12345678901234567890123456 instanceof\nObject", "var12345678901234567890123456 instanceof Object;\n"); // long final line, no previous break, add a break at end assertLineBreakAtEndOfFile( "\"1234567890\";\"12345678901234567890\";", "\"1234567890\";\"12345678901234567890\"", "\"1234567890\";\"12345678901234567890\";\n"); // long final line, previous break, add a break at end assertLineBreakAtEndOfFile( "\"123456789012345678901234567890\";\"12345678901234567890\";", "\"123456789012345678901234567890\";\n\"12345678901234567890\"", "\"123456789012345678901234567890\";\n\"12345678901234567890\";\n"); } private void assertLineBreakAtEndOfFile(String js, String expectedWithoutBreakAtEnd, String expectedWithBreakAtEnd) { assertEquals(expectedWithoutBreakAtEnd, parsePrint(js, false, false, false, 30)); assertEquals(expectedWithBreakAtEnd, parsePrint(js, false, false, true, 30)); } public void testPrettyPrinter() { // Ensure that the pretty printer inserts line breaks at appropriate // places. assertPrettyPrint("(function(){})();","(function() {\n})();\n"); assertPrettyPrint("var a = (function() {});alert(a);", "var a = function() {\n};\nalert(a);\n"); // Check we correctly handle putting brackets around all if clauses so // we can put breakpoints inside statements. assertPrettyPrint("if (1) {}", "if(1) {\n" + "}\n"); assertPrettyPrint("if (1) {alert(\"\");}", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1)alert(\"\");", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1) {alert();alert();}", "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); // Don't add blocks if they weren't there already. assertPrettyPrint("label: alert();", "label:alert();\n"); // But if statements and loops get blocks automagically. assertPrettyPrint("if (1) alert();", "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for (;;) alert();", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("while (1) alert();", "while(1) {\n" + " alert()\n" + "}\n"); // Do we put else clauses in blocks? assertPrettyPrint("if (1) {} else {alert(a);}", "if(1) {\n" + "}else {\n alert(a)\n}\n"); // Do we add blocks to else clauses? assertPrettyPrint("if (1) alert(a); else alert(b);", "if(1) {\n" + " alert(a)\n" + "}else {\n" + " alert(b)\n" + "}\n"); // Do we put for bodies in blocks? assertPrettyPrint("for(;;) { alert();}", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for(;;) {}", "for(;;) {\n" + "}\n"); assertPrettyPrint("for(;;) { alert(); alert(); }", "for(;;) {\n" + " alert();\n" + " alert()\n" + "}\n"); // How about do loops? assertPrettyPrint("do { alert(); } while(true);", "do {\n" + " alert()\n" + "}while(true);\n"); // label? assertPrettyPrint("myLabel: { alert();}", "myLabel: {\n" + " alert()\n" + "}\n"); // Don't move the label on a loop, because then break {label} and // continue {label} won't work. assertPrettyPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;) {\n" + " continue myLabel\n" + "}\n"); assertPrettyPrint("var a;", "var a;\n"); } public void testPrettyPrinter2() { assertPrettyPrint( "if(true) f();", "if(true) {\n" + " f()\n" + "}\n"); assertPrettyPrint( "if (true) { f() } else { g() }", "if(true) {\n" + " f()\n" + "}else {\n" + " g()\n" + "}\n"); assertPrettyPrint( "if(true) f(); for(;;) g();", "if(true) {\n" + " f()\n" + "}\n" + "for(;;) {\n" + " g()\n" + "}\n"); } public void testPrettyPrinter3() { assertPrettyPrint( "try {} catch(e) {}if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} finally {}if (1) {alert();alert();}", "try {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} catch(e) {} finally {} if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); } public void testPrettyPrinter4() { assertPrettyPrint( "function f() {}if (1) {alert();}", "function f() {\n" + "}\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "var f = function() {};if (1) {alert();}", "var f = function() {\n" + "};\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {})();if (1) {alert();}", "(function() {\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {alert();alert();})();if (1) {alert();}", "(function() {\n" + " alert();\n" + " alert()\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); } public void testTypeAnnotations() { assertTypeAnnotations( "/** @constructor */ function Foo(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "function Foo() {\n}\n"); } public void testTypeAnnotationsTypeDef() { // TODO(johnlenz): It would be nice if there were some way to preserve // typedefs but currently they are resolved into the basic types in the // type registry. assertTypeAnnotations( "/** @typedef {Array.<number>} */ goog.java.Long;\n" + "/** @param {!goog.java.Long} a*/\n" + "function f(a){};\n", "goog.java.Long;\n" + "/**\n" + " * @param {(Array.<number>|null)} a\n" + " * @return {undefined}\n" + " */\n" + "function f(a) {\n}\n"); } public void testTypeAnnotationsAssign() { assertTypeAnnotations("/** @constructor */ var Foo = function(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "var Foo = function() {\n};\n"); } public void testTypeAnnotationsNamespace() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n"); } public void testTypeAnnotationsMemberSubclass() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};" + "/** @constructor \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo = function(){};" + "/** @interface \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @extends {a.Foo}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMultipleInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo1 = function(){};" + "/** @interface */ a.Foo2 = function(){};" + "/** @interface \n @extends {a.Foo1} \n @extends {a.Foo2} */" + "a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo1 = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.Foo2 = function() {\n};\n" + "/**\n * @extends {a.Foo1}\n" + " * @extends {a.Foo2}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMember() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}" + "/** @param {string} foo\n" + " * @return {number} */\n" + "a.Foo.prototype.foo = function(foo) { return 3; };" + "/** @type {string|undefined} */" + "a.Foo.prototype.bar = '';", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n" + " * @param {string} foo\n" + " * @return {number}\n" + " */\n" + "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n" + "/** @type {string} */\n" + "a.Foo.prototype.bar = \"\";\n"); } public void testTypeAnnotationsImplements() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};\n" + "/** @interface */ a.I = function(){};\n" + "/** @interface */ a.I2 = function(){};\n" + "/** @constructor \n @extends {a.Foo}\n" + " * @implements {a.I} \n @implements {a.I2}\n" + "*/ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I2 = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @implements {a.I}\n" + " * @implements {a.I2}\n * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsDispatcher1() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " * @javadispatch \n" + " */\n" + "a.Foo = function(){}", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " * @javadispatch\n" + " */\n" + "a.Foo = function() {\n" + "};\n"); } public void testTypeAnnotationsDispatcher2() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " */\n" + "a.Foo = function(){}\n" + "/**\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {};", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " */\n" + "a.Foo = function() {\n" + "};\n" + "/**\n" + " * @return {undefined}\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {\n" + "};\n"); } public void testU2UFunctionTypeAnnotation1() { assertTypeAnnotations( "/** @type {!Function} */ var x = function() {}", "/** @type {!Function} */\n" + "var x = function() {\n};\n"); } public void testU2UFunctionTypeAnnotation2() { // TODO(johnlenz): we currently report the type of the RHS which is not // correct, we should export the type of the LHS. assertTypeAnnotations( "/** @type {Function} */ var x = function() {}", "/** @type {!Function} */\n" + "var x = function() {\n};\n"); } public void testEmitUnknownParamTypesAsAllType() { assertTypeAnnotations( "var a = function(x) {}", "/**\n" + " * @param {?} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testOptionalTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {string=} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {string=} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testVariableArgumentsTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {...string} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {...string} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testTempConstructor() { assertTypeAnnotations( "var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" + " /**\n * @constructor\n */\nfunction t2() {}\n" + " t1.prototype = t2.prototype}", "/**\n * @return {undefined}\n */\nvar x = function() {\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t1() {\n }\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t2() {\n }\n" + " t1.prototype = t2.prototype\n};\n" ); } public void testEnumAnnotation1() { assertTypeAnnotations( "/** @enum {string} */ var Enum = {FOO: 'x', BAR: 'y'};", "/** @enum {string} */\nvar Enum = {FOO:\"x\", BAR:\"y\"};\n"); } public void testEnumAnnotation2() { assertTypeAnnotations( "var goog = goog || {};" + "/** @enum {string} */ goog.Enum = {FOO: 'x', BAR: 'y'};" + "/** @const */ goog.Enum2 = goog.x ? {} : goog.Enum;", "var goog = goog || {};\n" + "/** @enum {string} */\ngoog.Enum = {FOO:\"x\", BAR:\"y\"};\n" + "/** @type {(Object|{})} */\ngoog.Enum2 = goog.x ? {} : goog.Enum;\n"); } private void assertPrettyPrint(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } private void assertTypeAnnotations(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true)); } public void testSubtraction() { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode("x - -4"); assertEquals(0, compiler.getErrorCount()); assertEquals( "x- -4", printNode(n)); } public void testFunctionWithCall() { assertPrint( "var user = new function() {" + "alert(\"foo\")}", "var user=new function(){" + "alert(\"foo\")}"); assertPrint( "var user = new function() {" + "this.name = \"foo\";" + "this.local = function(){alert(this.name)};}", "var user=new function(){" + "this.name=\"foo\";" + "this.local=function(){alert(this.name)}}"); } public void testLineLength() { // list assertLineLength("var aba,bcb,cdc", "var aba,bcb," + "\ncdc"); // operators, and two breaks assertLineLength( "\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"", "\"foo\"+\"bar,baz,bomb\"+" + "\n\"whee\"+\";long-string\"+" + "\n\"aaa\""); // assignment assertLineLength("var abazaba=1234", "var abazaba=" + "\n1234"); // statements assertLineLength("var abab=1;var bab=2", "var abab=1;" + "\nvar bab=2"); // don't break regexes assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a", "var a=/some[reg](ex),with.*we?rd|chars/i;" + "\nvar b=a"); // don't break strings assertLineLength("var a=\"foo,{bar};baz\";var b=a", "var a=\"foo,{bar};baz\";" + "\nvar b=a"); // don't break before post inc/dec assertLineLength("var a=\"a\";a++;var b=\"bbb\";", "var a=\"a\";a++;\n" + "var b=\"bbb\""); } private void assertLineLength(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, 10)); } public void testParsePrintParse() { testReparse("3;"); testReparse("var a = b;"); testReparse("var x, y, z;"); testReparse("try { foo() } catch(e) { bar() }"); testReparse("try { foo() } catch(e) { bar() } finally { stuff() }"); testReparse("try { foo() } finally { stuff() }"); testReparse("throw 'me'"); testReparse("function foo(a) { return a + 4; }"); testReparse("function foo() { return; }"); testReparse("var a = function(a, b) { foo(); return a + b; }"); testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];"); testReparse("v = (5, 6, 7, 8)"); testReparse("d = 34.0; x = 0; y = .3; z = -22"); testReparse("d = -x; t = !x + ~y;"); testReparse("'hi'; /* just a test */ stuff(a,b) \n" + " foo(); // and another \n" + " bar();"); testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;"); testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5"); testReparse("a = (2 + 3) * 4;"); testReparse("a = 1 + (2 + 3) + 4;"); testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());"); testReparse("a = b | c || d ^ e " + "&& f & !g != h << i <= j < k >>> l > m * n % !o"); testReparse("a == b; a != b; a === b; a == b == a;" + " (a == b) == a; a == (b == a);"); testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;"); testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }"); testReparse("for (var i in a) b += i;"); testReparse("for (var i = 0; i < 10; i++){ b /= 2;" + " if (b == 2)break;else continue;}"); testReparse("for (x = 0; x < 10; x++) a /= 2;"); testReparse("for (;;) a++;"); testReparse("while(true) { blah(); }while(true) blah();"); testReparse("do stuff(); while(a>b);"); testReparse("[0, null, , true, false, this];"); testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');"); testReparse("new Foo; new Bar(a, b,c);"); testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;"); testReparse("delete foo['bar']; delete foo;"); testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };"); testReparse("switch(a) { case 2: case 3: stuff(); break;" + "case 4: morestuff(); break; default: done();}"); testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;"); testReparse("a.v = b.v; x['foo'] = y['zoo'];"); testReparse("'test' in x; 3 in x; a in x;"); testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'"); testReparse("x.__proto__;"); } private void testReparse(String code) { Compiler compiler = new Compiler(); Node parse1 = parse(code); Node parse2 = parse(new CodePrinter.Builder(parse1).build()); String explanation = parse1.checkTreeEquals(parse2); assertNull("\nExpected: " + compiler.toSource(parse1) + "\nResult: " + compiler.toSource(parse2) + "\n" + explanation, explanation); } public void testDoLoopIECompatiblity() { // Do loops within IFs cause syntax errors in IE6 and IE7. assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("function f(){if(e1)do foo();while(e2)else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("if(x){do{foo()}while(y)}else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x)do{foo()}while(y);else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x){do{foo()}while(y)}", "if(x){do foo();while(y)}"); assertPrint("if(x)do{foo()}while(y);", "if(x){do foo();while(y)}"); assertPrint("if(x)A:do{foo()}while(y);", "if(x){A:do foo();while(y)}"); assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);", "var i=0;a:do{b:do{i++;break b}while(0)}while(0)"); } public void testFunctionSafariCompatiblity() { // Functions within IFs cause syntax errors on Safari. assertPrint("function f(){if(e1){function goo(){return true}}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("function f(){if(e1)function goo(){return true}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("if(e1){function goo(){return true}}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)function goo(){return true}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)A:function goo(){return true}", "if(e1){A:function goo(){return true}}"); } public void testExponents() { assertPrintNumber("1", 1); assertPrintNumber("10", 10); assertPrintNumber("100", 100); assertPrintNumber("1E3", 1000); assertPrintNumber("1E4", 10000); assertPrintNumber("1E5", 100000); assertPrintNumber("-1", -1); assertPrintNumber("-10", -10); assertPrintNumber("-100", -100); assertPrintNumber("-1E3", -1000); assertPrintNumber("-12341234E4", -123412340000L); assertPrintNumber("1E18", 1000000000000000000L); assertPrintNumber("1E5", 100000.0); assertPrintNumber("100000.1", 100000.1); assertPrintNumber("1E-6", 0.000001); assertPrintNumber("-0x38d7ea4c68001", -0x38d7ea4c68001L); assertPrintNumber("0x38d7ea4c68001", 0x38d7ea4c68001L); } // Make sure to test as both a String and a Node, because // negative numbers do not parse consistently from strings. private void assertPrintNumber(String expected, double number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } private void assertPrintNumber(String expected, int number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } public void testDirectEval() { assertPrint("eval('1');", "eval(\"1\")"); } public void testIndirectEval() { Node n = parse("eval('1');"); assertPrintNode("eval(\"1\")", n); n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp( Node.DIRECT_EVAL, false); assertPrintNode("(0,eval)(\"1\")", n); } public void testFreeCall1() { assertPrint("foo(a);", "foo(a)"); assertPrint("x.foo(a);", "x.foo(a)"); } public void testFreeCall2() { Node n = parse("foo(a);"); assertPrintNode("foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.isCall()); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("foo(a)", n); } public void testFreeCall3() { Node n = parse("x.foo(a);"); assertPrintNode("x.foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.isCall()); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("(0,x.foo)(a)", n); } public void testPrintScript() { // Verify that SCRIPT nodes not marked as synthetic are printed as // blocks. Node ast = new Node(Token.SCRIPT, new Node(Token.EXPR_RESULT, Node.newString("f")), new Node(Token.EXPR_RESULT, Node.newString("g"))); String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build(); assertEquals("\"f\";\n\"g\";\n", result); } public void testObjectLit() { assertPrint("({x:1})", "({x:1})"); assertPrint("var x=({x:1})", "var x={x:1}"); assertPrint("var x={'x':1}", "var x={\"x\":1}"); assertPrint("var x={1:1}", "var x={1:1}"); assertPrint("({},42)+0", "({},42)+0"); } public void testObjectLit2() { assertPrint("var x={1:1}", "var x={1:1}"); assertPrint("var x={'1':1}", "var x={1:1}"); assertPrint("var x={'1.0':1}", "var x={\"1.0\":1}"); assertPrint("var x={1.5:1}", "var x={\"1.5\":1}"); } public void testObjectLit3() { assertPrint("var x={3E9:1}", "var x={3E9:1}"); assertPrint("var x={'3000000000':1}", // More than 31 bits "var x={3E9:1}"); assertPrint("var x={'3000000001':1}", "var x={3000000001:1}"); assertPrint("var x={'6000000001':1}", // More than 32 bits "var x={6000000001:1}"); assertPrint("var x={\"12345678901234567\":1}", // More than 53 bits "var x={\"12345678901234567\":1}"); } public void testObjectLit4() { // More than 128 bits. assertPrint( "var x={\"123456789012345671234567890123456712345678901234567\":1}", "var x={\"123456789012345671234567890123456712345678901234567\":1}"); } public void testGetter() { assertPrint("var x = {}", "var x={}"); assertPrint("var x = {get a() {return 1}}", "var x={get a(){return 1}}"); assertPrint( "var x = {get a() {}, get b(){}}", "var x={get a(){},get b(){}}"); assertPrint( "var x = {get 'a'() {return 1}}", "var x={get \"a\"(){return 1}}"); assertPrint( "var x = {get 1() {return 1}}", "var x={get 1(){return 1}}"); assertPrint( "var x = {get \"()\"() {return 1}}", "var x={get \"()\"(){return 1}}"); } public void testSetter() { assertPrint("var x = {}", "var x={}"); assertPrint( "var x = {set a(y) {return 1}}", "var x={set a(y){return 1}}"); assertPrint( "var x = {get 'a'() {return 1}}", "var x={get \"a\"(){return 1}}"); assertPrint( "var x = {set 1(y) {return 1}}", "var x={set 1(y){return 1}}"); assertPrint( "var x = {set \"(x)\"(y) {return 1}}", "var x={set \"(x)\"(y){return 1}}"); } public void testNegCollapse() { // Collapse the negative symbol on numbers at generation time, // to match the Rhino behavior. assertPrint("var x = - - 2;", "var x=2"); assertPrint("var x = - (2);", "var x=-2"); } public void testStrict() { String result = parsePrint("var x", false, false, 0, false, true); assertEquals("'use strict';var x", result); } public void testArrayLiteral() { assertPrint("var x = [,];","var x=[,]"); assertPrint("var x = [,,];","var x=[,,]"); assertPrint("var x = [,s,,];","var x=[,s,,]"); assertPrint("var x = [,s];","var x=[,s]"); assertPrint("var x = [s,];","var x=[s]"); } public void testZero() { assertPrint("var x ='\\0';", "var x=\"\\x00\""); assertPrint("var x ='\\x00';", "var x=\"\\x00\""); assertPrint("var x ='\\u0000';", "var x=\"\\x00\""); assertPrint("var x ='\\u00003';", "var x=\"\\x003\""); } public void testUnicode() { assertPrint("var x ='\\x0f';", "var x=\"\\u000f\""); assertPrint("var x ='\\x68';", "var x=\"h\""); assertPrint("var x ='\\x7f';", "var x=\"\\u007f\""); } public void testUnicodeKeyword() { // keyword "if" assertPrint("var \\u0069\\u0066 = 1;", "var i\\u0066=1"); // keyword "var" assertPrint("var v\\u0061\\u0072 = 1;", "var va\\u0072=1"); // all are keyword "while" assertPrint("var w\\u0068\\u0069\\u006C\\u0065 = 1;" + "\\u0077\\u0068il\\u0065 = 2;" + "\\u0077h\\u0069le = 3;", "var whil\\u0065=1;whil\\u0065=2;whil\\u0065=3"); } public void testNumericKeys() { assertPrint("var x = {010: 1};", "var x={8:1}"); assertPrint("var x = {'010': 1};", "var x={\"010\":1}"); assertPrint("var x = {0x10: 1};", "var x={16:1}"); assertPrint("var x = {'0x10': 1};", "var x={\"0x10\":1}"); // I was surprised at this result too. assertPrint("var x = {.2: 1};", "var x={\"0.2\":1}"); assertPrint("var x = {'.2': 1};", "var x={\".2\":1}"); assertPrint("var x = {0.2: 1};", "var x={\"0.2\":1}"); assertPrint("var x = {'0.2': 1};", "var x={\"0.2\":1}"); } public void testIssue582() { assertPrint("var x = -0.0;", "var x=-0"); } public void testIssue942() { assertPrint("var x = {0: 1};", "var x={0:1}"); } public void testIssue601() { assertPrint("'\\v' == 'v'", "\"\\v\"==\"v\""); assertPrint("'\\u000B' == '\\v'", "\"\\x0B\"==\"\\v\""); assertPrint("'\\x0B' == '\\v'", "\"\\x0B\"==\"\\v\""); } public void testIssue620() { assertPrint("alert(/ / / / /);", "alert(/ // / /)"); assertPrint("alert(/ // / /);", "alert(/ // / /)"); } public void testIssue5746867() { assertPrint("var a = { '$\\\\' : 5 };", "var a={\"$\\\\\":5}"); } public void testCommaSpacing() { assertPrint("var a = (b = 5, c = 5);", "var a=(b=5,c=5)"); assertPrettyPrint("var a = (b = 5, c = 5);", "var a = (b = 5, c = 5);\n"); } public void testManyCommas() { int numCommas = 10000; List<String> numbers = Lists.newArrayList("0", "1"); Node current = new Node(Token.COMMA, Node.newNumber(0), Node.newNumber(1)); for (int i = 2; i < numCommas; i++) { current = new Node(Token.COMMA, current); // 1000 is printed as 1E3, and screws up our test. int num = i % 1000; numbers.add(String.valueOf(num)); current.addChildToBack(Node.newNumber(num)); } String expected = Joiner.on(",").join(numbers); String actual = printNode(current).replace("\n", ""); assertEquals(expected, actual); } public void testManyAdds() { int numAdds = 10000; List<String> numbers = Lists.newArrayList("0", "1"); Node current = new Node(Token.ADD, Node.newNumber(0), Node.newNumber(1)); for (int i = 2; i < numAdds; i++) { current = new Node(Token.ADD, current); // 1000 is printed as 1E3, and screws up our test. int num = i % 1000; numbers.add(String.valueOf(num)); current.addChildToBack(Node.newNumber(num)); } String expected = Joiner.on("+").join(numbers); String actual = printNode(current).replace("\n", ""); assertEquals(expected, actual); } public void testMinusNegativeZero() { // Negative zero is weird, because we have to be able to distinguish // it from positive zero (there are some subtle differences in behavior). assertPrint("x- -0", "x- -0"); } public void testStringEscapeSequences() { // From the SingleEscapeCharacter grammar production. assertPrintSame("var x=\"\\b\""); assertPrintSame("var x=\"\\f\""); assertPrintSame("var x=\"\\n\""); assertPrintSame("var x=\"\\r\""); assertPrintSame("var x=\"\\t\""); assertPrintSame("var x=\"\\v\""); assertPrint("var x=\"\\\"\"", "var x='\"'"); assertPrint("var x=\"\\\'\"", "var x=\"'\""); // From the LineTerminator grammar assertPrint("var x=\"\\u000A\"", "var x=\"\\n\""); assertPrint("var x=\"\\u000D\"", "var x=\"\\r\""); assertPrintSame("var x=\"\\u2028\""); assertPrintSame("var x=\"\\u2029\""); // Now with regular expressions. assertPrintSame("var x=/\\b/"); assertPrintSame("var x=/\\f/"); assertPrintSame("var x=/\\n/"); assertPrintSame("var x=/\\r/"); assertPrintSame("var x=/\\t/"); assertPrintSame("var x=/\\v/"); assertPrintSame("var x=/\\u000A/"); assertPrintSame("var x=/\\u000D/"); assertPrintSame("var x=/\\u2028/"); assertPrintSame("var x=/\\u2029/"); } }
// You are a professional Java test case writer, please create a test case named `testIssue942` for the issue `Closure-942`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-942 // // ## Issue-Title: // The compiler quotes the "0" keys in object literals // // ## Issue-Description: // **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. // // public void testIssue942() {
1,423
128
1,421
test/com/google/javascript/jscomp/CodePrinterTest.java
test
```markdown ## Issue-ID: Closure-942 ## Issue-Title: The compiler quotes the "0" keys in object literals ## Issue-Description: **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. ``` You are a professional Java test case writer, please create a test case named `testIssue942` for the issue `Closure-942`, utilizing the provided issue report information and the following function signature. ```java public void testIssue942() { ```
1,421
[ "com.google.javascript.jscomp.CodeGenerator" ]
15d60e6645b093549e8c3de4539bca0e969d9c49f179eabf2a0ff154411dd46d
public void testIssue942()
// You are a professional Java test case writer, please create a test case named `testIssue942` for the issue `Closure-942`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-942 // // ## Issue-Title: // The compiler quotes the "0" keys in object literals // // ## Issue-Description: // **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. // //
Closure
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; import java.util.List; public class CodePrinterTest extends TestCase { private boolean trustedStrings = true; private Compiler lastCompiler = null; @Override public void setUp() { trustedStrings = true; lastCompiler = null; } Node parse(String js) { return parse(js, false); } Node parse(String js, boolean checkTypes) { Compiler compiler = new Compiler(); lastCompiler = compiler; CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); // Allow getters and setters. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.initOptions(options); Node n = compiler.parseTestCode(js); if (checkTypes) { DefaultPassConfig passConfig = new DefaultPassConfig(null); CompilerPass typeResolver = passConfig.resolveTypes.create(compiler); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); typeResolver.process(externs, n); CompilerPass inferTypes = passConfig.inferTypes.create(compiler); inferTypes.process(externs, n); } checkUnexpectedErrorsOrWarnings(compiler, 0); return n; } private static void checkUnexpectedErrorsOrWarnings( Compiler compiler, int expected) { int actual = compiler.getErrors().length + compiler.getWarnings().length; if (actual != expected) { String msg = ""; for (JSError err : compiler.getErrors()) { msg += "Error:" + err.toString() + "\n"; } for (JSError err : compiler.getWarnings()) { msg += "Warning:" + err.toString() + "\n"; } assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual); } } String parsePrint(String js, boolean prettyprint, int lineThreshold) { CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); return new CodePrinter.Builder(parse(js)).setCompilerOptions(options) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold) { CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); options.setLineBreak(lineBreak); return new CodePrinter.Builder(parse(js)).setCompilerOptions(options) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, boolean preferLineBreakAtEof, int lineThreshold) { CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); options.setPreferLineBreakAtEndOfFile(preferLineBreakAtEof); options.setLineBreak(lineBreak); return new CodePrinter.Builder(parse(js)).setCompilerOptions(options) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes) { Node node = parse(js, true); CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); options.setLineBreak(lineBreak); return new CodePrinter.Builder(node).setCompilerOptions(options) .setOutputTypes(outputTypes) .setTypeRegistry(lastCompiler.getTypeRegistry()) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes, boolean tagAsStrict) { Node node = parse(js, true); CompilerOptions options = new CompilerOptions(); options.setTrustedStrings(trustedStrings); options.setPrettyPrint(prettyprint); options.setLineLengthThreshold(lineThreshold); options.setLineBreak(lineBreak); return new CodePrinter.Builder(node).setCompilerOptions(options) .setOutputTypes(outputTypes) .setTypeRegistry(lastCompiler.getTypeRegistry()) .setTagAsStrict(tagAsStrict) .build(); } String printNode(Node n) { CompilerOptions options = new CompilerOptions(); options.setLineLengthThreshold(CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD); return new CodePrinter.Builder(n).setCompilerOptions(options).build(); } void assertPrintNode(String expectedJs, Node ast) { assertEquals(expectedJs, printNode(ast)); } public void testPrint() { assertPrint("10 + a + b", "10+a+b"); assertPrint("10 + (30*50)", "10+30*50"); assertPrint("with(x) { x + 3; }", "with(x)x+3"); assertPrint("\"aa'a\"", "\"aa'a\""); assertPrint("\"aa\\\"a\"", "'aa\"a'"); assertPrint("function foo()\n{return 10;}", "function foo(){return 10}"); assertPrint("a instanceof b", "a instanceof b"); assertPrint("typeof(a)", "typeof a"); assertPrint( "var foo = x ? { a : 1 } : {a: 3, b:4, \"default\": 5, \"foo-bar\": 6}", "var foo=x?{a:1}:{a:3,b:4,\"default\":5,\"foo-bar\":6}"); // Safari: needs ';' at the end of a throw statement assertPrint("function foo(){throw 'error';}", "function foo(){throw\"error\";}"); // Safari 3 needs a "{" around a single function assertPrint("if (true) function foo(){return}", "if(true){function foo(){return}}"); assertPrint("var x = 10; { var y = 20; }", "var x=10;var y=20"); assertPrint("while (x-- > 0);", "while(x-- >0);"); assertPrint("x-- >> 1", "x-- >>1"); assertPrint("(function () {})(); ", "(function(){})()"); // Associativity assertPrint("var a,b,c,d;a || (b&& c) && (a || d)", "var a,b,c,d;a||b&&c&&(a||d)"); assertPrint("var a,b,c; a || (b || c); a * (b * c); a | (b | c)", "var a,b,c;a||b||c;a*b*c;a|b|c"); assertPrint("var a,b,c; a / b / c;a / (b / c); a - (b - c);", "var a,b,c;a/b/c;a/(b/c);a-(b-c)"); assertPrint("var a,b; a = b = 3;", "var a,b;a=b=3"); assertPrint("var a,b,c,d; a = (b = c = (d = 3));", "var a,b,c,d;a=b=c=d=3"); assertPrint("var a,b,c; a += (b = c += 3);", "var a,b,c;a+=b=c+=3"); assertPrint("var a,b,c; a *= (b -= c);", "var a,b,c;a*=b-=c"); // Precedence assertPrint("a ? delete b[0] : 3", "a?delete b[0]:3"); assertPrint("(delete a[0])/10", "delete a[0]/10"); // optional '()' for new // simple new assertPrint("new A", "new A"); assertPrint("new A()", "new A"); assertPrint("new A('x')", "new A(\"x\")"); // calling instance method directly after new assertPrint("new A().a()", "(new A).a()"); assertPrint("(new A).a()", "(new A).a()"); // this case should be fixed assertPrint("new A('y').a()", "(new A(\"y\")).a()"); // internal class assertPrint("new A.B", "new A.B"); assertPrint("new A.B()", "new A.B"); assertPrint("new A.B('z')", "new A.B(\"z\")"); // calling instance method directly after new internal class assertPrint("(new A.B).a()", "(new A.B).a()"); assertPrint("new A.B().a()", "(new A.B).a()"); // this case should be fixed assertPrint("new A.B('w').a()", "(new A.B(\"w\")).a()"); // Operators: make sure we don't convert binary + and unary + into ++ assertPrint("x + +y", "x+ +y"); assertPrint("x - (-y)", "x- -y"); assertPrint("x++ +y", "x++ +y"); assertPrint("x-- -y", "x-- -y"); assertPrint("x++ -y", "x++-y"); // Label assertPrint("foo:for(;;){break foo;}", "foo:for(;;)break foo"); assertPrint("foo:while(1){continue foo;}", "foo:while(1)continue foo"); // Object literals. assertPrint("({})", "({})"); assertPrint("var x = {};", "var x={}"); assertPrint("({}).x", "({}).x"); assertPrint("({})['x']", "({})[\"x\"]"); assertPrint("({}) instanceof Object", "({})instanceof Object"); assertPrint("({}) || 1", "({})||1"); assertPrint("1 || ({})", "1||{}"); assertPrint("({}) ? 1 : 2", "({})?1:2"); assertPrint("0 ? ({}) : 2", "0?{}:2"); assertPrint("0 ? 1 : ({})", "0?1:{}"); assertPrint("typeof ({})", "typeof{}"); assertPrint("f({})", "f({})"); // Anonymous function expressions. assertPrint("(function(){})", "(function(){})"); assertPrint("(function(){})()", "(function(){})()"); assertPrint("(function(){})instanceof Object", "(function(){})instanceof Object"); assertPrint("(function(){}).bind().call()", "(function(){}).bind().call()"); assertPrint("var x = function() { };", "var x=function(){}"); assertPrint("var x = function() { }();", "var x=function(){}()"); assertPrint("(function() {}), 2", "(function(){}),2"); // Name functions expression. assertPrint("(function f(){})", "(function f(){})"); // Function declaration. assertPrint("function f(){}", "function f(){}"); // Make sure we don't treat non-Latin character escapes as raw strings. assertPrint("({ 'a': 4, '\\u0100': 4 })", "({\"a\":4,\"\\u0100\":4})"); assertPrint("({ a: 4, '\\u0100': 4 })", "({a:4,\"\\u0100\":4})"); // Test if statement and for statements with single statements in body. assertPrint("if (true) { alert();}", "if(true)alert()"); assertPrint("if (false) {} else {alert(\"a\");}", "if(false);else alert(\"a\")"); assertPrint("for(;;) { alert();};", "for(;;)alert()"); assertPrint("do { alert(); } while(true);", "do alert();while(true)"); assertPrint("myLabel: { alert();}", "myLabel:alert()"); assertPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;)continue myLabel"); // Test nested var statement assertPrint("if (true) var x; x = 4;", "if(true)var x;x=4"); // Non-latin identifier. Make sure we keep them escaped. assertPrint("\\u00fb", "\\u00fb"); assertPrint("\\u00fa=1", "\\u00fa=1"); assertPrint("function \\u00f9(){}", "function \\u00f9(){}"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("abc\\u4e00\\u4e01jkl", "abc\\u4e00\\u4e01jkl"); // Test the right-associative unary operators for spurious parens assertPrint("! ! true", "!!true"); assertPrint("!(!(true))", "!!true"); assertPrint("typeof(void(0))", "typeof void 0"); assertPrint("typeof(void(!0))", "typeof void!0"); assertPrint("+ - + + - + 3", "+-+ +-+3"); // chained unary plus/minus assertPrint("+(--x)", "+--x"); assertPrint("-(++x)", "-++x"); // needs a space to prevent an ambiguous parse assertPrint("-(--x)", "- --x"); assertPrint("!(~~5)", "!~~5"); assertPrint("~(a/b)", "~(a/b)"); // Preserve parens to overcome greedy binding of NEW assertPrint("new (foo.bar()).factory(baz)", "new (foo.bar().factory)(baz)"); assertPrint("new (bar()).factory(baz)", "new (bar().factory)(baz)"); assertPrint("new (new foobar(x)).factory(baz)", "new (new foobar(x)).factory(baz)"); // Make sure that HOOK is right associative assertPrint("a ? b : (c ? d : e)", "a?b:c?d:e"); assertPrint("a ? (b ? c : d) : e", "a?b?c:d:e"); assertPrint("(a ? b : c) ? d : e", "(a?b:c)?d:e"); // Test nested ifs assertPrint("if (x) if (y); else;", "if(x)if(y);else;"); // Test comma. assertPrint("a,b,c", "a,b,c"); assertPrint("(a,b),c", "a,b,c"); assertPrint("a,(b,c)", "a,b,c"); assertPrint("x=a,b,c", "x=a,b,c"); assertPrint("x=(a,b),c", "x=(a,b),c"); assertPrint("x=a,(b,c)", "x=a,b,c"); assertPrint("x=a,y=b,z=c", "x=a,y=b,z=c"); assertPrint("x=(a,y=b,z=c)", "x=(a,y=b,z=c)"); assertPrint("x=[a,b,c,d]", "x=[a,b,c,d]"); assertPrint("x=[(a,b,c),d]", "x=[(a,b,c),d]"); assertPrint("x=[(a,(b,c)),d]", "x=[(a,b,c),d]"); assertPrint("x=[a,(b,c,d)]", "x=[a,(b,c,d)]"); assertPrint("var x=(a,b)", "var x=(a,b)"); assertPrint("var x=a,b,c", "var x=a,b,c"); assertPrint("var x=(a,b),c", "var x=(a,b),c"); assertPrint("var x=a,b=(c,d)", "var x=a,b=(c,d)"); assertPrint("foo(a,b,c,d)", "foo(a,b,c,d)"); assertPrint("foo((a,b,c),d)", "foo((a,b,c),d)"); assertPrint("foo((a,(b,c)),d)", "foo((a,b,c),d)"); assertPrint("f(a+b,(c,d,(e,f,g)))", "f(a+b,(c,d,e,f,g))"); assertPrint("({}) , 1 , 2", "({}),1,2"); assertPrint("({}) , {} , {}", "({}),{},{}"); // EMPTY nodes assertPrint("if (x){}", "if(x);"); assertPrint("if(x);", "if(x);"); assertPrint("if(x)if(y);", "if(x)if(y);"); assertPrint("if(x){if(y);}", "if(x)if(y);"); assertPrint("if(x){if(y){};;;}", "if(x)if(y);"); assertPrint("if(x){;;function y(){};;}", "if(x){function y(){}}"); } public void testBreakTrustedStrings() { // Break scripts assertPrint("'<script>'", "\"<script>\""); assertPrint("'</script>'", "\"\\x3c/script>\""); assertPrint("\"</script> </SCRIPT>\"", "\"\\x3c/script> \\x3c/SCRIPT>\""); assertPrint("'-->'", "\"--\\x3e\""); assertPrint("']]>'", "\"]]\\x3e\""); assertPrint("' --></script>'", "\" --\\x3e\\x3c/script>\""); assertPrint("/--> <\\/script>/g", "/--\\x3e <\\/script>/g"); // Break HTML start comments. Certain versions of WebKit // begin an HTML comment when they see this. assertPrint("'<!-- I am a string -->'", "\"\\x3c!-- I am a string --\\x3e\""); assertPrint("'<=&>'", "\"<=&>\""); } public void testBreakUntrustedStrings() { trustedStrings = false; // Break scripts assertPrint("'<script>'", "\"\\x3cscript\\x3e\""); assertPrint("'</script>'", "\"\\x3c/script\\x3e\""); assertPrint("\"</script> </SCRIPT>\"", "\"\\x3c/script\\x3e \\x3c/SCRIPT\\x3e\""); assertPrint("'-->'", "\"--\\x3e\""); assertPrint("']]>'", "\"]]\\x3e\""); assertPrint("' --></script>'", "\" --\\x3e\\x3c/script\\x3e\""); assertPrint("/--> <\\/script>/g", "/--\\x3e <\\/script>/g"); // Break HTML start comments. Certain versions of WebKit // begin an HTML comment when they see this. assertPrint("'<!-- I am a string -->'", "\"\\x3c!-- I am a string --\\x3e\""); assertPrint("'<=&>'", "\"\\x3c\\x3d\\x26\\x3e\""); assertPrint("/(?=x)/", "/(?=x)/"); } public void testPrintArray() { assertPrint("[void 0, void 0]", "[void 0,void 0]"); assertPrint("[undefined, undefined]", "[undefined,undefined]"); assertPrint("[ , , , undefined]", "[,,,undefined]"); assertPrint("[ , , , 0]", "[,,,0]"); } public void testHook() { assertPrint("a ? b = 1 : c = 2", "a?b=1:c=2"); assertPrint("x = a ? b = 1 : c = 2", "x=a?b=1:c=2"); assertPrint("(x = a) ? b = 1 : c = 2", "(x=a)?b=1:c=2"); assertPrint("x, a ? b = 1 : c = 2", "x,a?b=1:c=2"); assertPrint("x, (a ? b = 1 : c = 2)", "x,a?b=1:c=2"); assertPrint("(x, a) ? b = 1 : c = 2", "(x,a)?b=1:c=2"); assertPrint("a ? (x, b) : c = 2", "a?(x,b):c=2"); assertPrint("a ? b = 1 : (x,c)", "a?b=1:(x,c)"); assertPrint("a ? b = 1 : c = 2 + x", "a?b=1:c=2+x"); assertPrint("(a ? b = 1 : c = 2) + x", "(a?b=1:c=2)+x"); assertPrint("a ? b = 1 : (c = 2) + x", "a?b=1:(c=2)+x"); assertPrint("a ? (b?1:2) : 3", "a?b?1:2:3"); } public void testPrintInOperatorInForLoop() { // Check for in expression in for's init expression. // Check alone, with + (higher precedence), with ?: (lower precedence), // and with conditional. assertPrint("var a={}; for (var i = (\"length\" in a); i;) {}", "var a={};for(var i=(\"length\"in a);i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) ? 0 : 1; i;) {}", "var a={};for(var i=(\"length\"in a)?0:1;i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) + 1; i;) {}", "var a={};for(var i=(\"length\"in a)+1;i;);"); assertPrint("var a={};for (var i = (\"length\" in a|| \"size\" in a);;);", "var a={};for(var i=(\"length\"in a)||(\"size\"in a);;);"); assertPrint("var a={};for (var i = a || a || (\"size\" in a);;);", "var a={};for(var i=a||a||(\"size\"in a);;);"); // Test works with unary operators and calls. assertPrint("var a={}; for (var i = -(\"length\" in a); i;) {}", "var a={};for(var i=-(\"length\"in a);i;);"); assertPrint("var a={};function b_(p){ return p;};" + "for(var i=1,j=b_(\"length\" in a);;) {}", "var a={};function b_(p){return p}" + "for(var i=1,j=b_(\"length\"in a);;);"); // Test we correctly handle an in operator in the test clause. assertPrint("var a={}; for (;(\"length\" in a);) {}", "var a={};for(;\"length\"in a;);"); } public void testLiteralProperty() { assertPrint("(64).toString()", "(64).toString()"); } private void assertPrint(String js, String expected) { parse(expected); // validate the expected string is valid JS assertEquals(expected, parsePrint(js, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } private void assertPrintSame(String js) { assertPrint(js, js); } // Make sure that the code generator doesn't associate an // else clause with the wrong if clause. public void testAmbiguousElseClauses() { assertPrintNode("if(x)if(y);else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), // ELSE clause for the inner if new Node(Token.BLOCK))))); assertPrintNode("if(x){if(y);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK))), // ELSE clause for the outer if new Node(Token.BLOCK))); assertPrintNode("if(x)if(y);else{if(z);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "z"), new Node(Token.BLOCK))))), // ELSE clause for the outermost if new Node(Token.BLOCK))); } public void testLineBreak() { // line break after function if in a statement context assertLineBreak("function a() {}\n" + "function b() {}", "function a(){}\n" + "function b(){}\n"); // line break after ; after a function assertLineBreak("var a = {};\n" + "a.foo = function () {}\n" + "function b() {}", "var a={};a.foo=function(){};\n" + "function b(){}\n"); // break after comma after a function assertLineBreak("var a = {\n" + " b: function() {},\n" + " c: function() {}\n" + "};\n" + "alert(a);", "var a={b:function(){},\n" + "c:function(){}};\n" + "alert(a)"); } private void assertLineBreak(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } public void testPreferLineBreakAtEndOfFile() { // short final line, no previous break, do nothing assertLineBreakAtEndOfFile( "\"1234567890\";", "\"1234567890\"", "\"1234567890\""); // short final line, shift previous break to end assertLineBreakAtEndOfFile( "\"123456789012345678901234567890\";\"1234567890\"", "\"123456789012345678901234567890\";\n\"1234567890\"", "\"123456789012345678901234567890\"; \"1234567890\";\n"); assertLineBreakAtEndOfFile( "var12345678901234567890123456 instanceof Object;", "var12345678901234567890123456 instanceof\nObject", "var12345678901234567890123456 instanceof Object;\n"); // long final line, no previous break, add a break at end assertLineBreakAtEndOfFile( "\"1234567890\";\"12345678901234567890\";", "\"1234567890\";\"12345678901234567890\"", "\"1234567890\";\"12345678901234567890\";\n"); // long final line, previous break, add a break at end assertLineBreakAtEndOfFile( "\"123456789012345678901234567890\";\"12345678901234567890\";", "\"123456789012345678901234567890\";\n\"12345678901234567890\"", "\"123456789012345678901234567890\";\n\"12345678901234567890\";\n"); } private void assertLineBreakAtEndOfFile(String js, String expectedWithoutBreakAtEnd, String expectedWithBreakAtEnd) { assertEquals(expectedWithoutBreakAtEnd, parsePrint(js, false, false, false, 30)); assertEquals(expectedWithBreakAtEnd, parsePrint(js, false, false, true, 30)); } public void testPrettyPrinter() { // Ensure that the pretty printer inserts line breaks at appropriate // places. assertPrettyPrint("(function(){})();","(function() {\n})();\n"); assertPrettyPrint("var a = (function() {});alert(a);", "var a = function() {\n};\nalert(a);\n"); // Check we correctly handle putting brackets around all if clauses so // we can put breakpoints inside statements. assertPrettyPrint("if (1) {}", "if(1) {\n" + "}\n"); assertPrettyPrint("if (1) {alert(\"\");}", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1)alert(\"\");", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1) {alert();alert();}", "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); // Don't add blocks if they weren't there already. assertPrettyPrint("label: alert();", "label:alert();\n"); // But if statements and loops get blocks automagically. assertPrettyPrint("if (1) alert();", "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for (;;) alert();", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("while (1) alert();", "while(1) {\n" + " alert()\n" + "}\n"); // Do we put else clauses in blocks? assertPrettyPrint("if (1) {} else {alert(a);}", "if(1) {\n" + "}else {\n alert(a)\n}\n"); // Do we add blocks to else clauses? assertPrettyPrint("if (1) alert(a); else alert(b);", "if(1) {\n" + " alert(a)\n" + "}else {\n" + " alert(b)\n" + "}\n"); // Do we put for bodies in blocks? assertPrettyPrint("for(;;) { alert();}", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for(;;) {}", "for(;;) {\n" + "}\n"); assertPrettyPrint("for(;;) { alert(); alert(); }", "for(;;) {\n" + " alert();\n" + " alert()\n" + "}\n"); // How about do loops? assertPrettyPrint("do { alert(); } while(true);", "do {\n" + " alert()\n" + "}while(true);\n"); // label? assertPrettyPrint("myLabel: { alert();}", "myLabel: {\n" + " alert()\n" + "}\n"); // Don't move the label on a loop, because then break {label} and // continue {label} won't work. assertPrettyPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;) {\n" + " continue myLabel\n" + "}\n"); assertPrettyPrint("var a;", "var a;\n"); } public void testPrettyPrinter2() { assertPrettyPrint( "if(true) f();", "if(true) {\n" + " f()\n" + "}\n"); assertPrettyPrint( "if (true) { f() } else { g() }", "if(true) {\n" + " f()\n" + "}else {\n" + " g()\n" + "}\n"); assertPrettyPrint( "if(true) f(); for(;;) g();", "if(true) {\n" + " f()\n" + "}\n" + "for(;;) {\n" + " g()\n" + "}\n"); } public void testPrettyPrinter3() { assertPrettyPrint( "try {} catch(e) {}if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} finally {}if (1) {alert();alert();}", "try {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} catch(e) {} finally {} if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); } public void testPrettyPrinter4() { assertPrettyPrint( "function f() {}if (1) {alert();}", "function f() {\n" + "}\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "var f = function() {};if (1) {alert();}", "var f = function() {\n" + "};\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {})();if (1) {alert();}", "(function() {\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {alert();alert();})();if (1) {alert();}", "(function() {\n" + " alert();\n" + " alert()\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); } public void testTypeAnnotations() { assertTypeAnnotations( "/** @constructor */ function Foo(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "function Foo() {\n}\n"); } public void testTypeAnnotationsTypeDef() { // TODO(johnlenz): It would be nice if there were some way to preserve // typedefs but currently they are resolved into the basic types in the // type registry. assertTypeAnnotations( "/** @typedef {Array.<number>} */ goog.java.Long;\n" + "/** @param {!goog.java.Long} a*/\n" + "function f(a){};\n", "goog.java.Long;\n" + "/**\n" + " * @param {(Array.<number>|null)} a\n" + " * @return {undefined}\n" + " */\n" + "function f(a) {\n}\n"); } public void testTypeAnnotationsAssign() { assertTypeAnnotations("/** @constructor */ var Foo = function(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "var Foo = function() {\n};\n"); } public void testTypeAnnotationsNamespace() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n"); } public void testTypeAnnotationsMemberSubclass() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};" + "/** @constructor \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo = function(){};" + "/** @interface \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @extends {a.Foo}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMultipleInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo1 = function(){};" + "/** @interface */ a.Foo2 = function(){};" + "/** @interface \n @extends {a.Foo1} \n @extends {a.Foo2} */" + "a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo1 = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.Foo2 = function() {\n};\n" + "/**\n * @extends {a.Foo1}\n" + " * @extends {a.Foo2}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMember() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}" + "/** @param {string} foo\n" + " * @return {number} */\n" + "a.Foo.prototype.foo = function(foo) { return 3; };" + "/** @type {string|undefined} */" + "a.Foo.prototype.bar = '';", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n" + " * @param {string} foo\n" + " * @return {number}\n" + " */\n" + "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n" + "/** @type {string} */\n" + "a.Foo.prototype.bar = \"\";\n"); } public void testTypeAnnotationsImplements() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};\n" + "/** @interface */ a.I = function(){};\n" + "/** @interface */ a.I2 = function(){};\n" + "/** @constructor \n @extends {a.Foo}\n" + " * @implements {a.I} \n @implements {a.I2}\n" + "*/ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I2 = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @implements {a.I}\n" + " * @implements {a.I2}\n * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsDispatcher1() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " * @javadispatch \n" + " */\n" + "a.Foo = function(){}", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " * @javadispatch\n" + " */\n" + "a.Foo = function() {\n" + "};\n"); } public void testTypeAnnotationsDispatcher2() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " */\n" + "a.Foo = function(){}\n" + "/**\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {};", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " */\n" + "a.Foo = function() {\n" + "};\n" + "/**\n" + " * @return {undefined}\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {\n" + "};\n"); } public void testU2UFunctionTypeAnnotation1() { assertTypeAnnotations( "/** @type {!Function} */ var x = function() {}", "/** @type {!Function} */\n" + "var x = function() {\n};\n"); } public void testU2UFunctionTypeAnnotation2() { // TODO(johnlenz): we currently report the type of the RHS which is not // correct, we should export the type of the LHS. assertTypeAnnotations( "/** @type {Function} */ var x = function() {}", "/** @type {!Function} */\n" + "var x = function() {\n};\n"); } public void testEmitUnknownParamTypesAsAllType() { assertTypeAnnotations( "var a = function(x) {}", "/**\n" + " * @param {?} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testOptionalTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {string=} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {string=} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testVariableArgumentsTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {...string} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {...string} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testTempConstructor() { assertTypeAnnotations( "var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" + " /**\n * @constructor\n */\nfunction t2() {}\n" + " t1.prototype = t2.prototype}", "/**\n * @return {undefined}\n */\nvar x = function() {\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t1() {\n }\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t2() {\n }\n" + " t1.prototype = t2.prototype\n};\n" ); } public void testEnumAnnotation1() { assertTypeAnnotations( "/** @enum {string} */ var Enum = {FOO: 'x', BAR: 'y'};", "/** @enum {string} */\nvar Enum = {FOO:\"x\", BAR:\"y\"};\n"); } public void testEnumAnnotation2() { assertTypeAnnotations( "var goog = goog || {};" + "/** @enum {string} */ goog.Enum = {FOO: 'x', BAR: 'y'};" + "/** @const */ goog.Enum2 = goog.x ? {} : goog.Enum;", "var goog = goog || {};\n" + "/** @enum {string} */\ngoog.Enum = {FOO:\"x\", BAR:\"y\"};\n" + "/** @type {(Object|{})} */\ngoog.Enum2 = goog.x ? {} : goog.Enum;\n"); } private void assertPrettyPrint(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } private void assertTypeAnnotations(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true)); } public void testSubtraction() { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode("x - -4"); assertEquals(0, compiler.getErrorCount()); assertEquals( "x- -4", printNode(n)); } public void testFunctionWithCall() { assertPrint( "var user = new function() {" + "alert(\"foo\")}", "var user=new function(){" + "alert(\"foo\")}"); assertPrint( "var user = new function() {" + "this.name = \"foo\";" + "this.local = function(){alert(this.name)};}", "var user=new function(){" + "this.name=\"foo\";" + "this.local=function(){alert(this.name)}}"); } public void testLineLength() { // list assertLineLength("var aba,bcb,cdc", "var aba,bcb," + "\ncdc"); // operators, and two breaks assertLineLength( "\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"", "\"foo\"+\"bar,baz,bomb\"+" + "\n\"whee\"+\";long-string\"+" + "\n\"aaa\""); // assignment assertLineLength("var abazaba=1234", "var abazaba=" + "\n1234"); // statements assertLineLength("var abab=1;var bab=2", "var abab=1;" + "\nvar bab=2"); // don't break regexes assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a", "var a=/some[reg](ex),with.*we?rd|chars/i;" + "\nvar b=a"); // don't break strings assertLineLength("var a=\"foo,{bar};baz\";var b=a", "var a=\"foo,{bar};baz\";" + "\nvar b=a"); // don't break before post inc/dec assertLineLength("var a=\"a\";a++;var b=\"bbb\";", "var a=\"a\";a++;\n" + "var b=\"bbb\""); } private void assertLineLength(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, 10)); } public void testParsePrintParse() { testReparse("3;"); testReparse("var a = b;"); testReparse("var x, y, z;"); testReparse("try { foo() } catch(e) { bar() }"); testReparse("try { foo() } catch(e) { bar() } finally { stuff() }"); testReparse("try { foo() } finally { stuff() }"); testReparse("throw 'me'"); testReparse("function foo(a) { return a + 4; }"); testReparse("function foo() { return; }"); testReparse("var a = function(a, b) { foo(); return a + b; }"); testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];"); testReparse("v = (5, 6, 7, 8)"); testReparse("d = 34.0; x = 0; y = .3; z = -22"); testReparse("d = -x; t = !x + ~y;"); testReparse("'hi'; /* just a test */ stuff(a,b) \n" + " foo(); // and another \n" + " bar();"); testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;"); testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5"); testReparse("a = (2 + 3) * 4;"); testReparse("a = 1 + (2 + 3) + 4;"); testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());"); testReparse("a = b | c || d ^ e " + "&& f & !g != h << i <= j < k >>> l > m * n % !o"); testReparse("a == b; a != b; a === b; a == b == a;" + " (a == b) == a; a == (b == a);"); testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;"); testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }"); testReparse("for (var i in a) b += i;"); testReparse("for (var i = 0; i < 10; i++){ b /= 2;" + " if (b == 2)break;else continue;}"); testReparse("for (x = 0; x < 10; x++) a /= 2;"); testReparse("for (;;) a++;"); testReparse("while(true) { blah(); }while(true) blah();"); testReparse("do stuff(); while(a>b);"); testReparse("[0, null, , true, false, this];"); testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');"); testReparse("new Foo; new Bar(a, b,c);"); testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;"); testReparse("delete foo['bar']; delete foo;"); testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };"); testReparse("switch(a) { case 2: case 3: stuff(); break;" + "case 4: morestuff(); break; default: done();}"); testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;"); testReparse("a.v = b.v; x['foo'] = y['zoo'];"); testReparse("'test' in x; 3 in x; a in x;"); testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'"); testReparse("x.__proto__;"); } private void testReparse(String code) { Compiler compiler = new Compiler(); Node parse1 = parse(code); Node parse2 = parse(new CodePrinter.Builder(parse1).build()); String explanation = parse1.checkTreeEquals(parse2); assertNull("\nExpected: " + compiler.toSource(parse1) + "\nResult: " + compiler.toSource(parse2) + "\n" + explanation, explanation); } public void testDoLoopIECompatiblity() { // Do loops within IFs cause syntax errors in IE6 and IE7. assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("function f(){if(e1)do foo();while(e2)else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("if(x){do{foo()}while(y)}else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x)do{foo()}while(y);else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x){do{foo()}while(y)}", "if(x){do foo();while(y)}"); assertPrint("if(x)do{foo()}while(y);", "if(x){do foo();while(y)}"); assertPrint("if(x)A:do{foo()}while(y);", "if(x){A:do foo();while(y)}"); assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);", "var i=0;a:do{b:do{i++;break b}while(0)}while(0)"); } public void testFunctionSafariCompatiblity() { // Functions within IFs cause syntax errors on Safari. assertPrint("function f(){if(e1){function goo(){return true}}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("function f(){if(e1)function goo(){return true}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("if(e1){function goo(){return true}}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)function goo(){return true}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)A:function goo(){return true}", "if(e1){A:function goo(){return true}}"); } public void testExponents() { assertPrintNumber("1", 1); assertPrintNumber("10", 10); assertPrintNumber("100", 100); assertPrintNumber("1E3", 1000); assertPrintNumber("1E4", 10000); assertPrintNumber("1E5", 100000); assertPrintNumber("-1", -1); assertPrintNumber("-10", -10); assertPrintNumber("-100", -100); assertPrintNumber("-1E3", -1000); assertPrintNumber("-12341234E4", -123412340000L); assertPrintNumber("1E18", 1000000000000000000L); assertPrintNumber("1E5", 100000.0); assertPrintNumber("100000.1", 100000.1); assertPrintNumber("1E-6", 0.000001); assertPrintNumber("-0x38d7ea4c68001", -0x38d7ea4c68001L); assertPrintNumber("0x38d7ea4c68001", 0x38d7ea4c68001L); } // Make sure to test as both a String and a Node, because // negative numbers do not parse consistently from strings. private void assertPrintNumber(String expected, double number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } private void assertPrintNumber(String expected, int number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } public void testDirectEval() { assertPrint("eval('1');", "eval(\"1\")"); } public void testIndirectEval() { Node n = parse("eval('1');"); assertPrintNode("eval(\"1\")", n); n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp( Node.DIRECT_EVAL, false); assertPrintNode("(0,eval)(\"1\")", n); } public void testFreeCall1() { assertPrint("foo(a);", "foo(a)"); assertPrint("x.foo(a);", "x.foo(a)"); } public void testFreeCall2() { Node n = parse("foo(a);"); assertPrintNode("foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.isCall()); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("foo(a)", n); } public void testFreeCall3() { Node n = parse("x.foo(a);"); assertPrintNode("x.foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.isCall()); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("(0,x.foo)(a)", n); } public void testPrintScript() { // Verify that SCRIPT nodes not marked as synthetic are printed as // blocks. Node ast = new Node(Token.SCRIPT, new Node(Token.EXPR_RESULT, Node.newString("f")), new Node(Token.EXPR_RESULT, Node.newString("g"))); String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build(); assertEquals("\"f\";\n\"g\";\n", result); } public void testObjectLit() { assertPrint("({x:1})", "({x:1})"); assertPrint("var x=({x:1})", "var x={x:1}"); assertPrint("var x={'x':1}", "var x={\"x\":1}"); assertPrint("var x={1:1}", "var x={1:1}"); assertPrint("({},42)+0", "({},42)+0"); } public void testObjectLit2() { assertPrint("var x={1:1}", "var x={1:1}"); assertPrint("var x={'1':1}", "var x={1:1}"); assertPrint("var x={'1.0':1}", "var x={\"1.0\":1}"); assertPrint("var x={1.5:1}", "var x={\"1.5\":1}"); } public void testObjectLit3() { assertPrint("var x={3E9:1}", "var x={3E9:1}"); assertPrint("var x={'3000000000':1}", // More than 31 bits "var x={3E9:1}"); assertPrint("var x={'3000000001':1}", "var x={3000000001:1}"); assertPrint("var x={'6000000001':1}", // More than 32 bits "var x={6000000001:1}"); assertPrint("var x={\"12345678901234567\":1}", // More than 53 bits "var x={\"12345678901234567\":1}"); } public void testObjectLit4() { // More than 128 bits. assertPrint( "var x={\"123456789012345671234567890123456712345678901234567\":1}", "var x={\"123456789012345671234567890123456712345678901234567\":1}"); } public void testGetter() { assertPrint("var x = {}", "var x={}"); assertPrint("var x = {get a() {return 1}}", "var x={get a(){return 1}}"); assertPrint( "var x = {get a() {}, get b(){}}", "var x={get a(){},get b(){}}"); assertPrint( "var x = {get 'a'() {return 1}}", "var x={get \"a\"(){return 1}}"); assertPrint( "var x = {get 1() {return 1}}", "var x={get 1(){return 1}}"); assertPrint( "var x = {get \"()\"() {return 1}}", "var x={get \"()\"(){return 1}}"); } public void testSetter() { assertPrint("var x = {}", "var x={}"); assertPrint( "var x = {set a(y) {return 1}}", "var x={set a(y){return 1}}"); assertPrint( "var x = {get 'a'() {return 1}}", "var x={get \"a\"(){return 1}}"); assertPrint( "var x = {set 1(y) {return 1}}", "var x={set 1(y){return 1}}"); assertPrint( "var x = {set \"(x)\"(y) {return 1}}", "var x={set \"(x)\"(y){return 1}}"); } public void testNegCollapse() { // Collapse the negative symbol on numbers at generation time, // to match the Rhino behavior. assertPrint("var x = - - 2;", "var x=2"); assertPrint("var x = - (2);", "var x=-2"); } public void testStrict() { String result = parsePrint("var x", false, false, 0, false, true); assertEquals("'use strict';var x", result); } public void testArrayLiteral() { assertPrint("var x = [,];","var x=[,]"); assertPrint("var x = [,,];","var x=[,,]"); assertPrint("var x = [,s,,];","var x=[,s,,]"); assertPrint("var x = [,s];","var x=[,s]"); assertPrint("var x = [s,];","var x=[s]"); } public void testZero() { assertPrint("var x ='\\0';", "var x=\"\\x00\""); assertPrint("var x ='\\x00';", "var x=\"\\x00\""); assertPrint("var x ='\\u0000';", "var x=\"\\x00\""); assertPrint("var x ='\\u00003';", "var x=\"\\x003\""); } public void testUnicode() { assertPrint("var x ='\\x0f';", "var x=\"\\u000f\""); assertPrint("var x ='\\x68';", "var x=\"h\""); assertPrint("var x ='\\x7f';", "var x=\"\\u007f\""); } public void testUnicodeKeyword() { // keyword "if" assertPrint("var \\u0069\\u0066 = 1;", "var i\\u0066=1"); // keyword "var" assertPrint("var v\\u0061\\u0072 = 1;", "var va\\u0072=1"); // all are keyword "while" assertPrint("var w\\u0068\\u0069\\u006C\\u0065 = 1;" + "\\u0077\\u0068il\\u0065 = 2;" + "\\u0077h\\u0069le = 3;", "var whil\\u0065=1;whil\\u0065=2;whil\\u0065=3"); } public void testNumericKeys() { assertPrint("var x = {010: 1};", "var x={8:1}"); assertPrint("var x = {'010': 1};", "var x={\"010\":1}"); assertPrint("var x = {0x10: 1};", "var x={16:1}"); assertPrint("var x = {'0x10': 1};", "var x={\"0x10\":1}"); // I was surprised at this result too. assertPrint("var x = {.2: 1};", "var x={\"0.2\":1}"); assertPrint("var x = {'.2': 1};", "var x={\".2\":1}"); assertPrint("var x = {0.2: 1};", "var x={\"0.2\":1}"); assertPrint("var x = {'0.2': 1};", "var x={\"0.2\":1}"); } public void testIssue582() { assertPrint("var x = -0.0;", "var x=-0"); } public void testIssue942() { assertPrint("var x = {0: 1};", "var x={0:1}"); } public void testIssue601() { assertPrint("'\\v' == 'v'", "\"\\v\"==\"v\""); assertPrint("'\\u000B' == '\\v'", "\"\\x0B\"==\"\\v\""); assertPrint("'\\x0B' == '\\v'", "\"\\x0B\"==\"\\v\""); } public void testIssue620() { assertPrint("alert(/ / / / /);", "alert(/ // / /)"); assertPrint("alert(/ // / /);", "alert(/ // / /)"); } public void testIssue5746867() { assertPrint("var a = { '$\\\\' : 5 };", "var a={\"$\\\\\":5}"); } public void testCommaSpacing() { assertPrint("var a = (b = 5, c = 5);", "var a=(b=5,c=5)"); assertPrettyPrint("var a = (b = 5, c = 5);", "var a = (b = 5, c = 5);\n"); } public void testManyCommas() { int numCommas = 10000; List<String> numbers = Lists.newArrayList("0", "1"); Node current = new Node(Token.COMMA, Node.newNumber(0), Node.newNumber(1)); for (int i = 2; i < numCommas; i++) { current = new Node(Token.COMMA, current); // 1000 is printed as 1E3, and screws up our test. int num = i % 1000; numbers.add(String.valueOf(num)); current.addChildToBack(Node.newNumber(num)); } String expected = Joiner.on(",").join(numbers); String actual = printNode(current).replace("\n", ""); assertEquals(expected, actual); } public void testManyAdds() { int numAdds = 10000; List<String> numbers = Lists.newArrayList("0", "1"); Node current = new Node(Token.ADD, Node.newNumber(0), Node.newNumber(1)); for (int i = 2; i < numAdds; i++) { current = new Node(Token.ADD, current); // 1000 is printed as 1E3, and screws up our test. int num = i % 1000; numbers.add(String.valueOf(num)); current.addChildToBack(Node.newNumber(num)); } String expected = Joiner.on("+").join(numbers); String actual = printNode(current).replace("\n", ""); assertEquals(expected, actual); } public void testMinusNegativeZero() { // Negative zero is weird, because we have to be able to distinguish // it from positive zero (there are some subtle differences in behavior). assertPrint("x- -0", "x- -0"); } public void testStringEscapeSequences() { // From the SingleEscapeCharacter grammar production. assertPrintSame("var x=\"\\b\""); assertPrintSame("var x=\"\\f\""); assertPrintSame("var x=\"\\n\""); assertPrintSame("var x=\"\\r\""); assertPrintSame("var x=\"\\t\""); assertPrintSame("var x=\"\\v\""); assertPrint("var x=\"\\\"\"", "var x='\"'"); assertPrint("var x=\"\\\'\"", "var x=\"'\""); // From the LineTerminator grammar assertPrint("var x=\"\\u000A\"", "var x=\"\\n\""); assertPrint("var x=\"\\u000D\"", "var x=\"\\r\""); assertPrintSame("var x=\"\\u2028\""); assertPrintSame("var x=\"\\u2029\""); // Now with regular expressions. assertPrintSame("var x=/\\b/"); assertPrintSame("var x=/\\f/"); assertPrintSame("var x=/\\n/"); assertPrintSame("var x=/\\r/"); assertPrintSame("var x=/\\t/"); assertPrintSame("var x=/\\v/"); assertPrintSame("var x=/\\u000A/"); assertPrintSame("var x=/\\u000D/"); assertPrintSame("var x=/\\u2028/"); assertPrintSame("var x=/\\u2029/"); } }
public void testGenericSignature1195() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Method m; JavaType t; m = Generic1195.class.getMethod("getList"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/List<Ljava/lang/String;>;", t.getGenericSignature()); m = Generic1195.class.getMethod("getMap"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", t.getGenericSignature()); m = Generic1195.class.getMethod("getGeneric"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>;", t.getGenericSignature()); }
com.fasterxml.jackson.databind.type.TestJavaType::testGenericSignature1195
src/test/java/com/fasterxml/jackson/databind/type/TestJavaType.java
56
src/test/java/com/fasterxml/jackson/databind/type/TestJavaType.java
testGenericSignature1195
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.JavaType; /** * Simple tests to verify that {@link JavaType} types work to * some degree */ public class TestJavaType extends BaseMapTest { static class BaseType { } static class SubType extends BaseType { } static enum MyEnum { A, B; } static enum MyEnum2 { A(1), B(2); private MyEnum2(int value) { } } // [databind#728] static class Issue728 { public <C extends CharSequence> C method(C input) { return null; } } public interface Generic1195 { public AtomicReference<String> getGeneric(); public List<String> getList(); public Map<String,String> getMap(); } public void testGenericSignature1195() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Method m; JavaType t; m = Generic1195.class.getMethod("getList"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/List<Ljava/lang/String;>;", t.getGenericSignature()); m = Generic1195.class.getMethod("getMap"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", t.getGenericSignature()); m = Generic1195.class.getMethod("getGeneric"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>;", t.getGenericSignature()); } /* /********************************************************** /* Test methods /********************************************************** */ public void testLocalType728() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Method m = Issue728.class.getMethod("method", CharSequence.class); assertNotNull(m); // Start with return type // first type-erased JavaType t = tf.constructType(m.getReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then generic t = tf.constructType(m.getGenericReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then parameter type t = tf.constructType(m.getParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); t = tf.constructType(m.getGenericParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); } public void testSimpleClass() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType baseType = tf.constructType(BaseType.class); assertSame(BaseType.class, baseType.getRawClass()); assertTrue(baseType.hasRawClass(BaseType.class)); assertFalse(baseType.isArrayType()); assertFalse(baseType.isContainerType()); assertFalse(baseType.isEnumType()); assertFalse(baseType.isInterface()); assertFalse(baseType.isPrimitive()); assertNull(baseType.getContentType()); assertNull(baseType.getValueHandler()); /* both narrow and widen just return type itself (exact, not just * equal) * (also note that widen/narrow wouldn't work on basic simple * class type otherwise) */ assertSame(baseType, baseType.narrowBy(BaseType.class)); assertSame(baseType, baseType.widenBy(BaseType.class)); // Also: no narrowing for simple types (but should there be?) try { baseType.narrowBy(SubType.class); } catch (IllegalArgumentException e) { verifyException(e, "should never be called"); } // Also, let's try assigning bogus handler /* baseType.setValueHandler("xyz"); // untyped assertEquals("xyz", baseType.getValueHandler()); // illegal to re-set try { baseType.setValueHandler("foobar"); fail("Shouldn't allow re-setting value handler"); } catch (IllegalStateException iae) { verifyException(iae, "Trying to reset"); } */ } public void testMapType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType keyT = tf.constructType(String.class); JavaType baseT = tf.constructType(BaseType.class); MapType mapT = MapType.construct(Map.class, keyT, baseT); assertNotNull(mapT); assertTrue(mapT.isContainerType()); // NOPs: assertSame(mapT, mapT.narrowContentsBy(BaseType.class)); assertSame(mapT, mapT.narrowKey(String.class)); assertTrue(mapT.equals(mapT)); assertFalse(mapT.equals(null)); assertFalse(mapT.equals("xyz")); MapType mapT2 = MapType.construct(HashMap.class, keyT, baseT); assertFalse(mapT.equals(mapT2)); // Also, must use map type constructor, not simple... try { SimpleType.construct(HashMap.class); } catch (IllegalArgumentException e) { verifyException(e, "for a Map"); } } public void testArrayType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType arrayT = ArrayType.construct(tf.constructType(String.class), null, null); assertNotNull(arrayT); assertTrue(arrayT.isContainerType()); // NOPs: assertSame(arrayT, arrayT.narrowContentsBy(String.class)); assertNotNull(arrayT.toString()); assertTrue(arrayT.equals(arrayT)); assertFalse(arrayT.equals(null)); assertFalse(arrayT.equals("xyz")); assertTrue(arrayT.equals(ArrayType.construct(tf.constructType(String.class), null, null))); assertFalse(arrayT.equals(ArrayType.construct(tf.constructType(Integer.class), null, null))); // Also, must NOT try to create using simple type try { SimpleType.construct(String[].class); } catch (IllegalArgumentException e) { verifyException(e, "for an array"); } } public void testCollectionType() { TypeFactory tf = TypeFactory.defaultInstance(); // List<String> JavaType collectionT = CollectionType.construct(List.class, tf.constructType(String.class)); assertNotNull(collectionT); assertTrue(collectionT.isContainerType()); // NOPs: assertSame(collectionT, collectionT.narrowContentsBy(String.class)); assertNotNull(collectionT.toString()); assertTrue(collectionT.equals(collectionT)); assertFalse(collectionT.equals(null)); assertFalse(collectionT.equals("xyz")); assertTrue(collectionT.equals(CollectionType.construct(List.class, tf.constructType(String.class)))); assertFalse(collectionT.equals(CollectionType.construct(Set.class, tf.constructType(String.class)))); // Also, must NOT try to create using simple type try { SimpleType.construct(ArrayList.class); } catch (IllegalArgumentException e) { verifyException(e, "for a Collection"); } } public void testEnumType() { TypeFactory tf = TypeFactory.defaultInstance(); assertTrue(tf.constructType(MyEnum.class).isEnumType()); assertTrue(tf.constructType(MyEnum2.class).isEnumType()); assertTrue(tf.constructType(MyEnum.A.getClass()).isEnumType()); assertTrue(tf.constructType(MyEnum2.A.getClass()).isEnumType()); } public void testClassKey() { ClassKey key = new ClassKey(String.class); assertEquals(0, key.compareTo(key)); assertTrue(key.equals(key)); assertFalse(key.equals(null)); assertFalse(key.equals("foo")); assertFalse(key.equals(new ClassKey(Integer.class))); assertEquals(String.class.getName(), key.toString()); } // [Issue#116] public void testJavaTypeAsJLRType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t1 = tf.constructType(getClass()); // should just get it back as-is: JavaType t2 = tf.constructType(t1); assertSame(t1, t2); } }
// You are a professional Java test case writer, please create a test case named `testGenericSignature1195` for the issue `JacksonDatabind-1194`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1194 // // ## Issue-Title: // Incorrect signature for generic type via `JavaType.getGenericSignature // // ## Issue-Description: // (see [FasterXML/jackson-modules-base#8](https://github.com/FasterXML/jackson-modules-base/issues/8) for background) // // // It looks like generic signature generation is missing one closing `>` character to produce: // // // // ``` // ()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;; // // ``` // // instead of expected // // // // ``` // ()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>; // // ``` // // that is, closing '>' is missing. // // // // public void testGenericSignature1195() throws Exception {
56
46
38
src/test/java/com/fasterxml/jackson/databind/type/TestJavaType.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1194 ## Issue-Title: Incorrect signature for generic type via `JavaType.getGenericSignature ## Issue-Description: (see [FasterXML/jackson-modules-base#8](https://github.com/FasterXML/jackson-modules-base/issues/8) for background) It looks like generic signature generation is missing one closing `>` character to produce: ``` ()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;; ``` instead of expected ``` ()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>; ``` that is, closing '>' is missing. ``` You are a professional Java test case writer, please create a test case named `testGenericSignature1195` for the issue `JacksonDatabind-1194`, utilizing the provided issue report information and the following function signature. ```java public void testGenericSignature1195() throws Exception { ```
38
[ "com.fasterxml.jackson.databind.type.ReferenceType" ]
15f1707f5eb0b9d6cebece154c25df4a7aae8d618c89e22ab738e0d1b2a6fc59
public void testGenericSignature1195() throws Exception
// You are a professional Java test case writer, please create a test case named `testGenericSignature1195` for the issue `JacksonDatabind-1194`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1194 // // ## Issue-Title: // Incorrect signature for generic type via `JavaType.getGenericSignature // // ## Issue-Description: // (see [FasterXML/jackson-modules-base#8](https://github.com/FasterXML/jackson-modules-base/issues/8) for background) // // // It looks like generic signature generation is missing one closing `>` character to produce: // // // // ``` // ()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;; // // ``` // // instead of expected // // // // ``` // ()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>; // // ``` // // that is, closing '>' is missing. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.JavaType; /** * Simple tests to verify that {@link JavaType} types work to * some degree */ public class TestJavaType extends BaseMapTest { static class BaseType { } static class SubType extends BaseType { } static enum MyEnum { A, B; } static enum MyEnum2 { A(1), B(2); private MyEnum2(int value) { } } // [databind#728] static class Issue728 { public <C extends CharSequence> C method(C input) { return null; } } public interface Generic1195 { public AtomicReference<String> getGeneric(); public List<String> getList(); public Map<String,String> getMap(); } public void testGenericSignature1195() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Method m; JavaType t; m = Generic1195.class.getMethod("getList"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/List<Ljava/lang/String;>;", t.getGenericSignature()); m = Generic1195.class.getMethod("getMap"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", t.getGenericSignature()); m = Generic1195.class.getMethod("getGeneric"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>;", t.getGenericSignature()); } /* /********************************************************** /* Test methods /********************************************************** */ public void testLocalType728() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Method m = Issue728.class.getMethod("method", CharSequence.class); assertNotNull(m); // Start with return type // first type-erased JavaType t = tf.constructType(m.getReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then generic t = tf.constructType(m.getGenericReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then parameter type t = tf.constructType(m.getParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); t = tf.constructType(m.getGenericParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); } public void testSimpleClass() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType baseType = tf.constructType(BaseType.class); assertSame(BaseType.class, baseType.getRawClass()); assertTrue(baseType.hasRawClass(BaseType.class)); assertFalse(baseType.isArrayType()); assertFalse(baseType.isContainerType()); assertFalse(baseType.isEnumType()); assertFalse(baseType.isInterface()); assertFalse(baseType.isPrimitive()); assertNull(baseType.getContentType()); assertNull(baseType.getValueHandler()); /* both narrow and widen just return type itself (exact, not just * equal) * (also note that widen/narrow wouldn't work on basic simple * class type otherwise) */ assertSame(baseType, baseType.narrowBy(BaseType.class)); assertSame(baseType, baseType.widenBy(BaseType.class)); // Also: no narrowing for simple types (but should there be?) try { baseType.narrowBy(SubType.class); } catch (IllegalArgumentException e) { verifyException(e, "should never be called"); } // Also, let's try assigning bogus handler /* baseType.setValueHandler("xyz"); // untyped assertEquals("xyz", baseType.getValueHandler()); // illegal to re-set try { baseType.setValueHandler("foobar"); fail("Shouldn't allow re-setting value handler"); } catch (IllegalStateException iae) { verifyException(iae, "Trying to reset"); } */ } public void testMapType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType keyT = tf.constructType(String.class); JavaType baseT = tf.constructType(BaseType.class); MapType mapT = MapType.construct(Map.class, keyT, baseT); assertNotNull(mapT); assertTrue(mapT.isContainerType()); // NOPs: assertSame(mapT, mapT.narrowContentsBy(BaseType.class)); assertSame(mapT, mapT.narrowKey(String.class)); assertTrue(mapT.equals(mapT)); assertFalse(mapT.equals(null)); assertFalse(mapT.equals("xyz")); MapType mapT2 = MapType.construct(HashMap.class, keyT, baseT); assertFalse(mapT.equals(mapT2)); // Also, must use map type constructor, not simple... try { SimpleType.construct(HashMap.class); } catch (IllegalArgumentException e) { verifyException(e, "for a Map"); } } public void testArrayType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType arrayT = ArrayType.construct(tf.constructType(String.class), null, null); assertNotNull(arrayT); assertTrue(arrayT.isContainerType()); // NOPs: assertSame(arrayT, arrayT.narrowContentsBy(String.class)); assertNotNull(arrayT.toString()); assertTrue(arrayT.equals(arrayT)); assertFalse(arrayT.equals(null)); assertFalse(arrayT.equals("xyz")); assertTrue(arrayT.equals(ArrayType.construct(tf.constructType(String.class), null, null))); assertFalse(arrayT.equals(ArrayType.construct(tf.constructType(Integer.class), null, null))); // Also, must NOT try to create using simple type try { SimpleType.construct(String[].class); } catch (IllegalArgumentException e) { verifyException(e, "for an array"); } } public void testCollectionType() { TypeFactory tf = TypeFactory.defaultInstance(); // List<String> JavaType collectionT = CollectionType.construct(List.class, tf.constructType(String.class)); assertNotNull(collectionT); assertTrue(collectionT.isContainerType()); // NOPs: assertSame(collectionT, collectionT.narrowContentsBy(String.class)); assertNotNull(collectionT.toString()); assertTrue(collectionT.equals(collectionT)); assertFalse(collectionT.equals(null)); assertFalse(collectionT.equals("xyz")); assertTrue(collectionT.equals(CollectionType.construct(List.class, tf.constructType(String.class)))); assertFalse(collectionT.equals(CollectionType.construct(Set.class, tf.constructType(String.class)))); // Also, must NOT try to create using simple type try { SimpleType.construct(ArrayList.class); } catch (IllegalArgumentException e) { verifyException(e, "for a Collection"); } } public void testEnumType() { TypeFactory tf = TypeFactory.defaultInstance(); assertTrue(tf.constructType(MyEnum.class).isEnumType()); assertTrue(tf.constructType(MyEnum2.class).isEnumType()); assertTrue(tf.constructType(MyEnum.A.getClass()).isEnumType()); assertTrue(tf.constructType(MyEnum2.A.getClass()).isEnumType()); } public void testClassKey() { ClassKey key = new ClassKey(String.class); assertEquals(0, key.compareTo(key)); assertTrue(key.equals(key)); assertFalse(key.equals(null)); assertFalse(key.equals("foo")); assertFalse(key.equals(new ClassKey(Integer.class))); assertEquals(String.class.getName(), key.toString()); } // [Issue#116] public void testJavaTypeAsJLRType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t1 = tf.constructType(getClass()); // should just get it back as-is: JavaType t2 = tf.constructType(t1); assertSame(t1, t2); } }
public void testEqualsAfterSerializationOfDerivedClass() throws IOException, ClassNotFoundException { final DerivedMultiKey<?> mk = new DerivedMultiKey<String>("A", "B"); // serialize final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(mk); out.close(); // deserialize final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bais); final DerivedMultiKey<?> mk2 = (DerivedMultiKey<?>)in.readObject(); in.close(); assertEquals(mk.hashCode(), mk2.hashCode()); }
org.apache.commons.collections4.keyvalue.MultiKeyTest::testEqualsAfterSerializationOfDerivedClass
src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java
292
src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java
testEqualsAfterSerializationOfDerivedClass
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * Unit tests for {@link org.apache.commons.collections4.keyvalue.MultiKey}. * * @version $Id$ */ public class MultiKeyTest extends TestCase { Integer ONE = Integer.valueOf(1); Integer TWO = Integer.valueOf(2); Integer THREE = Integer.valueOf(3); Integer FOUR = Integer.valueOf(4); Integer FIVE = Integer.valueOf(5); @Override public void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- public void testConstructors() throws Exception { MultiKey<Integer> mk; mk = new MultiKey<Integer>(ONE, TWO); assertTrue(Arrays.equals(new Object[] { ONE, TWO }, mk.getKeys())); mk = new MultiKey<Integer>(ONE, TWO, THREE); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE }, mk.getKeys())); mk = new MultiKey<Integer>(ONE, TWO, THREE, FOUR); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE, FOUR }, mk.getKeys())); mk = new MultiKey<Integer>(ONE, TWO, THREE, FOUR, FIVE); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE, FOUR, FIVE }, mk.getKeys())); mk = new MultiKey<Integer>(new Integer[] { THREE, FOUR, ONE, TWO }, false); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); } public void testConstructorsByArray() throws Exception { MultiKey<Integer> mk; Integer[] keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey<Integer>(keys); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys[3] = FIVE; // no effect assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys = new Integer[] {}; mk = new MultiKey<Integer>(keys); assertTrue(Arrays.equals(new Object[] {}, mk.getKeys())); keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey<Integer>(keys, true); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys[3] = FIVE; // no effect assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey<Integer>(keys, false); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); // change key - don't do this! // the hashcode of the MultiKey is now broken keys[3] = FIVE; assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, FIVE }, mk.getKeys())); } public void testConstructorsByArrayNull() throws Exception { final Integer[] keys = null; try { new MultiKey<Integer>(keys); fail(); } catch (final IllegalArgumentException ex) {} try { new MultiKey<Integer>(keys, true); fail(); } catch (final IllegalArgumentException ex) {} try { new MultiKey<Integer>(keys, false); fail(); } catch (final IllegalArgumentException ex) {} } public void testSize() { assertEquals(2, new MultiKey<Integer>(ONE, TWO).size()); assertEquals(2, new MultiKey<Object>(null, null).size()); assertEquals(3, new MultiKey<Integer>(ONE, TWO, THREE).size()); assertEquals(3, new MultiKey<Object>(null, null, null).size()); assertEquals(4, new MultiKey<Integer>(ONE, TWO, THREE, FOUR).size()); assertEquals(4, new MultiKey<Object>(null, null, null, null).size()); assertEquals(5, new MultiKey<Integer>(ONE, TWO, THREE, FOUR, FIVE).size()); assertEquals(5, new MultiKey<Object>(null, null, null, null, null).size()); assertEquals(0, new MultiKey<Object>(new Object[] {}).size()); assertEquals(1, new MultiKey<Integer>(new Integer[] { ONE }).size()); assertEquals(2, new MultiKey<Integer>(new Integer[] { ONE, TWO }).size()); assertEquals(7, new MultiKey<Integer>(new Integer[] { ONE, TWO, ONE, TWO, ONE, TWO, ONE }).size()); } public void testGetIndexed() { final MultiKey<Integer> mk = new MultiKey<Integer>(ONE, TWO); assertSame(ONE, mk.getKey(0)); assertSame(TWO, mk.getKey(1)); try { mk.getKey(-1); fail(); } catch (final IndexOutOfBoundsException ex) {} try { mk.getKey(2); fail(); } catch (final IndexOutOfBoundsException ex) {} } public void testGetKeysSimpleConstructor() { final MultiKey<Integer> mk = new MultiKey<Integer>(ONE, TWO); final Object[] array = mk.getKeys(); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testGetKeysArrayConstructorCloned() { final Integer[] keys = new Integer[] { ONE, TWO }; final MultiKey<Integer> mk = new MultiKey<Integer>(keys, true); final Object[] array = mk.getKeys(); assertTrue(array != keys); assertTrue(Arrays.equals(array, keys)); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testGetKeysArrayConstructorNonCloned() { final Integer[] keys = new Integer[] { ONE, TWO }; final MultiKey<Integer> mk = new MultiKey<Integer>(keys, false); final Object[] array = mk.getKeys(); assertTrue(array != keys); // still not equal assertTrue(Arrays.equals(array, keys)); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testHashCode() { final MultiKey<Integer> mk1 = new MultiKey<Integer>(ONE, TWO); final MultiKey<Integer> mk2 = new MultiKey<Integer>(ONE, TWO); final MultiKey<Object> mk3 = new MultiKey<Object>(ONE, "TWO"); assertTrue(mk1.hashCode() == mk1.hashCode()); assertTrue(mk1.hashCode() == mk2.hashCode()); assertTrue(mk1.hashCode() != mk3.hashCode()); final int total = (0 ^ ONE.hashCode()) ^ TWO.hashCode(); assertEquals(total, mk1.hashCode()); } public void testEquals() { final MultiKey<Integer> mk1 = new MultiKey<Integer>(ONE, TWO); final MultiKey<Integer> mk2 = new MultiKey<Integer>(ONE, TWO); final MultiKey<Object> mk3 = new MultiKey<Object>(ONE, "TWO"); assertEquals(mk1, mk1); assertEquals(mk1, mk2); assertFalse(mk1.equals(mk3)); assertFalse(mk1.equals("")); assertFalse(mk1.equals(null)); } static class SystemHashCodeSimulatingKey implements Serializable { private static final long serialVersionUID = -1736147315703444603L; private final String name; private int hashCode = 1; public SystemHashCodeSimulatingKey(final String name) { this.name = name; } @Override public boolean equals(final Object obj) { return obj instanceof SystemHashCodeSimulatingKey && name.equals(((SystemHashCodeSimulatingKey)obj).name); } @Override public int hashCode() { return hashCode; } private Object readResolve() { hashCode=2; // simulate different hashCode after deserialization in another process return this; } } public void testEqualsAfterSerialization() throws IOException, ClassNotFoundException { SystemHashCodeSimulatingKey sysKey = new SystemHashCodeSimulatingKey("test"); final MultiKey<?> mk = new MultiKey<Object>(ONE, sysKey); final Map<MultiKey<?>, Integer> map = new HashMap<MultiKey<?>, Integer>(); map.put(mk, TWO); // serialize final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(sysKey); out.writeObject(map); out.close(); // deserialize final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bais); sysKey = (SystemHashCodeSimulatingKey)in.readObject(); // simulate deserialization in another process final Map<?, ?> map2 = (Map<?, ?>) in.readObject(); in.close(); assertEquals(2, sysKey.hashCode()); // different hashCode now final MultiKey<?> mk2 = new MultiKey<Object>(ONE, sysKey); assertEquals(TWO, map2.get(mk2)); } static class DerivedMultiKey<T> extends MultiKey<T> { private static final long serialVersionUID = 1928896152249821416L; public DerivedMultiKey(T key1, T key2) { super(key1, key2); } public T getFirst() { return getKey(0); } public T getSecond() { return getKey(1); } } public void testEqualsAfterSerializationOfDerivedClass() throws IOException, ClassNotFoundException { final DerivedMultiKey<?> mk = new DerivedMultiKey<String>("A", "B"); // serialize final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(mk); out.close(); // deserialize final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bais); final DerivedMultiKey<?> mk2 = (DerivedMultiKey<?>)in.readObject(); in.close(); assertEquals(mk.hashCode(), mk2.hashCode()); } }
// You are a professional Java test case writer, please create a test case named `testEqualsAfterSerializationOfDerivedClass` for the issue `Collections-COLLECTIONS-576`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Collections-COLLECTIONS-576 // // ## Issue-Title: // MultiKey subclassing has deserialization problem since COLLECTIONS-266: either declare protected readResolve() or MultiKey must be final // // ## Issue-Description: // // MultiKey from collections 4 provides a transient hashCode and a **private** readResolve to resolve [~~COLLECTIONS-266~~](https://issues.apache.org/jira/browse/COLLECTIONS-266 "Issue with MultiKey when serialized/deserialized via RMI"): Issue with MultiKey when serialized/deserialized via RMI. // // // Unfortunately the solution does not work in case of **subclassing**: readResolve in MultiKey should be declared **protected** readResolve() to be called during deserialization of the subclass. Otherwise MultiKey must be final to avoid such subclassing. // // // **Testcase**: // // // **MultiKeySerializationTest.java** // // ``` // package de.ivu.test.common.collections4; // // import static org.junit.Assert.assertEquals; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.IOException; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // // import org.apache.commons.collections4.keyvalue.MultiKey; // import org.junit.Test; // // public class MultiKeySerializationTest { // // @Test // @SuppressWarnings("unchecked") // public void testReadResolveEqualHashCode() // throws IOException, ClassNotFoundException { // class MultiKey2<A, B> // extends MultiKey { // // private static final long serialVersionUID = 1928896152249821416L; // // public MultiKey2(A key1, B key2) { // super(key1, key2); // } // // public A getFirst() { // return (A) getKey(0); // } // // public B getSecond() { // return (B) getKey(1); // } // // // FIXME: MultiKey should either declare protected readResolve() or must be final. // } // MultiKey2<String, String> one = new MultiKey2<>("bla", "blub"); // System.out.println(one.hashCode()); // ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); // ObjectOutputStream out = new ObjectOutputStream(byteOut); // out.writeObject(one); // out.close(); // byte[] serialized = byteOut.toByteArray(); // ByteArrayInputStream byteIn = new ByteArrayInputStream(serialized); // ObjectInputStream in = new ObjectInputStream(byteIn); // MultiKey2<String, String> two = (MultiKey2<String, String>) in.readObject(); // System.out.println(two.hashCode()); // assertEquals("hashCode must be equal - please check for protected readResolve in MultiKey\*", one.hashCode(), // two.hashCode()); // } // } // // ``` // // // **Fix:** // // // **MultiKey.java** // // ``` // @@ -274,7 +274,7 @@ // public void testEqualsAfterSerializationOfDerivedClass() throws IOException, ClassNotFoundException {
292
26
275
src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java
src/test/java
```markdown ## Issue-ID: Collections-COLLECTIONS-576 ## Issue-Title: MultiKey subclassing has deserialization problem since COLLECTIONS-266: either declare protected readResolve() or MultiKey must be final ## Issue-Description: MultiKey from collections 4 provides a transient hashCode and a **private** readResolve to resolve [~~COLLECTIONS-266~~](https://issues.apache.org/jira/browse/COLLECTIONS-266 "Issue with MultiKey when serialized/deserialized via RMI"): Issue with MultiKey when serialized/deserialized via RMI. Unfortunately the solution does not work in case of **subclassing**: readResolve in MultiKey should be declared **protected** readResolve() to be called during deserialization of the subclass. Otherwise MultiKey must be final to avoid such subclassing. **Testcase**: **MultiKeySerializationTest.java** ``` package de.ivu.test.common.collections4; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.commons.collections4.keyvalue.MultiKey; import org.junit.Test; public class MultiKeySerializationTest { @Test @SuppressWarnings("unchecked") public void testReadResolveEqualHashCode() throws IOException, ClassNotFoundException { class MultiKey2<A, B> extends MultiKey { private static final long serialVersionUID = 1928896152249821416L; public MultiKey2(A key1, B key2) { super(key1, key2); } public A getFirst() { return (A) getKey(0); } public B getSecond() { return (B) getKey(1); } // FIXME: MultiKey should either declare protected readResolve() or must be final. } MultiKey2<String, String> one = new MultiKey2<>("bla", "blub"); System.out.println(one.hashCode()); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(one); out.close(); byte[] serialized = byteOut.toByteArray(); ByteArrayInputStream byteIn = new ByteArrayInputStream(serialized); ObjectInputStream in = new ObjectInputStream(byteIn); MultiKey2<String, String> two = (MultiKey2<String, String>) in.readObject(); System.out.println(two.hashCode()); assertEquals("hashCode must be equal - please check for protected readResolve in MultiKey\*", one.hashCode(), two.hashCode()); } } ``` **Fix:** **MultiKey.java** ``` @@ -274,7 +274,7 @@ ``` You are a professional Java test case writer, please create a test case named `testEqualsAfterSerializationOfDerivedClass` for the issue `Collections-COLLECTIONS-576`, utilizing the provided issue report information and the following function signature. ```java public void testEqualsAfterSerializationOfDerivedClass() throws IOException, ClassNotFoundException { ```
275
[ "org.apache.commons.collections4.keyvalue.MultiKey" ]
17672c8b1b39290675eea755b8b75fa120a2edb3265e497b9c7cb8422c0079db
public void testEqualsAfterSerializationOfDerivedClass() throws IOException, ClassNotFoundException
// You are a professional Java test case writer, please create a test case named `testEqualsAfterSerializationOfDerivedClass` for the issue `Collections-COLLECTIONS-576`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Collections-COLLECTIONS-576 // // ## Issue-Title: // MultiKey subclassing has deserialization problem since COLLECTIONS-266: either declare protected readResolve() or MultiKey must be final // // ## Issue-Description: // // MultiKey from collections 4 provides a transient hashCode and a **private** readResolve to resolve [~~COLLECTIONS-266~~](https://issues.apache.org/jira/browse/COLLECTIONS-266 "Issue with MultiKey when serialized/deserialized via RMI"): Issue with MultiKey when serialized/deserialized via RMI. // // // Unfortunately the solution does not work in case of **subclassing**: readResolve in MultiKey should be declared **protected** readResolve() to be called during deserialization of the subclass. Otherwise MultiKey must be final to avoid such subclassing. // // // **Testcase**: // // // **MultiKeySerializationTest.java** // // ``` // package de.ivu.test.common.collections4; // // import static org.junit.Assert.assertEquals; // // import java.io.ByteArrayInputStream; // import java.io.ByteArrayOutputStream; // import java.io.IOException; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // // import org.apache.commons.collections4.keyvalue.MultiKey; // import org.junit.Test; // // public class MultiKeySerializationTest { // // @Test // @SuppressWarnings("unchecked") // public void testReadResolveEqualHashCode() // throws IOException, ClassNotFoundException { // class MultiKey2<A, B> // extends MultiKey { // // private static final long serialVersionUID = 1928896152249821416L; // // public MultiKey2(A key1, B key2) { // super(key1, key2); // } // // public A getFirst() { // return (A) getKey(0); // } // // public B getSecond() { // return (B) getKey(1); // } // // // FIXME: MultiKey should either declare protected readResolve() or must be final. // } // MultiKey2<String, String> one = new MultiKey2<>("bla", "blub"); // System.out.println(one.hashCode()); // ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); // ObjectOutputStream out = new ObjectOutputStream(byteOut); // out.writeObject(one); // out.close(); // byte[] serialized = byteOut.toByteArray(); // ByteArrayInputStream byteIn = new ByteArrayInputStream(serialized); // ObjectInputStream in = new ObjectInputStream(byteIn); // MultiKey2<String, String> two = (MultiKey2<String, String>) in.readObject(); // System.out.println(two.hashCode()); // assertEquals("hashCode must be equal - please check for protected readResolve in MultiKey\*", one.hashCode(), // two.hashCode()); // } // } // // ``` // // // **Fix:** // // // **MultiKey.java** // // ``` // @@ -274,7 +274,7 @@ //
Collections
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * Unit tests for {@link org.apache.commons.collections4.keyvalue.MultiKey}. * * @version $Id$ */ public class MultiKeyTest extends TestCase { Integer ONE = Integer.valueOf(1); Integer TWO = Integer.valueOf(2); Integer THREE = Integer.valueOf(3); Integer FOUR = Integer.valueOf(4); Integer FIVE = Integer.valueOf(5); @Override public void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- public void testConstructors() throws Exception { MultiKey<Integer> mk; mk = new MultiKey<Integer>(ONE, TWO); assertTrue(Arrays.equals(new Object[] { ONE, TWO }, mk.getKeys())); mk = new MultiKey<Integer>(ONE, TWO, THREE); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE }, mk.getKeys())); mk = new MultiKey<Integer>(ONE, TWO, THREE, FOUR); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE, FOUR }, mk.getKeys())); mk = new MultiKey<Integer>(ONE, TWO, THREE, FOUR, FIVE); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE, FOUR, FIVE }, mk.getKeys())); mk = new MultiKey<Integer>(new Integer[] { THREE, FOUR, ONE, TWO }, false); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); } public void testConstructorsByArray() throws Exception { MultiKey<Integer> mk; Integer[] keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey<Integer>(keys); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys[3] = FIVE; // no effect assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys = new Integer[] {}; mk = new MultiKey<Integer>(keys); assertTrue(Arrays.equals(new Object[] {}, mk.getKeys())); keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey<Integer>(keys, true); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys[3] = FIVE; // no effect assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey<Integer>(keys, false); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); // change key - don't do this! // the hashcode of the MultiKey is now broken keys[3] = FIVE; assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, FIVE }, mk.getKeys())); } public void testConstructorsByArrayNull() throws Exception { final Integer[] keys = null; try { new MultiKey<Integer>(keys); fail(); } catch (final IllegalArgumentException ex) {} try { new MultiKey<Integer>(keys, true); fail(); } catch (final IllegalArgumentException ex) {} try { new MultiKey<Integer>(keys, false); fail(); } catch (final IllegalArgumentException ex) {} } public void testSize() { assertEquals(2, new MultiKey<Integer>(ONE, TWO).size()); assertEquals(2, new MultiKey<Object>(null, null).size()); assertEquals(3, new MultiKey<Integer>(ONE, TWO, THREE).size()); assertEquals(3, new MultiKey<Object>(null, null, null).size()); assertEquals(4, new MultiKey<Integer>(ONE, TWO, THREE, FOUR).size()); assertEquals(4, new MultiKey<Object>(null, null, null, null).size()); assertEquals(5, new MultiKey<Integer>(ONE, TWO, THREE, FOUR, FIVE).size()); assertEquals(5, new MultiKey<Object>(null, null, null, null, null).size()); assertEquals(0, new MultiKey<Object>(new Object[] {}).size()); assertEquals(1, new MultiKey<Integer>(new Integer[] { ONE }).size()); assertEquals(2, new MultiKey<Integer>(new Integer[] { ONE, TWO }).size()); assertEquals(7, new MultiKey<Integer>(new Integer[] { ONE, TWO, ONE, TWO, ONE, TWO, ONE }).size()); } public void testGetIndexed() { final MultiKey<Integer> mk = new MultiKey<Integer>(ONE, TWO); assertSame(ONE, mk.getKey(0)); assertSame(TWO, mk.getKey(1)); try { mk.getKey(-1); fail(); } catch (final IndexOutOfBoundsException ex) {} try { mk.getKey(2); fail(); } catch (final IndexOutOfBoundsException ex) {} } public void testGetKeysSimpleConstructor() { final MultiKey<Integer> mk = new MultiKey<Integer>(ONE, TWO); final Object[] array = mk.getKeys(); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testGetKeysArrayConstructorCloned() { final Integer[] keys = new Integer[] { ONE, TWO }; final MultiKey<Integer> mk = new MultiKey<Integer>(keys, true); final Object[] array = mk.getKeys(); assertTrue(array != keys); assertTrue(Arrays.equals(array, keys)); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testGetKeysArrayConstructorNonCloned() { final Integer[] keys = new Integer[] { ONE, TWO }; final MultiKey<Integer> mk = new MultiKey<Integer>(keys, false); final Object[] array = mk.getKeys(); assertTrue(array != keys); // still not equal assertTrue(Arrays.equals(array, keys)); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testHashCode() { final MultiKey<Integer> mk1 = new MultiKey<Integer>(ONE, TWO); final MultiKey<Integer> mk2 = new MultiKey<Integer>(ONE, TWO); final MultiKey<Object> mk3 = new MultiKey<Object>(ONE, "TWO"); assertTrue(mk1.hashCode() == mk1.hashCode()); assertTrue(mk1.hashCode() == mk2.hashCode()); assertTrue(mk1.hashCode() != mk3.hashCode()); final int total = (0 ^ ONE.hashCode()) ^ TWO.hashCode(); assertEquals(total, mk1.hashCode()); } public void testEquals() { final MultiKey<Integer> mk1 = new MultiKey<Integer>(ONE, TWO); final MultiKey<Integer> mk2 = new MultiKey<Integer>(ONE, TWO); final MultiKey<Object> mk3 = new MultiKey<Object>(ONE, "TWO"); assertEquals(mk1, mk1); assertEquals(mk1, mk2); assertFalse(mk1.equals(mk3)); assertFalse(mk1.equals("")); assertFalse(mk1.equals(null)); } static class SystemHashCodeSimulatingKey implements Serializable { private static final long serialVersionUID = -1736147315703444603L; private final String name; private int hashCode = 1; public SystemHashCodeSimulatingKey(final String name) { this.name = name; } @Override public boolean equals(final Object obj) { return obj instanceof SystemHashCodeSimulatingKey && name.equals(((SystemHashCodeSimulatingKey)obj).name); } @Override public int hashCode() { return hashCode; } private Object readResolve() { hashCode=2; // simulate different hashCode after deserialization in another process return this; } } public void testEqualsAfterSerialization() throws IOException, ClassNotFoundException { SystemHashCodeSimulatingKey sysKey = new SystemHashCodeSimulatingKey("test"); final MultiKey<?> mk = new MultiKey<Object>(ONE, sysKey); final Map<MultiKey<?>, Integer> map = new HashMap<MultiKey<?>, Integer>(); map.put(mk, TWO); // serialize final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(sysKey); out.writeObject(map); out.close(); // deserialize final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bais); sysKey = (SystemHashCodeSimulatingKey)in.readObject(); // simulate deserialization in another process final Map<?, ?> map2 = (Map<?, ?>) in.readObject(); in.close(); assertEquals(2, sysKey.hashCode()); // different hashCode now final MultiKey<?> mk2 = new MultiKey<Object>(ONE, sysKey); assertEquals(TWO, map2.get(mk2)); } static class DerivedMultiKey<T> extends MultiKey<T> { private static final long serialVersionUID = 1928896152249821416L; public DerivedMultiKey(T key1, T key2) { super(key1, key2); } public T getFirst() { return getKey(0); } public T getSecond() { return getKey(1); } } public void testEqualsAfterSerializationOfDerivedClass() throws IOException, ClassNotFoundException { final DerivedMultiKey<?> mk = new DerivedMultiKey<String>("A", "B"); // serialize final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(mk); out.close(); // deserialize final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bais); final DerivedMultiKey<?> mk2 = (DerivedMultiKey<?>)in.readObject(); in.close(); assertEquals(mk.hashCode(), mk2.hashCode()); } }
public void testIssue931() { collapsePropertiesOnExternTypes = true; testSame( "function f() {\n" + " return function () {\n" + " var args = arguments;\n" + " setTimeout(function() { alert(args); }, 0);\n" + " }\n" + "};\n"); }
com.google.javascript.jscomp.CollapsePropertiesTest::testIssue931
test/com/google/javascript/jscomp/CollapsePropertiesTest.java
1,107
test/com/google/javascript/jscomp/CollapsePropertiesTest.java
testIssue931
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.jscomp.CollapseProperties.UNSAFE_THIS; import com.google.javascript.rhino.Node; /** * Tests for {@link CollapseProperties}. * */ public class CollapsePropertiesTest extends CompilerTestCase { private static String EXTERNS = "var window;\n" + "function alert(s) {}\n" + "function parseInt(s) {}\n" + "/** @constructor */ function String() {};\n" + "var arguments"; private boolean collapsePropertiesOnExternTypes = false; public CollapsePropertiesTest() { super(EXTERNS); } @Override public CompilerPass getProcessor(Compiler compiler) { return new CollapseProperties( compiler, collapsePropertiesOnExternTypes, true); } @Override public void setUp() { enableLineNumberCheck(true); enableNormalize(true); } @Override public int getNumRepetitions() { return 1; } public void testCollapse() { test("var a = {}; a.b = {}; var c = a.b;", "var a$b = {}; var c = a$b"); } public void testMultiLevelCollapse() { test("var a = {}; a.b = {}; a.b.c = {}; var d = a.b.c;", "var a$b$c = {}; var d = a$b$c;"); } public void testDecrement() { test("var a = {}; a.b = 5; a.b--; a.b = 5", "var a$b = 5; a$b--; a$b = 5"); } public void testIncrement() { test("var a = {}; a.b = 5; a.b++; a.b = 5", "var a$b = 5; a$b++; a$b = 5"); } public void testObjLitDeclaration() { test("var a = {b: {}, c: {}}; var d = a.b; var e = a.c", "var a$b = {}; var a$c = {}; var d = a$b; var e = a$c"); } public void testObjLitDeclarationWithGet1() { testSame("var a = {get b(){}};"); } public void testObjLitDeclarationWithGet2() { test("var a = {b: {}, get c(){}}; var d = a.b; var e = a.c", "var a$b = {};var a = {get c(){}};var d = a$b; var e = a.c"); } public void testObjLitDeclarationWithGet3() { test("var a = {b: {get c() { return 3; }}};", "var a$b = {get c() { return 3; }};"); } public void testObjLitDeclarationWithSet1() { testSame("var a = {set b(a){}};"); } public void testObjLitDeclarationWithSet2() { test("var a = {b: {}, set c(a){}}; var d = a.b; var e = a.c", "var a$b = {};var a = {set c(a){}};var d = a$b; var e = a.c"); } public void testObjLitDeclarationWithSet3() { test("var a = {b: {set c(d) {}}};", "var a$b = {set c(d) {}};"); } public void testObjLitDeclarationWithGetAndSet1() { test("var a = {b: {get c() { return 3; },set c(d) {}}};", "var a$b = {get c() { return 3; },set c(d) {}};"); } public void testObjLitDeclarationWithDuplicateKeys() { test("var a = {b: 0, b: 1}; var c = a.b;", "var a$b = 0; var a$b = 1; var c = a$b;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testObjLitAssignmentDepth1() { test("var a = {b: {}, c: {}}; var d = a.b; var e = a.c", "var a$b = {}; var a$c = {}; var d = a$b; var e = a$c"); } public void testObjLitAssignmentDepth2() { test("var a = {}; a.b = {c: {}, d: {}}; var e = a.b.c; var f = a.b.d", "var a$b$c = {}; var a$b$d = {}; var e = a$b$c; var f = a$b$d"); } public void testObjLitAssignmentDepth3() { test("var a = {}; a.b = {}; a.b.c = {d: 1, e: 2}; var f = a.b.c.d", "var a$b$c$d = 1; var a$b$c$e = 2; var f = a$b$c$d"); } public void testObjLitAssignmentDepth4() { test("var a = {}; a.b = {}; a.b.c = {}; a.b.c.d = {e: 1, f: 2}; " + "var g = a.b.c.d.e", "var a$b$c$d$e = 1; var a$b$c$d$f = 2; var g = a$b$c$d$e"); } public void testGlobalObjectDeclaredToPreserveItsPreviousValue1() { test("var a = a ? a : {}; a.c = 1;", "var a = a ? a : {}; var a$c = 1;"); } public void testGlobalObjectDeclaredToPreserveItsPreviousValue2() { test("var a = a || {}; a.c = 1;", "var a = a || {}; var a$c = 1;"); } public void testGlobalObjectDeclaredToPreserveItsPreviousValue3() { test("var a = a || {get b() {}}; a.c = 1;", "var a = a || {get b() {}}; var a$c = 1;"); } public void testGlobalObjectNameInBooleanExpressionDepth1_1() { test("var a = {b: 0}; a.c = 1; if (a) x();", "var a$b = 0; var a = {}; var a$c = 1; if (a) x();"); } public void testGlobalObjectNameInBooleanExpressionDepth1_2() { test("var a = {b: 0}; a.c = 1; if (!(a && a.c)) x();", "var a$b = 0; var a = {}; var a$c = 1; if (!(a && a$c)) x();"); } public void testGlobalObjectNameInBooleanExpressionDepth1_3() { test("var a = {b: 0}; a.c = 1; while (a || a.c) x();", "var a$b = 0; var a = {}; var a$c = 1; while (a || a$c) x();"); } public void testGlobalObjectNameInBooleanExpressionDepth1_4() { testSame("var a = {}; a.c = 1; var d = a || {}; a.c;"); } public void testGlobalObjectNameInBooleanExpressionDepth1_5() { testSame("var a = {}; a.c = 1; var d = a.c || a; a.c;"); } public void testGlobalObjectNameInBooleanExpressionDepth1_6() { test("var a = {b: 0}; a.c = 1; var d = !(a.c || a); a.c;", "var a$b = 0; var a = {}; var a$c = 1; var d = !(a$c || a); a$c;"); } public void testGlobalObjectNameInBooleanExpressionDepth2() { test("var a = {b: {}}; a.b.c = 1; if (a.b) x(a.b.c);", "var a$b = {}; var a$b$c = 1; if (a$b) x(a$b$c);"); } public void testGlobalObjectNameInBooleanExpressionDepth3() { // TODO(user): Make CollapseProperties even more aggressive so that // a$b.z gets collapsed. Right now, it doesn't get collapsed because the // expression (a.b && a.b.c) could return a.b. But since it returns a.b iff // a.b *is* safely collapsible, the Boolean logic should be smart enough to // only consider the right side of the && as aliasing. test("var a = {}; a.b = {}; /** @constructor */ a.b.c = function(){};" + " a.b.z = 1; var d = a.b && a.b.c;", "var a$b = {}; var a$b$c = function(){};" + " a$b.z = 1; var d = a$b && a$b$c;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testGlobalFunctionNameInBooleanExpressionDepth1() { test("function a() {} a.c = 1; if (a) x(a.c);", "function a() {} var a$c = 1; if (a) x(a$c);"); } public void testGlobalFunctionNameInBooleanExpressionDepth2() { test("var a = {b: function(){}}; a.b.c = 1; if (a.b) x(a.b.c);", "var a$b = function(){}; var a$b$c = 1; if (a$b) x(a$b$c);"); } public void testAliasCreatedForObjectDepth1_1() { // An object's properties are not collapsed if the object is referenced // in a such a way that an alias is created for it. testSame("var a = {b: 0}; var c = a; c.b = 1; a.b == c.b;"); } public void testAliasCreatedForObjectDepth1_2() { testSame("var a = {b: 0}; f(a); a.b;"); } public void testAliasCreatedForObjectDepth1_3() { testSame("var a = {b: 0}; new f(a); a.b;"); } public void testAliasCreatedForObjectDepth2_1() { test("var a = {}; a.b = {c: 0}; var d = a.b; a.b.c == d.c;", "var a$b = {c: 0}; var d = a$b; a$b.c == d.c;"); } public void testAliasCreatedForObjectDepth2_2() { test("var a = {}; a.b = {c: 0}; for (var p in a.b) { e(a.b[p]); }", "var a$b = {c: 0}; for (var p in a$b) { e(a$b[p]); }"); } public void testAliasCreatedForEnumDepth1_1() { // An enum's values are always collapsed, even if the enum object is // referenced in a such a way that an alias is created for it. test("/** @enum */ var a = {b: 0}; var c = a; c.b = 1; a.b != c.b;", "var a$b = 0; var a = {b: a$b}; var c = a; c.b = 1; a$b != c.b;"); } public void testAliasCreatedForEnumDepth1_2() { test("/** @enum */ var a = {b: 0}; f(a); a.b;", "var a$b = 0; var a = {b: a$b}; f(a); a$b;"); } public void testAliasCreatedForEnumDepth1_3() { test("/** @enum */ var a = {b: 0}; new f(a); a.b;", "var a$b = 0; var a = {b: a$b}; new f(a); a$b;"); } public void testAliasCreatedForEnumDepth1_4() { test("/** @enum */ var a = {b: 0}; for (var p in a) { f(a[p]); }", "var a$b = 0; var a = {b: a$b}; for (var p in a) { f(a[p]); }"); } public void testAliasCreatedForEnumDepth2_1() { test("var a = {}; /** @enum */ a.b = {c: 0};" + "var d = a.b; d.c = 1; a.b.c != d.c;", "var a$b$c = 0; var a$b = {c: a$b$c};" + "var d = a$b; d.c = 1; a$b$c != d.c;"); } public void testAliasCreatedForEnumDepth2_2() { test("var a = {}; /** @enum */ a.b = {c: 0};" + "for (var p in a.b) { f(a.b[p]); }", "var a$b$c = 0; var a$b = {c: a$b$c};" + "for (var p in a$b) { f(a$b[p]); }"); } public void testAliasCreatedForEnumDepth2_3() { test("var a = {}; var d = a; /** @enum */ a.b = {c: 0};" + "for (var p in a.b) { f(a.b[p]); }", "var a = {}; var d = a; var a$b$c = 0; var a$b = {c: a$b$c};" + "for (var p in a$b) { f(a$b[p]); }", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForEnumOfObjects() { test("var a = {}; " + "/** @enum {Object} */ a.b = {c: {d: 1}}; a.b.c;" + "searchEnum(a.b);", "var a$b$c = {d: 1};var a$b = {c: a$b$c}; a$b$c; " + "searchEnum(a$b)"); } public void testAliasCreatedForEnumOfObjects2() { test("var a = {}; " + "/** @enum {Object} */ a.b = {c: {d: 1}}; a.b.c.d;" + "searchEnum(a.b);", "var a$b$c = {d: 1};var a$b = {c: a$b$c}; a$b$c.d; " + "searchEnum(a$b)"); } public void testAliasCreatedForPropertyOfEnumOfObjects() { test("var a = {}; " + "/** @enum {Object} */ a.b = {c: {d: 1}}; a.b.c;" + "searchEnum(a.b.c);", "var a$b$c = {d: 1}; a$b$c; searchEnum(a$b$c);"); } public void testAliasCreatedForPropertyOfEnumOfObjects2() { test("var a = {}; " + "/** @enum {Object} */ a.b = {c: {d: 1}}; a.b.c.d;" + "searchEnum(a.b.c);", "var a$b$c = {d: 1}; a$b$c.d; searchEnum(a$b$c);"); } public void testMisusedEnumTag() { testSame("var a = {}; var d = a; a.b = function() {};" + "/** @enum */ a.b.c = 0; a.b.c;"); } public void testMisusedConstructorTag() { testSame("var a = {}; var d = a; a.b = function() {};" + "/** @constructor */ a.b.c = 0; a.b.c;"); } public void testAliasCreatedForFunctionDepth1_1() { testSame("var a = function(){}; a.b = 1; var c = a; c.b = 2; a.b != c.b;"); } public void testAliasCreatedForCtorDepth1_1() { // A constructor's properties *are* collapsed even if the function is // referenced in a such a way that an alias is created for it, // since a function with custom properties is considered a class and its // non-prototype properties are considered static methods and variables. // People don't typically iterate through static members of a class or // refer to them using an alias for the class name. test("/** @constructor */ var a = function(){}; a.b = 1; " + "var c = a; c.b = 2; a.b != c.b;", "var a = function(){}; var a$b = 1; var c = a; c.b = 2; a$b != c.b;"); } public void testAliasCreatedForFunctionDepth1_2() { testSame("var a = function(){}; a.b = 1; f(a); a.b;"); } public void testAliasCreatedForCtorDepth1_2() { test("/** @constructor */ var a = function(){}; a.b = 1; f(a); a.b;", "var a = function(){}; var a$b = 1; f(a); a$b;"); } public void testAliasCreatedForFunctionDepth1_3() { testSame("var a = function(){}; a.b = 1; new f(a); a.b;"); } public void testAliasCreatedForCtorDepth1_3() { test("/** @constructor */ var a = function(){}; a.b = 1; new f(a); a.b;", "var a = function(){}; var a$b = 1; new f(a); a$b;"); } public void testAliasCreatedForFunctionDepth2() { test( "var a = {}; a.b = function() {}; a.b.c = 1; var d = a.b;" + "a.b.c != d.c;", "var a$b = function() {}; a$b.c = 1; var d = a$b;" + "a$b.c != d.c;"); } public void testAliasCreatedForCtorDepth2() { test("var a = {}; /** @constructor */ a.b = function() {}; " + "a.b.c = 1; var d = a.b;" + "a.b.c != d.c;", "var a$b = function() {}; var a$b$c = 1; var d = a$b;" + "a$b$c != d.c;"); } public void testAliasCreatedForClassDepth1_1() { // A class's name is always collapsed, even if one of its prefixes is // referenced in a such a way that an alias is created for it. test("var a = {}; /** @constructor */ a.b = function(){};" + "var c = a; c.b = 0; a.b != c.b;", "var a = {}; var a$b = function(){};" + "var c = a; c.b = 0; a$b != c.b;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth1_2() { test("var a = {}; /** @constructor */ a.b = function(){}; f(a); a.b;", "var a = {}; var a$b = function(){}; f(a); a$b;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth1_3() { test("var a = {}; /** @constructor */ a.b = function(){}; new f(a); a.b;", "var a = {}; var a$b = function(){}; new f(a); a$b;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth2_1() { test("var a = {}; a.b = {}; /** @constructor */ a.b.c = function(){};" + "var d = a.b; a.b.c != d.c;", "var a$b = {}; var a$b$c = function(){};" + "var d = a$b; a$b$c != d.c;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth2_2() { test("var a = {}; a.b = {}; /** @constructor */ a.b.c = function(){};" + "f(a.b); a.b.c;", "var a$b = {}; var a$b$c = function(){}; f(a$b); a$b$c;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth2_3() { test("var a = {}; a.b = {}; /** @constructor */ a.b.c = function(){};" + "new f(a.b); a.b.c;", "var a$b = {}; var a$b$c = function(){}; new f(a$b); a$b$c;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassProperty() { test("var a = {}; /** @constructor */ a.b = function(){};" + "a.b.c = {d: 3}; new f(a.b.c); a.b.c.d;", "var a$b = function(){}; var a$b$c = {d:3}; new f(a$b$c); a$b$c.d;"); } public void testNestedObjLit() { test("var a = {}; a.b = {f: 0, c: {d: 1}}; var e = a.b.c.d", "var a$b$f = 0; var a$b$c$d = 1; var e = a$b$c$d;"); } public void testObjLitDeclarationUsedInSameVarList() { // The collapsed properties must defined in the same place in the var list // where they were originally defined (and not, for example, at the end). test("var a = {b: {}, c: {}}; var d = a.b; var e = a.c;", "var a$b = {}; var a$c = {}; var d = a$b; var e = a$c;"); } public void testPropGetInsideAnObjLit() { test("var x = {}; x.y = 1; var a = {}; a.b = {c: x.y}", "var x$y = 1; var a$b$c = x$y;"); } public void testObjLitWithQuotedKeyThatDoesNotGetRead() { test("var a = {}; a.b = {c: 0, 'd': 1}; var e = a.b.c;", "var a$b$c = 0; var a$b$d = 1; var e = a$b$c;"); } public void testObjLitWithQuotedKeyThatGetsRead() { test("var a = {}; a.b = {c: 0, 'd': 1}; var e = a.b['d'];", "var a$b = {c: 0, 'd': 1}; var e = a$b['d'];"); } public void testFunctionWithQuotedPropertyThatDoesNotGetRead() { test("var a = {}; a.b = function() {}; a.b['d'] = 1;", "var a$b = function() {}; a$b['d'] = 1;"); } public void testFunctionWithQuotedPropertyThatGetsRead() { test("var a = {}; a.b = function() {}; a.b['d'] = 1; f(a.b['d']);", "var a$b = function() {}; a$b['d'] = 1; f(a$b['d']);"); } public void testObjLitAssignedToMultipleNames1() { // An object literal that's assigned to multiple names isn't collapsed. testSame("var a = b = {c: 0, d: 1}; var e = a.c; var f = b.d;"); } public void testObjLitAssignedToMultipleNames2() { testSame("a = b = {c: 0, d: 1}; var e = a.c; var f = b.d;"); } public void testObjLitRedefinedInGlobalScope() { testSame("a = {b: 0}; a = {c: 1}; var d = a.b; var e = a.c;"); } public void testObjLitRedefinedInLocalScope() { test("var a = {}; a.b = {c: 0}; function d() { a.b = {c: 1}; } e(a.b.c);", "var a$b = {c: 0}; function d() { a$b = {c: 1}; } e(a$b.c);"); } public void testObjLitAssignedInTernaryExpression1() { testSame("a = x ? {b: 0} : d; var c = a.b;"); } public void testObjLitAssignedInTernaryExpression2() { testSame("a = x ? {b: 0} : {b: 1}; var c = a.b;"); } public void testGlobalVarSetToObjLitConditionally1() { testSame("var a; if (x) a = {b: 0}; var c = x ? a.b : 0;"); } public void testGlobalVarSetToObjLitConditionally1b() { test("if (x) var a = {b: 0}; var c = x ? a.b : 0;", "if (x) var a$b = 0; var c = x ? a$b : 0;"); } public void testGlobalVarSetToObjLitConditionally2() { test("if (x) var a = {b: 0}; var c = a.b; var d = a.c;", "if (x){ var a$b = 0; var a = {}; }var c = a$b; var d = a.c;"); } public void testGlobalVarSetToObjLitConditionally3() { testSame("var a; if (x) a = {b: 0}; else a = {b: 1}; var c = a.b;"); } public void testObjectPropertySetToObjLitConditionally() { test("var a = {}; if (x) a.b = {c: 0}; var d = a.b ? a.b.c : 0;", "if (x){ var a$b$c = 0; var a$b = {} } var d = a$b ? a$b$c : 0;"); } public void testFunctionPropertySetToObjLitConditionally() { test("function a() {} if (x) a.b = {c: 0}; var d = a.b ? a.b.c : 0;", "function a() {} if (x){ var a$b$c = 0; var a$b = {} }" + "var d = a$b ? a$b$c : 0;"); } public void testPrototypePropertySetToAnObjectLiteral() { test("var a = {b: function(){}}; a.b.prototype.c = {d: 0};", "var a$b = function(){}; a$b.prototype.c = {d: 0};"); } public void testObjectPropertyResetInLocalScope() { test("var z = {}; z.a = 0; function f() {z.a = 5; return z.a}", "var z$a = 0; function f() {z$a = 5; return z$a}"); } public void testFunctionPropertyResetInLocalScope() { test("function z() {} z.a = 0; function f() {z.a = 5; return z.a}", "function z() {} var z$a = 0; function f() {z$a = 5; return z$a}"); } public void testNamespaceResetInGlobalScope1() { test("var a = {}; /** @constructor */a.b = function() {}; a = {};", "var a = {}; var a$b = function() {}; a = {};", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testNamespaceResetInGlobalScope2() { test("var a = {}; a = {}; /** @constructor */a.b = function() {};", "var a = {}; a = {}; var a$b = function() {};", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testNamespaceResetInLocalScope1() { test("var a = {}; /** @constructor */a.b = function() {};" + " function f() { a = {}; }", "var a = {};var a$b = function() {};" + " function f() { a = {}; }", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testNamespaceResetInLocalScope2() { test("var a = {}; function f() { a = {}; }" + " /** @constructor */a.b = function() {};", "var a = {}; function f() { a = {}; }" + " var a$b = function() {};", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testNamespaceDefinedInLocalScope() { test("var a = {}; (function() { a.b = {}; })();" + " /** @constructor */a.b.c = function() {};", "var a$b; (function() { a$b = {}; })(); var a$b$c = function() {};"); } public void testAddPropertyToObjectInLocalScopeDepth1() { test("var a = {b: 0}; function f() { a.c = 5; return a.c; }", "var a$b = 0; var a$c; function f() { a$c = 5; return a$c; }"); } public void testAddPropertyToObjectInLocalScopeDepth2() { test("var a = {}; a.b = {}; (function() {a.b.c = 0;})(); x = a.b.c;", "var a$b$c; (function() {a$b$c = 0;})(); x = a$b$c;"); } public void testAddPropertyToFunctionInLocalScopeDepth1() { test("function a() {} function f() { a.c = 5; return a.c; }", "function a() {} var a$c; function f() { a$c = 5; return a$c; }"); } public void testAddPropertyToFunctionInLocalScopeDepth2() { test("var a = {}; a.b = function() {}; function f() {a.b.c = 0;}", "var a$b = function() {}; var a$b$c; function f() {a$b$c = 0;}"); } public void testAddPropertyToUncollapsibleObjectInLocalScopeDepth1() { testSame("var a = {}; var c = a; (function() {a.b = 0;})(); a.b;"); } public void testAddPropertyToUncollapsibleFunctionInLocalScopeDepth1() { testSame("function a() {} var c = a; (function() {a.b = 0;})(); a.b;"); } public void testAddPropertyToUncollapsibleNamedCtorInLocalScopeDepth1() { testSame( "/** @constructor */ function a() {} var a$b; var c = a; " + "(function() {a$b = 0;})(); a$b;"); } public void testAddPropertyToUncollapsibleCtorInLocalScopeDepth1() { test("/** @constructor */ var a = function() {}; var c = a; " + "(function() {a.b = 0;})(); a.b;", "var a = function() {}; var a$b; " + "var c = a; (function() {a$b = 0;})(); a$b;"); } public void testAddPropertyToUncollapsibleObjectInLocalScopeDepth2() { test("var a = {}; a.b = {}; var d = a.b;" + "(function() {a.b.c = 0;})(); a.b.c;", "var a$b = {}; var d = a$b;" + "(function() {a$b.c = 0;})(); a$b.c;"); } public void testAddPropertyToUncollapsibleFunctionInLocalScopeDepth2() { test("var a = {}; a.b = function (){}; var d = a.b;" + "(function() {a.b.c = 0;})(); a.b.c;", "var a$b = function (){}; var d = a$b;" + "(function() {a$b.c = 0;})(); a$b.c;"); } public void testAddPropertyToUncollapsibleCtorInLocalScopeDepth2() { test("var a = {}; /** @constructor */ a.b = function (){}; var d = a.b;" + "(function() {a.b.c = 0;})(); a.b.c;", "var a$b = function (){}; var a$b$c; var d = a$b;" + "(function() {a$b$c = 0;})(); a$b$c;"); } public void testPropertyOfChildFuncOfUncollapsibleObjectDepth1() { testSame("var a = {}; var c = a; a.b = function (){}; a.b.x = 0; a.b.x;"); } public void testPropertyOfChildFuncOfUncollapsibleObjectDepth2() { test("var a = {}; a.b = {}; var c = a.b;" + "a.b.c = function (){}; a.b.c.x = 0; a.b.c.x;", "var a$b = {}; var c = a$b;" + "a$b.c = function (){}; a$b.c.x = 0; a$b.c.x;"); } public void testAddPropertyToChildFuncOfUncollapsibleObjectInLocalScope() { testSame("var a = {}; a.b = function (){}; a.b.x = 0;" + "var c = a; (function() {a.b.y = 1;})(); a.b.x; a.b.y;"); } public void testAddPropertyToChildTypeOfUncollapsibleObjectInLocalScope() { test("var a = {}; /** @constructor */ a.b = function (){}; a.b.x = 0;" + "var c = a; (function() {a.b.y = 1;})(); a.b.x; a.b.y;", "var a = {}; var a$b = function (){}; var a$b$y; var a$b$x = 0;" + "var c = a; (function() {a$b$y = 1;})(); a$b$x; a$b$y;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAddPropertyToChildOfUncollapsibleFunctionInLocalScope() { testSame( "function a() {} a.b = {x: 0}; var c = a;" + "(function() {a.b.y = 0;})(); a.b.y;"); } public void testAddPropertyToChildOfUncollapsibleCtorInLocalScope() { test("/** @constructor */ var a = function() {}; a.b = {x: 0}; var c = a;" + "(function() {a.b.y = 0;})(); a.b.y;", "var a = function() {}; var a$b$x = 0; var a$b$y; var c = a;" + "(function() {a$b$y = 0;})(); a$b$y;"); } public void testResetObjectPropertyInLocalScope() { test("var a = {b: 0}; a.c = 1; function f() { a.c = 5; }", "var a$b = 0; var a$c = 1; function f() { a$c = 5; }"); } public void testResetFunctionPropertyInLocalScope() { test("function a() {}; a.c = 1; function f() { a.c = 5; }", "function a() {}; var a$c = 1; function f() { a$c = 5; }"); } public void testGlobalNameReferencedInLocalScopeBeforeDefined1() { // Because referencing global names earlier in the source code than they're // defined is such a common practice, we collapse them even though a runtime // exception could result (in the off-chance that the function gets called // before the alias variable is defined). test("var a = {b: 0}; function f() { a.c = 5; } a.c = 1;", "var a$b = 0; function f() { a$c = 5; } var a$c = 1;"); } public void testGlobalNameReferencedInLocalScopeBeforeDefined2() { test("var a = {b: 0}; function f() { return a.c; } a.c = 1;", "var a$b = 0; function f() { return a$c; } var a$c = 1;"); } public void testTwiceDefinedGlobalNameDepth1_1() { testSame("var a = {}; function f() { a.b(); }" + "a = function() {}; a.b = function() {};"); } public void testTwiceDefinedGlobalNameDepth1_2() { testSame("var a = {}; /** @constructor */ a = function() {};" + "a.b = {}; a.b.c = 0; function f() { a.b.d = 1; }"); } public void testTwiceDefinedGlobalNameDepth2() { test("var a = {}; a.b = {}; function f() { a.b.c(); }" + "a.b = function() {}; a.b.c = function() {};", "var a$b = {}; function f() { a$b.c(); }" + "a$b = function() {}; a$b.c = function() {};"); } public void testFunctionCallDepth1() { test("var a = {}; a.b = function(){}; var c = a.b();", "var a$b = function(){}; var c = a$b()"); } public void testFunctionCallDepth2() { test("var a = {}; a.b = {}; a.b.c = function(){}; a.b.c();", "var a$b$c = function(){}; a$b$c();"); } public void testFunctionAlias() { test("var a = {}; a.b = {}; a.b.c = function(){}; a.b.d = a.b.c;", "var a$b$c = function(){}; var a$b$d = a$b$c;"); } public void testCallToRedefinedFunction() { test("var a = {}; a.b = function(){}; a.b = function(){}; a.b();", "var a$b = function(){}; a$b = function(){}; a$b();"); } public void testCollapsePrototypeName() { test("var a = {}; a.b = {}; a.b.c = function(){}; " + "a.b.c.prototype.d = function(){}; (new a.b.c()).d();", "var a$b$c = function(){}; a$b$c.prototype.d = function(){}; " + "new a$b$c().d();"); } public void testReferencedPrototypeProperty() { test("var a = {b: {}}; a.b.c = function(){}; a.b.c.prototype.d = {};" + "e = a.b.c.prototype.d;", "var a$b$c = function(){}; a$b$c.prototype.d = {};" + "e = a$b$c.prototype.d;"); } public void testSetStaticAndPrototypePropertiesOnFunction() { test("var a = {}; a.b = function(){}; a.b.prototype.d = 0; a.b.c = 1;", "var a$b = function(){}; a$b.prototype.d = 0; var a$b$c = 1;"); } public void testReadUndefinedPropertyDepth1() { test("var a = {b: 0}; var c = a.d;", "var a$b = 0; var a = {}; var c = a.d;"); } public void testReadUndefinedPropertyDepth2() { test("var a = {b: {c: 0}}; f(a.b.c); f(a.b.d);", "var a$b$c = 0; var a$b = {}; f(a$b$c); f(a$b.d);"); } public void testCallUndefinedMethodOnObjLitDepth1() { test("var a = {b: 0}; a.c();", "var a$b = 0; var a = {}; a.c();"); } public void testCallUndefinedMethodOnObjLitDepth2() { test("var a = {b: {}}; a.b.c = function() {}; a.b.c(); a.b.d();", "var a$b = {}; var a$b$c = function() {}; a$b$c(); a$b.d();"); } public void testPropertiesOfAnUndefinedVar() { testSame("a.document = d; f(a.document.innerHTML);"); } public void testPropertyOfAnObjectThatIsNeitherFunctionNorObjLit() { testSame("var a = window; a.document = d; f(a.document)"); } public void testStaticFunctionReferencingThis1() { // Note: Google's JavaScript Style Guide says to avoid using the 'this' // keyword in a static function. test("var a = {}; a.b = function() {this.c}; var d = a.b;", "var a$b = function() {this.c}; var d = a$b;", null, UNSAFE_THIS); } public void testStaticFunctionReferencingThis2() { // This gives no warning, because "this" is in a scope whose name is not // getting collapsed. test("var a = {}; " + "a.b = function() { return function(){ return this; }; };", "var a$b = function() { return function(){ return this; }; };"); } public void testStaticFunctionReferencingThis3() { test("var a = {b: function() {this.c}};", "var a$b = function() { this.c };", null, UNSAFE_THIS); } public void testStaticFunctionReferencingThis4() { test("var a = {/** @this {Element} */ b: function() {this.c}};", "var a$b = function() { this.c };"); } public void testPrototypeMethodReferencingThis() { testSame("var A = function(){}; A.prototype = {b: function() {this.c}};"); } public void testConstructorReferencingThis() { test("var a = {}; " + "/** @constructor */ a.b = function() { this.a = 3; };", "var a$b = function() { this.a = 3; };"); } public void testSafeReferenceOfThis() { test("var a = {}; " + "/** @this {Object} */ a.b = function() { this.a = 3; };", "var a$b = function() { this.a = 3; };"); } public void testGlobalFunctionReferenceOfThis() { testSame("var a = function() { this.a = 3; };"); } public void testFunctionGivenTwoNames() { // It's okay to collapse f's properties because g is not added to the // global scope as an alias for f. (Try it in your browser.) test("var f = function g() {}; f.a = 1; h(f.a);", "var f = function g() {}; var f$a = 1; h(f$a);"); } public void testObjLitWithUsedNumericKey() { testSame("a = {40: {}, c: {}}; var d = a[40]; var e = a.c;"); } public void testObjLitWithUnusedNumericKey() { test("var a = {40: {}, c: {}}; var e = a.c;", "var a$1 = {}; var a$c = {}; var e = a$c"); } public void testObjLitWithNonIdentifierKeys() { testSame("a = {' ': 0, ',': 1}; var c = a[' '];"); } public void testChainedAssignments1() { test("var x = {}; x.y = a = 0;", "var x$y = a = 0;"); } public void testChainedAssignments2() { test("var x = {}; x.y = a = b = c();", "var x$y = a = b = c();"); } public void testChainedAssignments3() { test("var x = {y: 1}; a = b = x.y;", "var x$y = 1; a = b = x$y;"); } public void testChainedAssignments4() { test("var x = {}; a = b = x.y;", "var x = {}; a = b = x.y;"); } public void testChainedAssignments5() { test("var x = {}; a = x.y = 0;", "var x$y; a = x$y = 0;"); } public void testChainedAssignments6() { test("var x = {}; a = x.y = b = c();", "var x$y; a = x$y = b = c();"); } public void testChainedAssignments7() { test("var x = {}; a = x.y = {}; /** @constructor */ x.y.z = function() {};", "var x$y; a = x$y = {}; var x$y$z = function() {};", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testChainedVarAssignments1() { test("var x = {y: 1}; var a = x.y = 0;", "var x$y = 1; var a = x$y = 0;"); } public void testChainedVarAssignments2() { test("var x = {y: 1}; var a = x.y = b = 0;", "var x$y = 1; var a = x$y = b = 0;"); } public void testChainedVarAssignments3() { test("var x = {y: {z: 1}}; var b = 0; var a = x.y.z = 1; var c = 2;", "var x$y$z = 1; var b = 0; var a = x$y$z = 1; var c = 2;"); } public void testChainedVarAssignments4() { test("var x = {}; var a = b = x.y = 0;", "var x$y; var a = b = x$y = 0;"); } public void testChainedVarAssignments5() { test("var x = {y: {}}; var a = b = x.y.z = 0;", "var x$y$z; var a = b = x$y$z = 0;"); } public void testPeerAndSubpropertyOfUncollapsibleProperty() { test("var x = {}; var a = x.y = 0; x.w = 1; x.y.z = 2;" + "b = x.w; c = x.y.z;", "var x$y; var a = x$y = 0; var x$w = 1; x$y.z = 2;" + "b = x$w; c = x$y.z;"); } public void testComplexAssignmentAfterInitialAssignment() { test("var d = {}; d.e = {}; d.e.f = 0; a = b = d.e.f = 1;", "var d$e$f = 0; a = b = d$e$f = 1;"); } public void testRenamePrefixOfUncollapsibleProperty() { test("var d = {}; d.e = {}; a = b = d.e.f = 0;", "var d$e$f; a = b = d$e$f = 0;"); } public void testNewOperator() { // Using the new operator on a name doesn't prevent its (static) properties // from getting collapsed. test("var a = {}; a.b = function() {}; a.b.c = 1; var d = new a.b();", "var a$b = function() {}; var a$b$c = 1; var d = new a$b();"); } public void testMethodCall() { test("var a = {}; a.b = function() {}; var d = a.b();", "var a$b = function() {}; var d = a$b();"); } public void testObjLitDefinedInLocalScopeIsLeftAlone() { test("var a = {}; a.b = function() {};" + "a.b.prototype.f_ = function() {" + " var x = { p: '', q: '', r: ''}; var y = x.q;" + "};", "var a$b = function() {};" + "a$b.prototype.f_ = function() {" + " var x = { p: '', q: '', r: ''}; var y = x.q;" + "};"); } public void testPropertiesOnBothSidesOfAssignment() { // This verifies that replacements are done in the right order. Collapsing // the l-value in an assignment affects the parse tree immediately above // the r-value, so we update all rvalues before any lvalues. test("var a = {b: 0}; a.c = a.b;", "var a$b = 0; var a$c = a$b;"); } public void testCallOnUndefinedProperty() { // The "inherits" property is not explicitly defined on a.b anywhere, but // it is accessed as though it certainly exists (it is called), so we infer // that it must be an uncollapsible property that has come into existence // some other way. test("var a = {}; a.b = function(){}; a.b.inherits(x);", "var a$b = function(){}; a$b.inherits(x);"); } public void testGetPropOnUndefinedProperty() { // The "superClass_" property is not explicitly defined on a.b anywhere, // but it is accessed as though it certainly exists (a subproperty of it // is accessed), so we infer that it must be an uncollapsible property that // has come into existence some other way. test("var a = {b: function(){}}; a.b.prototype.c =" + "function() { a.b.superClass_.c.call(this); }", "var a$b = function(){}; a$b.prototype.c =" + "function() { a$b.superClass_.c.call(this); }"); } public void testLocalAlias1() { test("var a = {b: 3}; function f() { var x = a; f(x.b); }", "var a$b = 3; function f() { var x = null; f(a$b); }"); } public void testLocalAlias2() { test("var a = {b: 3, c: 4}; function f() { var x = a; f(x.b); f(x.c);}", "var a$b = 3; var a$c = 4; " + "function f() { var x = null; f(a$b); f(a$c);}"); } public void testLocalAlias3() { test("var a = {b: 3, c: {d: 5}}; " + "function f() { var x = a; f(x.b); f(x.c); f(x.c.d); }", "var a$b = 3; var a$c = {d: 5}; " + "function f() { var x = null; f(a$b); f(a$c); f(a$c.d);}"); } public void testLocalAlias4() { test("var a = {b: 3}; var c = {d: 5}; " + "function f() { var x = a; var y = c; f(x.b); f(y.d); }", "var a$b = 3; var c$d = 5; " + "function f() { var x = null; var y = null; f(a$b); f(c$d);}"); } public void testLocalAlias5() { test("var a = {b: {c: 5}}; " + "function f() { var x = a; var y = x.b; f(a.b.c); f(y.c); }", "var a$b$c = 5; " + "function f() { var x = null; var y = null; f(a$b$c); f(a$b$c);}"); } public void testLocalAlias6() { test("var a = {b: 3}; function f() { var x = a; if (x.b) { f(x.b); } }", "var a$b = 3; function f() { var x = null; if (a$b) { f(a$b); } }"); } public void testLocalAlias7() { test("var a = {b: {c: 5}}; function f() { var x = a.b; f(x.c); }", "var a$b$c = 5; function f() { var x = null; f(a$b$c); }"); } public void testGlobalWriteToAncestor() { testSame("var a = {b: 3}; function f() { var x = a; f(a.b); } a = 5;"); } public void testGlobalWriteToNonAncestor() { test("var a = {b: 3}; function f() { var x = a; f(a.b); } a.b = 5;", "var a$b = 3; function f() { var x = null; f(a$b); } a$b = 5;"); } public void testLocalWriteToAncestor() { testSame("var a = {b: 3}; function f() { a = 5; var x = a; f(a.b); } "); } public void testLocalWriteToNonAncestor() { test("var a = {b: 3}; " + "function f() { a.b = 5; var x = a; f(a.b); }", "var a$b = 3; function f() { a$b = 5; var x = null; f(a$b); } "); } public void testNonWellformedAlias1() { testSame("var a = {b: 3}; function f() { f(x); var x = a; f(x.b); }"); } public void testNonWellformedAlias2() { testSame("var a = {b: 3}; " + "function f() { if (false) { var x = a; f(x.b); } f(x); }"); } public void testLocalAliasOfAncestor() { testSame("var a = {b: {c: 5}}; function g() { f(a); } " + "function f() { var x = a.b; f(x.c); }"); } public void testGlobalAliasOfAncestor() { testSame("var a = {b: {c: 5}}; var y = a; " + "function f() { var x = a.b; f(x.c); }"); } public void testLocalAliasOfOtherName() { testSame("var foo = function() { return {b: 3}; };" + "var a = foo(); a.b = 5; " + "function f() { var x = a.b; f(x); }"); } public void testLocalAliasOfFunction() { test("var a = function() {}; a.b = 5; " + "function f() { var x = a.b; f(x); }", "var a = function() {}; var a$b = 5; " + "function f() { var x = null; f(a$b); }"); } public void testNoInlineGetpropIntoCall() { test("var b = x; function f() { var a = b; a(); }", "var b = x; function f() { var a = null; b(); }"); test("var b = {}; b.c = x; function f() { var a = b.c; a(); }", "var b$c = x; function f() { var a = null; b$c(); }"); } public void testInlineAliasWithModifications() { testSame("var x = 10; function f() { var y = x; x++; alert(y)} "); testSame("var x = 10; function f() { var y = x; x+=1; alert(y)} "); test("var x = {}; x.x = 10; function f() {var y=x.x; x.x++; alert(y)}", "var x$x = 10; function f() {var y=x$x; x$x++; alert(y)}"); test("var x = {}; x.x = 10; function f() {var y=x.x; x.x+=1; alert(y)}", "var x$x = 10; function f() {var y=x$x; x$x+=1; alert(y)}"); } public void testCollapsePropertyOnExternType() { collapsePropertiesOnExternTypes = true; test("String.myFunc = function() {}; String.myFunc();", "var String$myFunc = function() {}; String$myFunc()"); } public void testCollapseForEachWithoutExterns() { collapsePropertiesOnExternTypes = true; test("/** @constructor */function Array(){};\n", "if (!Array.forEach) {\n" + " Array.forEach = function() {};\n" + "}", "if (!Array$forEach) {\n" + " var Array$forEach = function() {};\n" + "}", null, null); } public void testNoCollapseForEachInExterns() { collapsePropertiesOnExternTypes = true; test("/** @constructor */ function Array() {}" + "Array.forEach = function() {}", "if (!Array.forEach) {\n" + " Array.forEach = function() {};\n" + "}", "if (!Array.forEach) {\n" + " Array.forEach = function() {};\n" + "}", null, null); } public void testIssue931() { collapsePropertiesOnExternTypes = true; testSame( "function f() {\n" + " return function () {\n" + " var args = arguments;\n" + " setTimeout(function() { alert(args); }, 0);\n" + " }\n" + "};\n"); } public void testDoNotCollapsePropertyOnExternType() { collapsePropertiesOnExternTypes = false; test("String.myFunc = function() {}; String.myFunc()", "String.myFunc = function() {}; String.myFunc()"); } public void testBug1704733() { String prelude = "function protect(x) { return x; }" + "function O() {}" + "protect(O).m1 = function() {};" + "protect(O).m2 = function() {};" + "protect(O).m3 = function() {};"; testSame(prelude + "alert(O.m1); alert(O.m2()); alert(!O.m3);"); } public void testBug1956277() { test("var CONST = {}; CONST.URL = 3;", "var CONST$URL = 3;"); } public void testBug1974371() { test( "/** @enum {Object} */ var Foo = {A: {c: 2}, B: {c: 3}};" + "for (var key in Foo) {}", "var Foo$A = {c: 2}; var Foo$B = {c: 3};" + "var Foo = {A: Foo$A, B: Foo$B};" + "for (var key in Foo) {}"); } private final String COMMON_ENUM = "/** @enum {Object} */ var Foo = {A: {c: 2}, B: {c: 3}};"; public void testEnumOfObjects1() { test( COMMON_ENUM + "for (var key in Foo.A) {}", "var Foo$A = {c: 2}; var Foo$B$c = 3; for (var key in Foo$A) {}"); } public void testEnumOfObjects2() { test( COMMON_ENUM + "foo(Foo.A.c);", "var Foo$A$c = 2; var Foo$B$c = 3; foo(Foo$A$c);"); } public void testEnumOfObjects3() { test( "var x = {c: 2}; var y = {c: 3};" + "/** @enum {Object} */ var Foo = {A: x, B: y};" + "for (var key in Foo) {}", "var x = {c: 2}; var y = {c: 3};" + "var Foo$A = x; var Foo$B = y; var Foo = {A: Foo$A, B: Foo$B};" + "for (var key in Foo) {}"); } public void testEnumOfObjects4() { // Note that this produces bad code, but that's OK, because // checkConsts will yell at you for reassigning an enum value. // (enum values have to be constant). test( COMMON_ENUM + "for (var key in Foo) {} Foo.A = 3; alert(Foo.A);", "var Foo$A = {c: 2}; var Foo$B = {c: 3};" + "var Foo = {A: Foo$A, B: Foo$B};" + "for (var key in Foo) {} Foo$A = 3; alert(Foo$A);"); } public void testObjectOfObjects1() { // Basically the same as testEnumOfObjects4, but without the // constant enum values. testSame( "var Foo = {a: {c: 2}, b: {c: 3}};" + "for (var key in Foo) {} Foo.a = 3; alert(Foo.a);"); } public void testReferenceInAnonymousObject0() { test("var a = {};" + "a.b = function(){};" + "a.b.prototype.c = function(){};" + "var d = a.b.prototype.c;", "var a$b = function(){};" + "a$b.prototype.c = function(){};" + "var d = a$b.prototype.c;"); } public void testReferenceInAnonymousObject1() { test("var a = {};" + "a.b = function(){};" + "var d = a.b.prototype.c;", "var a$b = function(){};" + "var d = a$b.prototype.c;"); } public void testReferenceInAnonymousObject2() { test("var a = {};" + "a.b = function(){};" + "a.b.prototype.c = function(){};" + "var d = {c: a.b.prototype.c};", "var a$b = function(){};" + "a$b.prototype.c = function(){};" + "var d$c = a$b.prototype.c;"); } public void testReferenceInAnonymousObject3() { test("function CreateClass(a$$1) {}" + "var a = {};" + "a.b = function(){};" + "a.b.prototype.c = function(){};" + "a.d = CreateClass({c: a.b.prototype.c});", "function CreateClass(a$$1) {}" + "var a$b = function(){};" + "a$b.prototype.c = function(){};" + "var a$d = CreateClass({c: a$b.prototype.c});"); } public void testReferenceInAnonymousObject4() { test("function CreateClass(a) {}" + "var a = {};" + "a.b = CreateClass({c: function() {}});" + "a.d = CreateClass({c: a.b.c});", "function CreateClass(a$$1) {}" + "var a$b = CreateClass({c: function() {}});" + "var a$d = CreateClass({c: a$b.c});"); } public void testReferenceInAnonymousObject5() { test("function CreateClass(a) {}" + "var a = {};" + "a.b = CreateClass({c: function() {}});" + "a.d = CreateClass({c: a.b.prototype.c});", "function CreateClass(a$$1) {}" + "var a$b = CreateClass({c: function() {}});" + "var a$d = CreateClass({c: a$b.prototype.c});"); } public void testCrashInCommaOperator() { test("var a = {}; a.b = function() {},a.b();", "var a$b; a$b=function() {},a$b();"); } public void testCrashInNestedAssign() { test("var a = {}; if (a.b = function() {}) a.b();", "var a$b; if (a$b=function() {}) { a$b(); }"); } public void testTwinReferenceCancelsChildCollapsing() { test("var a = {}; if (a.b = function() {}) { a.b.c = 3; a.b(a.b.c); }", "var a$b; if (a$b = function() {}) { a$b.c = 3; a$b(a$b.c); }"); } public void testPropWithDollarSign() { test("var a = {$: 3}", "var a$$0 = 3;"); } public void testPropWithDollarSign2() { test("var a = {$: function(){}}", "var a$$0 = function(){};"); } public void testPropWithDollarSign3() { test("var a = {b: {c: 3}, b$c: function(){}}", "var a$b$c = 3; var a$b$0c = function(){};"); } public void testPropWithDollarSign4() { test("var a = {$$: {$$$: 3}};", "var a$$0$0$$0$0$0 = 3;"); } public void testPropWithDollarSign5() { test("var a = {b: {$0c: true}, b$0c: false};", "var a$b$$00c = true; var a$b$00c = false;"); } public void testConstKey() { test("var foo = {A: 3};", "var foo$A = 3;"); } public void testPropertyOnGlobalCtor() { test("/** @constructor */ function Map() {} Map.foo = 3; Map;", "function Map() {} var Map$foo = 3; Map;"); } public void testPropertyOnGlobalInterface() { test("/** @interface */ function Map() {} Map.foo = 3; Map;", "function Map() {} var Map$foo = 3; Map;"); } public void testPropertyOnGlobalFunction() { testSame("function Map() {} Map.foo = 3; Map;"); } public void testIssue389() { test( "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "/** @constructor */" + "dojo.gfx.Shape = function() {};" + "dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);", "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "/** @constructor */" + "var dojo$gfx$Shape = function() {};" + "dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasedTopLevelName() { testSame( "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "dojo.gfx.Shape = {SQUARE: 2};" + "dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);" + "alias(dojo$gfx$Shape$SQUARE);"); } public void testAliasedTopLevelEnum() { test( "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "/** @enum {number} */" + "dojo.gfx.Shape = {SQUARE: 2};" + "dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);" + "alias(dojo.gfx.Shape.SQUARE);", "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "/** @constructor */" + "var dojo$gfx$Shape = {SQUARE: 2};" + "dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);" + "alias(dojo$gfx$Shape.SQUARE);", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAssignFunctionBeforeDefinition() { testSame( "f = function() {};" + "var f = null;"); } public void testObjectLitBeforeDefinition() { testSame( "a = {b: 3};" + "var a = null;" + "this.c = a.b;"); } public void testTypedef1() { test("var foo = {};" + "/** @typedef {number} */ foo.Baz;", "var foo = {}; var foo$Baz;"); } public void testTypedef2() { test("var foo = {};" + "/** @typedef {number} */ foo.Bar.Baz;" + "foo.Bar = function() {};", "var foo$Bar$Baz; var foo$Bar = function(){};"); } public void testDelete1() { testSame( "var foo = {};" + "foo.bar = 3;" + "delete foo.bar;"); } public void testDelete2() { test( "var foo = {};" + "foo.bar = 3;" + "foo.baz = 3;" + "delete foo.bar;", "var foo = {};" + "foo.bar = 3;" + "var foo$baz = 3;" + "delete foo.bar;"); } public void testDelete3() { testSame( "var foo = {bar: 3};" + "delete foo.bar;"); } public void testDelete4() { test( "var foo = {bar: 3, baz: 3};" + "delete foo.bar;", "var foo$baz=3;var foo={bar:3};delete foo.bar"); } public void testDelete5() { test( "var x = {};" + "x.foo = {};" + "x.foo.bar = 3;" + "delete x.foo.bar;", "var x$foo = {};" + "x$foo.bar = 3;" + "delete x$foo.bar;"); } public void testDelete6() { test( "var x = {};" + "x.foo = {};" + "x.foo.bar = 3;" + "x.foo.baz = 3;" + "delete x.foo.bar;", "var x$foo = {};" + "x$foo.bar = 3;" + "var x$foo$baz = 3;" + "delete x$foo.bar;"); } public void testDelete7() { test( "var x = {};" + "x.foo = {bar: 3};" + "delete x.foo.bar;", "var x$foo = {bar: 3};" + "delete x$foo.bar;"); } public void testDelete8() { test( "var x = {};" + "x.foo = {bar: 3, baz: 3};" + "delete x.foo.bar;", "var x$foo$baz = 3; var x$foo = {bar: 3};" + "delete x$foo.bar;"); } public void testDelete9() { testSame( "var x = {};" + "x.foo = {};" + "x.foo.bar = 3;" + "delete x.foo;"); } public void testDelete10() { testSame( "var x = {};" + "x.foo = {bar: 3};" + "delete x.foo;"); } public void testDelete11() { // Constructors are always collapsed. test( "var x = {};" + "x.foo = {};" + "/** @constructor */ x.foo.Bar = function() {};" + "delete x.foo;", "var x = {};" + "x.foo = {};" + "var x$foo$Bar = function() {};" + "delete x.foo;", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testPreserveConstructorDoc() { test("var foo = {};" + "/** @constructor */\n" + "foo.bar = function() {}", "var foo$bar = function() {}"); Node root = getLastCompiler().getRoot(); Node fooBarNode = findQualifiedNameNode("foo$bar", root); Node varNode = fooBarNode.getParent(); assertTrue(varNode.isVar()); assertTrue(varNode.getJSDocInfo().isConstructor()); } }
// You are a professional Java test case writer, please create a test case named `testIssue931` for the issue `Closure-931`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-931 // // ## Issue-Title: // arguments is moved to another scope // // ## Issue-Description: // Using ADVANCED\_OPTIMIZATIONS with CompilerOptions.collapsePropertiesOnExternTypes = true a script I used broke, it was something like: // // function () { // return function () { // var arg = arguments; // setTimeout(function() { alert(args); }, 0); // } // } // // Unfortunately it was rewritten to: // // function () { // return function () { // setTimeout(function() { alert(arguments); }, 0); // } // } // // arguments should not be collapsed. // // public void testIssue931() {
1,107
130
1,098
test/com/google/javascript/jscomp/CollapsePropertiesTest.java
test
```markdown ## Issue-ID: Closure-931 ## Issue-Title: arguments is moved to another scope ## Issue-Description: Using ADVANCED\_OPTIMIZATIONS with CompilerOptions.collapsePropertiesOnExternTypes = true a script I used broke, it was something like: function () { return function () { var arg = arguments; setTimeout(function() { alert(args); }, 0); } } Unfortunately it was rewritten to: function () { return function () { setTimeout(function() { alert(arguments); }, 0); } } arguments should not be collapsed. ``` You are a professional Java test case writer, please create a test case named `testIssue931` for the issue `Closure-931`, utilizing the provided issue report information and the following function signature. ```java public void testIssue931() { ```
1,098
[ "com.google.javascript.jscomp.CollapseProperties" ]
176b90f24eeb20bb5a4e01bcaa636646fb00e26cad9d44637802fca6f2764861
public void testIssue931()
// You are a professional Java test case writer, please create a test case named `testIssue931` for the issue `Closure-931`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-931 // // ## Issue-Title: // arguments is moved to another scope // // ## Issue-Description: // Using ADVANCED\_OPTIMIZATIONS with CompilerOptions.collapsePropertiesOnExternTypes = true a script I used broke, it was something like: // // function () { // return function () { // var arg = arguments; // setTimeout(function() { alert(args); }, 0); // } // } // // Unfortunately it was rewritten to: // // function () { // return function () { // setTimeout(function() { alert(arguments); }, 0); // } // } // // arguments should not be collapsed. // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.jscomp.CollapseProperties.UNSAFE_THIS; import com.google.javascript.rhino.Node; /** * Tests for {@link CollapseProperties}. * */ public class CollapsePropertiesTest extends CompilerTestCase { private static String EXTERNS = "var window;\n" + "function alert(s) {}\n" + "function parseInt(s) {}\n" + "/** @constructor */ function String() {};\n" + "var arguments"; private boolean collapsePropertiesOnExternTypes = false; public CollapsePropertiesTest() { super(EXTERNS); } @Override public CompilerPass getProcessor(Compiler compiler) { return new CollapseProperties( compiler, collapsePropertiesOnExternTypes, true); } @Override public void setUp() { enableLineNumberCheck(true); enableNormalize(true); } @Override public int getNumRepetitions() { return 1; } public void testCollapse() { test("var a = {}; a.b = {}; var c = a.b;", "var a$b = {}; var c = a$b"); } public void testMultiLevelCollapse() { test("var a = {}; a.b = {}; a.b.c = {}; var d = a.b.c;", "var a$b$c = {}; var d = a$b$c;"); } public void testDecrement() { test("var a = {}; a.b = 5; a.b--; a.b = 5", "var a$b = 5; a$b--; a$b = 5"); } public void testIncrement() { test("var a = {}; a.b = 5; a.b++; a.b = 5", "var a$b = 5; a$b++; a$b = 5"); } public void testObjLitDeclaration() { test("var a = {b: {}, c: {}}; var d = a.b; var e = a.c", "var a$b = {}; var a$c = {}; var d = a$b; var e = a$c"); } public void testObjLitDeclarationWithGet1() { testSame("var a = {get b(){}};"); } public void testObjLitDeclarationWithGet2() { test("var a = {b: {}, get c(){}}; var d = a.b; var e = a.c", "var a$b = {};var a = {get c(){}};var d = a$b; var e = a.c"); } public void testObjLitDeclarationWithGet3() { test("var a = {b: {get c() { return 3; }}};", "var a$b = {get c() { return 3; }};"); } public void testObjLitDeclarationWithSet1() { testSame("var a = {set b(a){}};"); } public void testObjLitDeclarationWithSet2() { test("var a = {b: {}, set c(a){}}; var d = a.b; var e = a.c", "var a$b = {};var a = {set c(a){}};var d = a$b; var e = a.c"); } public void testObjLitDeclarationWithSet3() { test("var a = {b: {set c(d) {}}};", "var a$b = {set c(d) {}};"); } public void testObjLitDeclarationWithGetAndSet1() { test("var a = {b: {get c() { return 3; },set c(d) {}}};", "var a$b = {get c() { return 3; },set c(d) {}};"); } public void testObjLitDeclarationWithDuplicateKeys() { test("var a = {b: 0, b: 1}; var c = a.b;", "var a$b = 0; var a$b = 1; var c = a$b;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testObjLitAssignmentDepth1() { test("var a = {b: {}, c: {}}; var d = a.b; var e = a.c", "var a$b = {}; var a$c = {}; var d = a$b; var e = a$c"); } public void testObjLitAssignmentDepth2() { test("var a = {}; a.b = {c: {}, d: {}}; var e = a.b.c; var f = a.b.d", "var a$b$c = {}; var a$b$d = {}; var e = a$b$c; var f = a$b$d"); } public void testObjLitAssignmentDepth3() { test("var a = {}; a.b = {}; a.b.c = {d: 1, e: 2}; var f = a.b.c.d", "var a$b$c$d = 1; var a$b$c$e = 2; var f = a$b$c$d"); } public void testObjLitAssignmentDepth4() { test("var a = {}; a.b = {}; a.b.c = {}; a.b.c.d = {e: 1, f: 2}; " + "var g = a.b.c.d.e", "var a$b$c$d$e = 1; var a$b$c$d$f = 2; var g = a$b$c$d$e"); } public void testGlobalObjectDeclaredToPreserveItsPreviousValue1() { test("var a = a ? a : {}; a.c = 1;", "var a = a ? a : {}; var a$c = 1;"); } public void testGlobalObjectDeclaredToPreserveItsPreviousValue2() { test("var a = a || {}; a.c = 1;", "var a = a || {}; var a$c = 1;"); } public void testGlobalObjectDeclaredToPreserveItsPreviousValue3() { test("var a = a || {get b() {}}; a.c = 1;", "var a = a || {get b() {}}; var a$c = 1;"); } public void testGlobalObjectNameInBooleanExpressionDepth1_1() { test("var a = {b: 0}; a.c = 1; if (a) x();", "var a$b = 0; var a = {}; var a$c = 1; if (a) x();"); } public void testGlobalObjectNameInBooleanExpressionDepth1_2() { test("var a = {b: 0}; a.c = 1; if (!(a && a.c)) x();", "var a$b = 0; var a = {}; var a$c = 1; if (!(a && a$c)) x();"); } public void testGlobalObjectNameInBooleanExpressionDepth1_3() { test("var a = {b: 0}; a.c = 1; while (a || a.c) x();", "var a$b = 0; var a = {}; var a$c = 1; while (a || a$c) x();"); } public void testGlobalObjectNameInBooleanExpressionDepth1_4() { testSame("var a = {}; a.c = 1; var d = a || {}; a.c;"); } public void testGlobalObjectNameInBooleanExpressionDepth1_5() { testSame("var a = {}; a.c = 1; var d = a.c || a; a.c;"); } public void testGlobalObjectNameInBooleanExpressionDepth1_6() { test("var a = {b: 0}; a.c = 1; var d = !(a.c || a); a.c;", "var a$b = 0; var a = {}; var a$c = 1; var d = !(a$c || a); a$c;"); } public void testGlobalObjectNameInBooleanExpressionDepth2() { test("var a = {b: {}}; a.b.c = 1; if (a.b) x(a.b.c);", "var a$b = {}; var a$b$c = 1; if (a$b) x(a$b$c);"); } public void testGlobalObjectNameInBooleanExpressionDepth3() { // TODO(user): Make CollapseProperties even more aggressive so that // a$b.z gets collapsed. Right now, it doesn't get collapsed because the // expression (a.b && a.b.c) could return a.b. But since it returns a.b iff // a.b *is* safely collapsible, the Boolean logic should be smart enough to // only consider the right side of the && as aliasing. test("var a = {}; a.b = {}; /** @constructor */ a.b.c = function(){};" + " a.b.z = 1; var d = a.b && a.b.c;", "var a$b = {}; var a$b$c = function(){};" + " a$b.z = 1; var d = a$b && a$b$c;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testGlobalFunctionNameInBooleanExpressionDepth1() { test("function a() {} a.c = 1; if (a) x(a.c);", "function a() {} var a$c = 1; if (a) x(a$c);"); } public void testGlobalFunctionNameInBooleanExpressionDepth2() { test("var a = {b: function(){}}; a.b.c = 1; if (a.b) x(a.b.c);", "var a$b = function(){}; var a$b$c = 1; if (a$b) x(a$b$c);"); } public void testAliasCreatedForObjectDepth1_1() { // An object's properties are not collapsed if the object is referenced // in a such a way that an alias is created for it. testSame("var a = {b: 0}; var c = a; c.b = 1; a.b == c.b;"); } public void testAliasCreatedForObjectDepth1_2() { testSame("var a = {b: 0}; f(a); a.b;"); } public void testAliasCreatedForObjectDepth1_3() { testSame("var a = {b: 0}; new f(a); a.b;"); } public void testAliasCreatedForObjectDepth2_1() { test("var a = {}; a.b = {c: 0}; var d = a.b; a.b.c == d.c;", "var a$b = {c: 0}; var d = a$b; a$b.c == d.c;"); } public void testAliasCreatedForObjectDepth2_2() { test("var a = {}; a.b = {c: 0}; for (var p in a.b) { e(a.b[p]); }", "var a$b = {c: 0}; for (var p in a$b) { e(a$b[p]); }"); } public void testAliasCreatedForEnumDepth1_1() { // An enum's values are always collapsed, even if the enum object is // referenced in a such a way that an alias is created for it. test("/** @enum */ var a = {b: 0}; var c = a; c.b = 1; a.b != c.b;", "var a$b = 0; var a = {b: a$b}; var c = a; c.b = 1; a$b != c.b;"); } public void testAliasCreatedForEnumDepth1_2() { test("/** @enum */ var a = {b: 0}; f(a); a.b;", "var a$b = 0; var a = {b: a$b}; f(a); a$b;"); } public void testAliasCreatedForEnumDepth1_3() { test("/** @enum */ var a = {b: 0}; new f(a); a.b;", "var a$b = 0; var a = {b: a$b}; new f(a); a$b;"); } public void testAliasCreatedForEnumDepth1_4() { test("/** @enum */ var a = {b: 0}; for (var p in a) { f(a[p]); }", "var a$b = 0; var a = {b: a$b}; for (var p in a) { f(a[p]); }"); } public void testAliasCreatedForEnumDepth2_1() { test("var a = {}; /** @enum */ a.b = {c: 0};" + "var d = a.b; d.c = 1; a.b.c != d.c;", "var a$b$c = 0; var a$b = {c: a$b$c};" + "var d = a$b; d.c = 1; a$b$c != d.c;"); } public void testAliasCreatedForEnumDepth2_2() { test("var a = {}; /** @enum */ a.b = {c: 0};" + "for (var p in a.b) { f(a.b[p]); }", "var a$b$c = 0; var a$b = {c: a$b$c};" + "for (var p in a$b) { f(a$b[p]); }"); } public void testAliasCreatedForEnumDepth2_3() { test("var a = {}; var d = a; /** @enum */ a.b = {c: 0};" + "for (var p in a.b) { f(a.b[p]); }", "var a = {}; var d = a; var a$b$c = 0; var a$b = {c: a$b$c};" + "for (var p in a$b) { f(a$b[p]); }", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForEnumOfObjects() { test("var a = {}; " + "/** @enum {Object} */ a.b = {c: {d: 1}}; a.b.c;" + "searchEnum(a.b);", "var a$b$c = {d: 1};var a$b = {c: a$b$c}; a$b$c; " + "searchEnum(a$b)"); } public void testAliasCreatedForEnumOfObjects2() { test("var a = {}; " + "/** @enum {Object} */ a.b = {c: {d: 1}}; a.b.c.d;" + "searchEnum(a.b);", "var a$b$c = {d: 1};var a$b = {c: a$b$c}; a$b$c.d; " + "searchEnum(a$b)"); } public void testAliasCreatedForPropertyOfEnumOfObjects() { test("var a = {}; " + "/** @enum {Object} */ a.b = {c: {d: 1}}; a.b.c;" + "searchEnum(a.b.c);", "var a$b$c = {d: 1}; a$b$c; searchEnum(a$b$c);"); } public void testAliasCreatedForPropertyOfEnumOfObjects2() { test("var a = {}; " + "/** @enum {Object} */ a.b = {c: {d: 1}}; a.b.c.d;" + "searchEnum(a.b.c);", "var a$b$c = {d: 1}; a$b$c.d; searchEnum(a$b$c);"); } public void testMisusedEnumTag() { testSame("var a = {}; var d = a; a.b = function() {};" + "/** @enum */ a.b.c = 0; a.b.c;"); } public void testMisusedConstructorTag() { testSame("var a = {}; var d = a; a.b = function() {};" + "/** @constructor */ a.b.c = 0; a.b.c;"); } public void testAliasCreatedForFunctionDepth1_1() { testSame("var a = function(){}; a.b = 1; var c = a; c.b = 2; a.b != c.b;"); } public void testAliasCreatedForCtorDepth1_1() { // A constructor's properties *are* collapsed even if the function is // referenced in a such a way that an alias is created for it, // since a function with custom properties is considered a class and its // non-prototype properties are considered static methods and variables. // People don't typically iterate through static members of a class or // refer to them using an alias for the class name. test("/** @constructor */ var a = function(){}; a.b = 1; " + "var c = a; c.b = 2; a.b != c.b;", "var a = function(){}; var a$b = 1; var c = a; c.b = 2; a$b != c.b;"); } public void testAliasCreatedForFunctionDepth1_2() { testSame("var a = function(){}; a.b = 1; f(a); a.b;"); } public void testAliasCreatedForCtorDepth1_2() { test("/** @constructor */ var a = function(){}; a.b = 1; f(a); a.b;", "var a = function(){}; var a$b = 1; f(a); a$b;"); } public void testAliasCreatedForFunctionDepth1_3() { testSame("var a = function(){}; a.b = 1; new f(a); a.b;"); } public void testAliasCreatedForCtorDepth1_3() { test("/** @constructor */ var a = function(){}; a.b = 1; new f(a); a.b;", "var a = function(){}; var a$b = 1; new f(a); a$b;"); } public void testAliasCreatedForFunctionDepth2() { test( "var a = {}; a.b = function() {}; a.b.c = 1; var d = a.b;" + "a.b.c != d.c;", "var a$b = function() {}; a$b.c = 1; var d = a$b;" + "a$b.c != d.c;"); } public void testAliasCreatedForCtorDepth2() { test("var a = {}; /** @constructor */ a.b = function() {}; " + "a.b.c = 1; var d = a.b;" + "a.b.c != d.c;", "var a$b = function() {}; var a$b$c = 1; var d = a$b;" + "a$b$c != d.c;"); } public void testAliasCreatedForClassDepth1_1() { // A class's name is always collapsed, even if one of its prefixes is // referenced in a such a way that an alias is created for it. test("var a = {}; /** @constructor */ a.b = function(){};" + "var c = a; c.b = 0; a.b != c.b;", "var a = {}; var a$b = function(){};" + "var c = a; c.b = 0; a$b != c.b;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth1_2() { test("var a = {}; /** @constructor */ a.b = function(){}; f(a); a.b;", "var a = {}; var a$b = function(){}; f(a); a$b;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth1_3() { test("var a = {}; /** @constructor */ a.b = function(){}; new f(a); a.b;", "var a = {}; var a$b = function(){}; new f(a); a$b;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth2_1() { test("var a = {}; a.b = {}; /** @constructor */ a.b.c = function(){};" + "var d = a.b; a.b.c != d.c;", "var a$b = {}; var a$b$c = function(){};" + "var d = a$b; a$b$c != d.c;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth2_2() { test("var a = {}; a.b = {}; /** @constructor */ a.b.c = function(){};" + "f(a.b); a.b.c;", "var a$b = {}; var a$b$c = function(){}; f(a$b); a$b$c;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassDepth2_3() { test("var a = {}; a.b = {}; /** @constructor */ a.b.c = function(){};" + "new f(a.b); a.b.c;", "var a$b = {}; var a$b$c = function(){}; new f(a$b); a$b$c;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasCreatedForClassProperty() { test("var a = {}; /** @constructor */ a.b = function(){};" + "a.b.c = {d: 3}; new f(a.b.c); a.b.c.d;", "var a$b = function(){}; var a$b$c = {d:3}; new f(a$b$c); a$b$c.d;"); } public void testNestedObjLit() { test("var a = {}; a.b = {f: 0, c: {d: 1}}; var e = a.b.c.d", "var a$b$f = 0; var a$b$c$d = 1; var e = a$b$c$d;"); } public void testObjLitDeclarationUsedInSameVarList() { // The collapsed properties must defined in the same place in the var list // where they were originally defined (and not, for example, at the end). test("var a = {b: {}, c: {}}; var d = a.b; var e = a.c;", "var a$b = {}; var a$c = {}; var d = a$b; var e = a$c;"); } public void testPropGetInsideAnObjLit() { test("var x = {}; x.y = 1; var a = {}; a.b = {c: x.y}", "var x$y = 1; var a$b$c = x$y;"); } public void testObjLitWithQuotedKeyThatDoesNotGetRead() { test("var a = {}; a.b = {c: 0, 'd': 1}; var e = a.b.c;", "var a$b$c = 0; var a$b$d = 1; var e = a$b$c;"); } public void testObjLitWithQuotedKeyThatGetsRead() { test("var a = {}; a.b = {c: 0, 'd': 1}; var e = a.b['d'];", "var a$b = {c: 0, 'd': 1}; var e = a$b['d'];"); } public void testFunctionWithQuotedPropertyThatDoesNotGetRead() { test("var a = {}; a.b = function() {}; a.b['d'] = 1;", "var a$b = function() {}; a$b['d'] = 1;"); } public void testFunctionWithQuotedPropertyThatGetsRead() { test("var a = {}; a.b = function() {}; a.b['d'] = 1; f(a.b['d']);", "var a$b = function() {}; a$b['d'] = 1; f(a$b['d']);"); } public void testObjLitAssignedToMultipleNames1() { // An object literal that's assigned to multiple names isn't collapsed. testSame("var a = b = {c: 0, d: 1}; var e = a.c; var f = b.d;"); } public void testObjLitAssignedToMultipleNames2() { testSame("a = b = {c: 0, d: 1}; var e = a.c; var f = b.d;"); } public void testObjLitRedefinedInGlobalScope() { testSame("a = {b: 0}; a = {c: 1}; var d = a.b; var e = a.c;"); } public void testObjLitRedefinedInLocalScope() { test("var a = {}; a.b = {c: 0}; function d() { a.b = {c: 1}; } e(a.b.c);", "var a$b = {c: 0}; function d() { a$b = {c: 1}; } e(a$b.c);"); } public void testObjLitAssignedInTernaryExpression1() { testSame("a = x ? {b: 0} : d; var c = a.b;"); } public void testObjLitAssignedInTernaryExpression2() { testSame("a = x ? {b: 0} : {b: 1}; var c = a.b;"); } public void testGlobalVarSetToObjLitConditionally1() { testSame("var a; if (x) a = {b: 0}; var c = x ? a.b : 0;"); } public void testGlobalVarSetToObjLitConditionally1b() { test("if (x) var a = {b: 0}; var c = x ? a.b : 0;", "if (x) var a$b = 0; var c = x ? a$b : 0;"); } public void testGlobalVarSetToObjLitConditionally2() { test("if (x) var a = {b: 0}; var c = a.b; var d = a.c;", "if (x){ var a$b = 0; var a = {}; }var c = a$b; var d = a.c;"); } public void testGlobalVarSetToObjLitConditionally3() { testSame("var a; if (x) a = {b: 0}; else a = {b: 1}; var c = a.b;"); } public void testObjectPropertySetToObjLitConditionally() { test("var a = {}; if (x) a.b = {c: 0}; var d = a.b ? a.b.c : 0;", "if (x){ var a$b$c = 0; var a$b = {} } var d = a$b ? a$b$c : 0;"); } public void testFunctionPropertySetToObjLitConditionally() { test("function a() {} if (x) a.b = {c: 0}; var d = a.b ? a.b.c : 0;", "function a() {} if (x){ var a$b$c = 0; var a$b = {} }" + "var d = a$b ? a$b$c : 0;"); } public void testPrototypePropertySetToAnObjectLiteral() { test("var a = {b: function(){}}; a.b.prototype.c = {d: 0};", "var a$b = function(){}; a$b.prototype.c = {d: 0};"); } public void testObjectPropertyResetInLocalScope() { test("var z = {}; z.a = 0; function f() {z.a = 5; return z.a}", "var z$a = 0; function f() {z$a = 5; return z$a}"); } public void testFunctionPropertyResetInLocalScope() { test("function z() {} z.a = 0; function f() {z.a = 5; return z.a}", "function z() {} var z$a = 0; function f() {z$a = 5; return z$a}"); } public void testNamespaceResetInGlobalScope1() { test("var a = {}; /** @constructor */a.b = function() {}; a = {};", "var a = {}; var a$b = function() {}; a = {};", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testNamespaceResetInGlobalScope2() { test("var a = {}; a = {}; /** @constructor */a.b = function() {};", "var a = {}; a = {}; var a$b = function() {};", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testNamespaceResetInLocalScope1() { test("var a = {}; /** @constructor */a.b = function() {};" + " function f() { a = {}; }", "var a = {};var a$b = function() {};" + " function f() { a = {}; }", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testNamespaceResetInLocalScope2() { test("var a = {}; function f() { a = {}; }" + " /** @constructor */a.b = function() {};", "var a = {}; function f() { a = {}; }" + " var a$b = function() {};", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testNamespaceDefinedInLocalScope() { test("var a = {}; (function() { a.b = {}; })();" + " /** @constructor */a.b.c = function() {};", "var a$b; (function() { a$b = {}; })(); var a$b$c = function() {};"); } public void testAddPropertyToObjectInLocalScopeDepth1() { test("var a = {b: 0}; function f() { a.c = 5; return a.c; }", "var a$b = 0; var a$c; function f() { a$c = 5; return a$c; }"); } public void testAddPropertyToObjectInLocalScopeDepth2() { test("var a = {}; a.b = {}; (function() {a.b.c = 0;})(); x = a.b.c;", "var a$b$c; (function() {a$b$c = 0;})(); x = a$b$c;"); } public void testAddPropertyToFunctionInLocalScopeDepth1() { test("function a() {} function f() { a.c = 5; return a.c; }", "function a() {} var a$c; function f() { a$c = 5; return a$c; }"); } public void testAddPropertyToFunctionInLocalScopeDepth2() { test("var a = {}; a.b = function() {}; function f() {a.b.c = 0;}", "var a$b = function() {}; var a$b$c; function f() {a$b$c = 0;}"); } public void testAddPropertyToUncollapsibleObjectInLocalScopeDepth1() { testSame("var a = {}; var c = a; (function() {a.b = 0;})(); a.b;"); } public void testAddPropertyToUncollapsibleFunctionInLocalScopeDepth1() { testSame("function a() {} var c = a; (function() {a.b = 0;})(); a.b;"); } public void testAddPropertyToUncollapsibleNamedCtorInLocalScopeDepth1() { testSame( "/** @constructor */ function a() {} var a$b; var c = a; " + "(function() {a$b = 0;})(); a$b;"); } public void testAddPropertyToUncollapsibleCtorInLocalScopeDepth1() { test("/** @constructor */ var a = function() {}; var c = a; " + "(function() {a.b = 0;})(); a.b;", "var a = function() {}; var a$b; " + "var c = a; (function() {a$b = 0;})(); a$b;"); } public void testAddPropertyToUncollapsibleObjectInLocalScopeDepth2() { test("var a = {}; a.b = {}; var d = a.b;" + "(function() {a.b.c = 0;})(); a.b.c;", "var a$b = {}; var d = a$b;" + "(function() {a$b.c = 0;})(); a$b.c;"); } public void testAddPropertyToUncollapsibleFunctionInLocalScopeDepth2() { test("var a = {}; a.b = function (){}; var d = a.b;" + "(function() {a.b.c = 0;})(); a.b.c;", "var a$b = function (){}; var d = a$b;" + "(function() {a$b.c = 0;})(); a$b.c;"); } public void testAddPropertyToUncollapsibleCtorInLocalScopeDepth2() { test("var a = {}; /** @constructor */ a.b = function (){}; var d = a.b;" + "(function() {a.b.c = 0;})(); a.b.c;", "var a$b = function (){}; var a$b$c; var d = a$b;" + "(function() {a$b$c = 0;})(); a$b$c;"); } public void testPropertyOfChildFuncOfUncollapsibleObjectDepth1() { testSame("var a = {}; var c = a; a.b = function (){}; a.b.x = 0; a.b.x;"); } public void testPropertyOfChildFuncOfUncollapsibleObjectDepth2() { test("var a = {}; a.b = {}; var c = a.b;" + "a.b.c = function (){}; a.b.c.x = 0; a.b.c.x;", "var a$b = {}; var c = a$b;" + "a$b.c = function (){}; a$b.c.x = 0; a$b.c.x;"); } public void testAddPropertyToChildFuncOfUncollapsibleObjectInLocalScope() { testSame("var a = {}; a.b = function (){}; a.b.x = 0;" + "var c = a; (function() {a.b.y = 1;})(); a.b.x; a.b.y;"); } public void testAddPropertyToChildTypeOfUncollapsibleObjectInLocalScope() { test("var a = {}; /** @constructor */ a.b = function (){}; a.b.x = 0;" + "var c = a; (function() {a.b.y = 1;})(); a.b.x; a.b.y;", "var a = {}; var a$b = function (){}; var a$b$y; var a$b$x = 0;" + "var c = a; (function() {a$b$y = 1;})(); a$b$x; a$b$y;", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAddPropertyToChildOfUncollapsibleFunctionInLocalScope() { testSame( "function a() {} a.b = {x: 0}; var c = a;" + "(function() {a.b.y = 0;})(); a.b.y;"); } public void testAddPropertyToChildOfUncollapsibleCtorInLocalScope() { test("/** @constructor */ var a = function() {}; a.b = {x: 0}; var c = a;" + "(function() {a.b.y = 0;})(); a.b.y;", "var a = function() {}; var a$b$x = 0; var a$b$y; var c = a;" + "(function() {a$b$y = 0;})(); a$b$y;"); } public void testResetObjectPropertyInLocalScope() { test("var a = {b: 0}; a.c = 1; function f() { a.c = 5; }", "var a$b = 0; var a$c = 1; function f() { a$c = 5; }"); } public void testResetFunctionPropertyInLocalScope() { test("function a() {}; a.c = 1; function f() { a.c = 5; }", "function a() {}; var a$c = 1; function f() { a$c = 5; }"); } public void testGlobalNameReferencedInLocalScopeBeforeDefined1() { // Because referencing global names earlier in the source code than they're // defined is such a common practice, we collapse them even though a runtime // exception could result (in the off-chance that the function gets called // before the alias variable is defined). test("var a = {b: 0}; function f() { a.c = 5; } a.c = 1;", "var a$b = 0; function f() { a$c = 5; } var a$c = 1;"); } public void testGlobalNameReferencedInLocalScopeBeforeDefined2() { test("var a = {b: 0}; function f() { return a.c; } a.c = 1;", "var a$b = 0; function f() { return a$c; } var a$c = 1;"); } public void testTwiceDefinedGlobalNameDepth1_1() { testSame("var a = {}; function f() { a.b(); }" + "a = function() {}; a.b = function() {};"); } public void testTwiceDefinedGlobalNameDepth1_2() { testSame("var a = {}; /** @constructor */ a = function() {};" + "a.b = {}; a.b.c = 0; function f() { a.b.d = 1; }"); } public void testTwiceDefinedGlobalNameDepth2() { test("var a = {}; a.b = {}; function f() { a.b.c(); }" + "a.b = function() {}; a.b.c = function() {};", "var a$b = {}; function f() { a$b.c(); }" + "a$b = function() {}; a$b.c = function() {};"); } public void testFunctionCallDepth1() { test("var a = {}; a.b = function(){}; var c = a.b();", "var a$b = function(){}; var c = a$b()"); } public void testFunctionCallDepth2() { test("var a = {}; a.b = {}; a.b.c = function(){}; a.b.c();", "var a$b$c = function(){}; a$b$c();"); } public void testFunctionAlias() { test("var a = {}; a.b = {}; a.b.c = function(){}; a.b.d = a.b.c;", "var a$b$c = function(){}; var a$b$d = a$b$c;"); } public void testCallToRedefinedFunction() { test("var a = {}; a.b = function(){}; a.b = function(){}; a.b();", "var a$b = function(){}; a$b = function(){}; a$b();"); } public void testCollapsePrototypeName() { test("var a = {}; a.b = {}; a.b.c = function(){}; " + "a.b.c.prototype.d = function(){}; (new a.b.c()).d();", "var a$b$c = function(){}; a$b$c.prototype.d = function(){}; " + "new a$b$c().d();"); } public void testReferencedPrototypeProperty() { test("var a = {b: {}}; a.b.c = function(){}; a.b.c.prototype.d = {};" + "e = a.b.c.prototype.d;", "var a$b$c = function(){}; a$b$c.prototype.d = {};" + "e = a$b$c.prototype.d;"); } public void testSetStaticAndPrototypePropertiesOnFunction() { test("var a = {}; a.b = function(){}; a.b.prototype.d = 0; a.b.c = 1;", "var a$b = function(){}; a$b.prototype.d = 0; var a$b$c = 1;"); } public void testReadUndefinedPropertyDepth1() { test("var a = {b: 0}; var c = a.d;", "var a$b = 0; var a = {}; var c = a.d;"); } public void testReadUndefinedPropertyDepth2() { test("var a = {b: {c: 0}}; f(a.b.c); f(a.b.d);", "var a$b$c = 0; var a$b = {}; f(a$b$c); f(a$b.d);"); } public void testCallUndefinedMethodOnObjLitDepth1() { test("var a = {b: 0}; a.c();", "var a$b = 0; var a = {}; a.c();"); } public void testCallUndefinedMethodOnObjLitDepth2() { test("var a = {b: {}}; a.b.c = function() {}; a.b.c(); a.b.d();", "var a$b = {}; var a$b$c = function() {}; a$b$c(); a$b.d();"); } public void testPropertiesOfAnUndefinedVar() { testSame("a.document = d; f(a.document.innerHTML);"); } public void testPropertyOfAnObjectThatIsNeitherFunctionNorObjLit() { testSame("var a = window; a.document = d; f(a.document)"); } public void testStaticFunctionReferencingThis1() { // Note: Google's JavaScript Style Guide says to avoid using the 'this' // keyword in a static function. test("var a = {}; a.b = function() {this.c}; var d = a.b;", "var a$b = function() {this.c}; var d = a$b;", null, UNSAFE_THIS); } public void testStaticFunctionReferencingThis2() { // This gives no warning, because "this" is in a scope whose name is not // getting collapsed. test("var a = {}; " + "a.b = function() { return function(){ return this; }; };", "var a$b = function() { return function(){ return this; }; };"); } public void testStaticFunctionReferencingThis3() { test("var a = {b: function() {this.c}};", "var a$b = function() { this.c };", null, UNSAFE_THIS); } public void testStaticFunctionReferencingThis4() { test("var a = {/** @this {Element} */ b: function() {this.c}};", "var a$b = function() { this.c };"); } public void testPrototypeMethodReferencingThis() { testSame("var A = function(){}; A.prototype = {b: function() {this.c}};"); } public void testConstructorReferencingThis() { test("var a = {}; " + "/** @constructor */ a.b = function() { this.a = 3; };", "var a$b = function() { this.a = 3; };"); } public void testSafeReferenceOfThis() { test("var a = {}; " + "/** @this {Object} */ a.b = function() { this.a = 3; };", "var a$b = function() { this.a = 3; };"); } public void testGlobalFunctionReferenceOfThis() { testSame("var a = function() { this.a = 3; };"); } public void testFunctionGivenTwoNames() { // It's okay to collapse f's properties because g is not added to the // global scope as an alias for f. (Try it in your browser.) test("var f = function g() {}; f.a = 1; h(f.a);", "var f = function g() {}; var f$a = 1; h(f$a);"); } public void testObjLitWithUsedNumericKey() { testSame("a = {40: {}, c: {}}; var d = a[40]; var e = a.c;"); } public void testObjLitWithUnusedNumericKey() { test("var a = {40: {}, c: {}}; var e = a.c;", "var a$1 = {}; var a$c = {}; var e = a$c"); } public void testObjLitWithNonIdentifierKeys() { testSame("a = {' ': 0, ',': 1}; var c = a[' '];"); } public void testChainedAssignments1() { test("var x = {}; x.y = a = 0;", "var x$y = a = 0;"); } public void testChainedAssignments2() { test("var x = {}; x.y = a = b = c();", "var x$y = a = b = c();"); } public void testChainedAssignments3() { test("var x = {y: 1}; a = b = x.y;", "var x$y = 1; a = b = x$y;"); } public void testChainedAssignments4() { test("var x = {}; a = b = x.y;", "var x = {}; a = b = x.y;"); } public void testChainedAssignments5() { test("var x = {}; a = x.y = 0;", "var x$y; a = x$y = 0;"); } public void testChainedAssignments6() { test("var x = {}; a = x.y = b = c();", "var x$y; a = x$y = b = c();"); } public void testChainedAssignments7() { test("var x = {}; a = x.y = {}; /** @constructor */ x.y.z = function() {};", "var x$y; a = x$y = {}; var x$y$z = function() {};", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testChainedVarAssignments1() { test("var x = {y: 1}; var a = x.y = 0;", "var x$y = 1; var a = x$y = 0;"); } public void testChainedVarAssignments2() { test("var x = {y: 1}; var a = x.y = b = 0;", "var x$y = 1; var a = x$y = b = 0;"); } public void testChainedVarAssignments3() { test("var x = {y: {z: 1}}; var b = 0; var a = x.y.z = 1; var c = 2;", "var x$y$z = 1; var b = 0; var a = x$y$z = 1; var c = 2;"); } public void testChainedVarAssignments4() { test("var x = {}; var a = b = x.y = 0;", "var x$y; var a = b = x$y = 0;"); } public void testChainedVarAssignments5() { test("var x = {y: {}}; var a = b = x.y.z = 0;", "var x$y$z; var a = b = x$y$z = 0;"); } public void testPeerAndSubpropertyOfUncollapsibleProperty() { test("var x = {}; var a = x.y = 0; x.w = 1; x.y.z = 2;" + "b = x.w; c = x.y.z;", "var x$y; var a = x$y = 0; var x$w = 1; x$y.z = 2;" + "b = x$w; c = x$y.z;"); } public void testComplexAssignmentAfterInitialAssignment() { test("var d = {}; d.e = {}; d.e.f = 0; a = b = d.e.f = 1;", "var d$e$f = 0; a = b = d$e$f = 1;"); } public void testRenamePrefixOfUncollapsibleProperty() { test("var d = {}; d.e = {}; a = b = d.e.f = 0;", "var d$e$f; a = b = d$e$f = 0;"); } public void testNewOperator() { // Using the new operator on a name doesn't prevent its (static) properties // from getting collapsed. test("var a = {}; a.b = function() {}; a.b.c = 1; var d = new a.b();", "var a$b = function() {}; var a$b$c = 1; var d = new a$b();"); } public void testMethodCall() { test("var a = {}; a.b = function() {}; var d = a.b();", "var a$b = function() {}; var d = a$b();"); } public void testObjLitDefinedInLocalScopeIsLeftAlone() { test("var a = {}; a.b = function() {};" + "a.b.prototype.f_ = function() {" + " var x = { p: '', q: '', r: ''}; var y = x.q;" + "};", "var a$b = function() {};" + "a$b.prototype.f_ = function() {" + " var x = { p: '', q: '', r: ''}; var y = x.q;" + "};"); } public void testPropertiesOnBothSidesOfAssignment() { // This verifies that replacements are done in the right order. Collapsing // the l-value in an assignment affects the parse tree immediately above // the r-value, so we update all rvalues before any lvalues. test("var a = {b: 0}; a.c = a.b;", "var a$b = 0; var a$c = a$b;"); } public void testCallOnUndefinedProperty() { // The "inherits" property is not explicitly defined on a.b anywhere, but // it is accessed as though it certainly exists (it is called), so we infer // that it must be an uncollapsible property that has come into existence // some other way. test("var a = {}; a.b = function(){}; a.b.inherits(x);", "var a$b = function(){}; a$b.inherits(x);"); } public void testGetPropOnUndefinedProperty() { // The "superClass_" property is not explicitly defined on a.b anywhere, // but it is accessed as though it certainly exists (a subproperty of it // is accessed), so we infer that it must be an uncollapsible property that // has come into existence some other way. test("var a = {b: function(){}}; a.b.prototype.c =" + "function() { a.b.superClass_.c.call(this); }", "var a$b = function(){}; a$b.prototype.c =" + "function() { a$b.superClass_.c.call(this); }"); } public void testLocalAlias1() { test("var a = {b: 3}; function f() { var x = a; f(x.b); }", "var a$b = 3; function f() { var x = null; f(a$b); }"); } public void testLocalAlias2() { test("var a = {b: 3, c: 4}; function f() { var x = a; f(x.b); f(x.c);}", "var a$b = 3; var a$c = 4; " + "function f() { var x = null; f(a$b); f(a$c);}"); } public void testLocalAlias3() { test("var a = {b: 3, c: {d: 5}}; " + "function f() { var x = a; f(x.b); f(x.c); f(x.c.d); }", "var a$b = 3; var a$c = {d: 5}; " + "function f() { var x = null; f(a$b); f(a$c); f(a$c.d);}"); } public void testLocalAlias4() { test("var a = {b: 3}; var c = {d: 5}; " + "function f() { var x = a; var y = c; f(x.b); f(y.d); }", "var a$b = 3; var c$d = 5; " + "function f() { var x = null; var y = null; f(a$b); f(c$d);}"); } public void testLocalAlias5() { test("var a = {b: {c: 5}}; " + "function f() { var x = a; var y = x.b; f(a.b.c); f(y.c); }", "var a$b$c = 5; " + "function f() { var x = null; var y = null; f(a$b$c); f(a$b$c);}"); } public void testLocalAlias6() { test("var a = {b: 3}; function f() { var x = a; if (x.b) { f(x.b); } }", "var a$b = 3; function f() { var x = null; if (a$b) { f(a$b); } }"); } public void testLocalAlias7() { test("var a = {b: {c: 5}}; function f() { var x = a.b; f(x.c); }", "var a$b$c = 5; function f() { var x = null; f(a$b$c); }"); } public void testGlobalWriteToAncestor() { testSame("var a = {b: 3}; function f() { var x = a; f(a.b); } a = 5;"); } public void testGlobalWriteToNonAncestor() { test("var a = {b: 3}; function f() { var x = a; f(a.b); } a.b = 5;", "var a$b = 3; function f() { var x = null; f(a$b); } a$b = 5;"); } public void testLocalWriteToAncestor() { testSame("var a = {b: 3}; function f() { a = 5; var x = a; f(a.b); } "); } public void testLocalWriteToNonAncestor() { test("var a = {b: 3}; " + "function f() { a.b = 5; var x = a; f(a.b); }", "var a$b = 3; function f() { a$b = 5; var x = null; f(a$b); } "); } public void testNonWellformedAlias1() { testSame("var a = {b: 3}; function f() { f(x); var x = a; f(x.b); }"); } public void testNonWellformedAlias2() { testSame("var a = {b: 3}; " + "function f() { if (false) { var x = a; f(x.b); } f(x); }"); } public void testLocalAliasOfAncestor() { testSame("var a = {b: {c: 5}}; function g() { f(a); } " + "function f() { var x = a.b; f(x.c); }"); } public void testGlobalAliasOfAncestor() { testSame("var a = {b: {c: 5}}; var y = a; " + "function f() { var x = a.b; f(x.c); }"); } public void testLocalAliasOfOtherName() { testSame("var foo = function() { return {b: 3}; };" + "var a = foo(); a.b = 5; " + "function f() { var x = a.b; f(x); }"); } public void testLocalAliasOfFunction() { test("var a = function() {}; a.b = 5; " + "function f() { var x = a.b; f(x); }", "var a = function() {}; var a$b = 5; " + "function f() { var x = null; f(a$b); }"); } public void testNoInlineGetpropIntoCall() { test("var b = x; function f() { var a = b; a(); }", "var b = x; function f() { var a = null; b(); }"); test("var b = {}; b.c = x; function f() { var a = b.c; a(); }", "var b$c = x; function f() { var a = null; b$c(); }"); } public void testInlineAliasWithModifications() { testSame("var x = 10; function f() { var y = x; x++; alert(y)} "); testSame("var x = 10; function f() { var y = x; x+=1; alert(y)} "); test("var x = {}; x.x = 10; function f() {var y=x.x; x.x++; alert(y)}", "var x$x = 10; function f() {var y=x$x; x$x++; alert(y)}"); test("var x = {}; x.x = 10; function f() {var y=x.x; x.x+=1; alert(y)}", "var x$x = 10; function f() {var y=x$x; x$x+=1; alert(y)}"); } public void testCollapsePropertyOnExternType() { collapsePropertiesOnExternTypes = true; test("String.myFunc = function() {}; String.myFunc();", "var String$myFunc = function() {}; String$myFunc()"); } public void testCollapseForEachWithoutExterns() { collapsePropertiesOnExternTypes = true; test("/** @constructor */function Array(){};\n", "if (!Array.forEach) {\n" + " Array.forEach = function() {};\n" + "}", "if (!Array$forEach) {\n" + " var Array$forEach = function() {};\n" + "}", null, null); } public void testNoCollapseForEachInExterns() { collapsePropertiesOnExternTypes = true; test("/** @constructor */ function Array() {}" + "Array.forEach = function() {}", "if (!Array.forEach) {\n" + " Array.forEach = function() {};\n" + "}", "if (!Array.forEach) {\n" + " Array.forEach = function() {};\n" + "}", null, null); } public void testIssue931() { collapsePropertiesOnExternTypes = true; testSame( "function f() {\n" + " return function () {\n" + " var args = arguments;\n" + " setTimeout(function() { alert(args); }, 0);\n" + " }\n" + "};\n"); } public void testDoNotCollapsePropertyOnExternType() { collapsePropertiesOnExternTypes = false; test("String.myFunc = function() {}; String.myFunc()", "String.myFunc = function() {}; String.myFunc()"); } public void testBug1704733() { String prelude = "function protect(x) { return x; }" + "function O() {}" + "protect(O).m1 = function() {};" + "protect(O).m2 = function() {};" + "protect(O).m3 = function() {};"; testSame(prelude + "alert(O.m1); alert(O.m2()); alert(!O.m3);"); } public void testBug1956277() { test("var CONST = {}; CONST.URL = 3;", "var CONST$URL = 3;"); } public void testBug1974371() { test( "/** @enum {Object} */ var Foo = {A: {c: 2}, B: {c: 3}};" + "for (var key in Foo) {}", "var Foo$A = {c: 2}; var Foo$B = {c: 3};" + "var Foo = {A: Foo$A, B: Foo$B};" + "for (var key in Foo) {}"); } private final String COMMON_ENUM = "/** @enum {Object} */ var Foo = {A: {c: 2}, B: {c: 3}};"; public void testEnumOfObjects1() { test( COMMON_ENUM + "for (var key in Foo.A) {}", "var Foo$A = {c: 2}; var Foo$B$c = 3; for (var key in Foo$A) {}"); } public void testEnumOfObjects2() { test( COMMON_ENUM + "foo(Foo.A.c);", "var Foo$A$c = 2; var Foo$B$c = 3; foo(Foo$A$c);"); } public void testEnumOfObjects3() { test( "var x = {c: 2}; var y = {c: 3};" + "/** @enum {Object} */ var Foo = {A: x, B: y};" + "for (var key in Foo) {}", "var x = {c: 2}; var y = {c: 3};" + "var Foo$A = x; var Foo$B = y; var Foo = {A: Foo$A, B: Foo$B};" + "for (var key in Foo) {}"); } public void testEnumOfObjects4() { // Note that this produces bad code, but that's OK, because // checkConsts will yell at you for reassigning an enum value. // (enum values have to be constant). test( COMMON_ENUM + "for (var key in Foo) {} Foo.A = 3; alert(Foo.A);", "var Foo$A = {c: 2}; var Foo$B = {c: 3};" + "var Foo = {A: Foo$A, B: Foo$B};" + "for (var key in Foo) {} Foo$A = 3; alert(Foo$A);"); } public void testObjectOfObjects1() { // Basically the same as testEnumOfObjects4, but without the // constant enum values. testSame( "var Foo = {a: {c: 2}, b: {c: 3}};" + "for (var key in Foo) {} Foo.a = 3; alert(Foo.a);"); } public void testReferenceInAnonymousObject0() { test("var a = {};" + "a.b = function(){};" + "a.b.prototype.c = function(){};" + "var d = a.b.prototype.c;", "var a$b = function(){};" + "a$b.prototype.c = function(){};" + "var d = a$b.prototype.c;"); } public void testReferenceInAnonymousObject1() { test("var a = {};" + "a.b = function(){};" + "var d = a.b.prototype.c;", "var a$b = function(){};" + "var d = a$b.prototype.c;"); } public void testReferenceInAnonymousObject2() { test("var a = {};" + "a.b = function(){};" + "a.b.prototype.c = function(){};" + "var d = {c: a.b.prototype.c};", "var a$b = function(){};" + "a$b.prototype.c = function(){};" + "var d$c = a$b.prototype.c;"); } public void testReferenceInAnonymousObject3() { test("function CreateClass(a$$1) {}" + "var a = {};" + "a.b = function(){};" + "a.b.prototype.c = function(){};" + "a.d = CreateClass({c: a.b.prototype.c});", "function CreateClass(a$$1) {}" + "var a$b = function(){};" + "a$b.prototype.c = function(){};" + "var a$d = CreateClass({c: a$b.prototype.c});"); } public void testReferenceInAnonymousObject4() { test("function CreateClass(a) {}" + "var a = {};" + "a.b = CreateClass({c: function() {}});" + "a.d = CreateClass({c: a.b.c});", "function CreateClass(a$$1) {}" + "var a$b = CreateClass({c: function() {}});" + "var a$d = CreateClass({c: a$b.c});"); } public void testReferenceInAnonymousObject5() { test("function CreateClass(a) {}" + "var a = {};" + "a.b = CreateClass({c: function() {}});" + "a.d = CreateClass({c: a.b.prototype.c});", "function CreateClass(a$$1) {}" + "var a$b = CreateClass({c: function() {}});" + "var a$d = CreateClass({c: a$b.prototype.c});"); } public void testCrashInCommaOperator() { test("var a = {}; a.b = function() {},a.b();", "var a$b; a$b=function() {},a$b();"); } public void testCrashInNestedAssign() { test("var a = {}; if (a.b = function() {}) a.b();", "var a$b; if (a$b=function() {}) { a$b(); }"); } public void testTwinReferenceCancelsChildCollapsing() { test("var a = {}; if (a.b = function() {}) { a.b.c = 3; a.b(a.b.c); }", "var a$b; if (a$b = function() {}) { a$b.c = 3; a$b(a$b.c); }"); } public void testPropWithDollarSign() { test("var a = {$: 3}", "var a$$0 = 3;"); } public void testPropWithDollarSign2() { test("var a = {$: function(){}}", "var a$$0 = function(){};"); } public void testPropWithDollarSign3() { test("var a = {b: {c: 3}, b$c: function(){}}", "var a$b$c = 3; var a$b$0c = function(){};"); } public void testPropWithDollarSign4() { test("var a = {$$: {$$$: 3}};", "var a$$0$0$$0$0$0 = 3;"); } public void testPropWithDollarSign5() { test("var a = {b: {$0c: true}, b$0c: false};", "var a$b$$00c = true; var a$b$00c = false;"); } public void testConstKey() { test("var foo = {A: 3};", "var foo$A = 3;"); } public void testPropertyOnGlobalCtor() { test("/** @constructor */ function Map() {} Map.foo = 3; Map;", "function Map() {} var Map$foo = 3; Map;"); } public void testPropertyOnGlobalInterface() { test("/** @interface */ function Map() {} Map.foo = 3; Map;", "function Map() {} var Map$foo = 3; Map;"); } public void testPropertyOnGlobalFunction() { testSame("function Map() {} Map.foo = 3; Map;"); } public void testIssue389() { test( "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "/** @constructor */" + "dojo.gfx.Shape = function() {};" + "dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);", "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "/** @constructor */" + "var dojo$gfx$Shape = function() {};" + "dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAliasedTopLevelName() { testSame( "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "dojo.gfx.Shape = {SQUARE: 2};" + "dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);" + "alias(dojo$gfx$Shape$SQUARE);"); } public void testAliasedTopLevelEnum() { test( "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "/** @enum {number} */" + "dojo.gfx.Shape = {SQUARE: 2};" + "dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);" + "alias(dojo.gfx.Shape.SQUARE);", "function alias() {}" + "var dojo = {};" + "dojo.gfx = {};" + "dojo.declare = function() {};" + "/** @constructor */" + "var dojo$gfx$Shape = {SQUARE: 2};" + "dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');" + "alias(dojo);" + "alias(dojo$gfx$Shape.SQUARE);", null, CollapseProperties.UNSAFE_NAMESPACE_WARNING); } public void testAssignFunctionBeforeDefinition() { testSame( "f = function() {};" + "var f = null;"); } public void testObjectLitBeforeDefinition() { testSame( "a = {b: 3};" + "var a = null;" + "this.c = a.b;"); } public void testTypedef1() { test("var foo = {};" + "/** @typedef {number} */ foo.Baz;", "var foo = {}; var foo$Baz;"); } public void testTypedef2() { test("var foo = {};" + "/** @typedef {number} */ foo.Bar.Baz;" + "foo.Bar = function() {};", "var foo$Bar$Baz; var foo$Bar = function(){};"); } public void testDelete1() { testSame( "var foo = {};" + "foo.bar = 3;" + "delete foo.bar;"); } public void testDelete2() { test( "var foo = {};" + "foo.bar = 3;" + "foo.baz = 3;" + "delete foo.bar;", "var foo = {};" + "foo.bar = 3;" + "var foo$baz = 3;" + "delete foo.bar;"); } public void testDelete3() { testSame( "var foo = {bar: 3};" + "delete foo.bar;"); } public void testDelete4() { test( "var foo = {bar: 3, baz: 3};" + "delete foo.bar;", "var foo$baz=3;var foo={bar:3};delete foo.bar"); } public void testDelete5() { test( "var x = {};" + "x.foo = {};" + "x.foo.bar = 3;" + "delete x.foo.bar;", "var x$foo = {};" + "x$foo.bar = 3;" + "delete x$foo.bar;"); } public void testDelete6() { test( "var x = {};" + "x.foo = {};" + "x.foo.bar = 3;" + "x.foo.baz = 3;" + "delete x.foo.bar;", "var x$foo = {};" + "x$foo.bar = 3;" + "var x$foo$baz = 3;" + "delete x$foo.bar;"); } public void testDelete7() { test( "var x = {};" + "x.foo = {bar: 3};" + "delete x.foo.bar;", "var x$foo = {bar: 3};" + "delete x$foo.bar;"); } public void testDelete8() { test( "var x = {};" + "x.foo = {bar: 3, baz: 3};" + "delete x.foo.bar;", "var x$foo$baz = 3; var x$foo = {bar: 3};" + "delete x$foo.bar;"); } public void testDelete9() { testSame( "var x = {};" + "x.foo = {};" + "x.foo.bar = 3;" + "delete x.foo;"); } public void testDelete10() { testSame( "var x = {};" + "x.foo = {bar: 3};" + "delete x.foo;"); } public void testDelete11() { // Constructors are always collapsed. test( "var x = {};" + "x.foo = {};" + "/** @constructor */ x.foo.Bar = function() {};" + "delete x.foo;", "var x = {};" + "x.foo = {};" + "var x$foo$Bar = function() {};" + "delete x.foo;", null, CollapseProperties.NAMESPACE_REDEFINED_WARNING); } public void testPreserveConstructorDoc() { test("var foo = {};" + "/** @constructor */\n" + "foo.bar = function() {}", "var foo$bar = function() {}"); Node root = getLastCompiler().getRoot(); Node fooBarNode = findQualifiedNameNode("foo$bar", root); Node varNode = fooBarNode.getParent(); assertTrue(varNode.isVar()); assertTrue(varNode.getJSDocInfo().isConstructor()); } }
public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "x = 1 / 0"); fold("x = 3 % 2", "x = 1"); fold("x = 3 % -2", "x = 1"); fold("x = -1 % 3", "x = -1"); fold("x = 1 % 0", "x = 1 % 0"); }
com.google.javascript.jscomp.PeepholeFoldConstantsTest::testFoldArithmetic
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
562
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
testFoldArithmetic
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.javascript.rhino.Node; import java.util.List; import java.util.Map; import java.util.Set; /** * Tests for {@link PeepholeFoldConstants} in isolation. Tests for * the interaction of multiple peephole passes are in * {@link PeepholeIntegrationTest}. */ public class PeepholeFoldConstantsTest extends CompilerTestCase { // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeFoldConstantsTest(boolean compareAsTree) { super("", compareAsTree); } public PeepholeFoldConstantsTest() { super(""); } @Override public void setUp() { enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants()); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } private void fold(String js, String expected, DiagnosticType warning) { test(js, expected, warning); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. private void assertResultString(String js, String expected) { PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false); scTest.test(js, expected); } public void testUndefinedComparison1() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUndefinedComparison2() { fold("\"123\" !== void 0", "true"); fold("\"123\" === void 0", "false"); fold("void 0 !== \"123\"", "true"); fold("void 0 === \"123\"", "false"); } public void testUndefinedComparison3() { fold("\"123\" !== undefined", "true"); fold("\"123\" === undefined", "false"); fold("undefined !== \"123\"", "true"); fold("undefined === \"123\"", "false"); } public void testUndefinedComparison4() { fold("1 !== void 0", "true"); fold("1 === void 0", "false"); fold("null !== void 0", "true"); fold("null === void 0", "false"); fold("undefined !== void 0", "false"); fold("undefined === void 0", "true"); } public void testUnaryOps() { // These cases are handled by PeepholeRemoveDeadCode. foldSame("!foo()"); foldSame("~foo()"); foldSame("-foo()"); // These cases are handled here. fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); fold("a=-0", "a=0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=+true", "a=1"); fold("a=+10", "a=10"); fold("a=+false", "a=0"); foldSame("a=+foo()"); foldSame("a=+f"); fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable fold("a=+0", "a=0"); fold("a=+Infinity", "a=Infinity"); fold("a=+NaN", "a=NaN"); fold("a=+-7", "a=-7"); fold("a=+.5", "a=.5"); fold("a=~0x100000000", "a=~0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~-0x100000000", "a=~-0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { // Negatives are folded into a single number node. assertResultString("a=-1", "a=-1"); assertResultString("a=~0", "a=-1"); assertResultString("a=~1", "a=-2"); assertResultString("a=~101", "a=-102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // unfoldable, because the right-side may be the result fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // folded, but not here. foldSame("a = x || false ? b : c"); foldSame("a = x && true ? b : c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || false || bar()", "x = foo()||bar()"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("x = foo() && false || bar()", "x = foo()&&false||bar()"); fold("1 && b()", "b()"); fold("a() && (1 && b())", "a() && b()"); // TODO(johnlenz): Consider folding the following to: // "(a(),1) && b(); fold("(a() && 1) && b()", "(a() && 1) && b()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = 1 ^ 1", "x = 0"); fold("x = 1 ^ 2", "x = 3"); fold("x = 3 ^ 1", "x = 2"); fold("x = 3 ^ 3", "x = 0"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1"); fold("x = 1.1 & 1", "x = 1"); fold("x = 1 & 3000000000", "x = 0"); fold("x = 3000000000 & 1", "x = 0"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1"); foldSame("x = 1 | 3E9"); fold("x = 1 | 3000000001", "x = -1294967295"); } public void testFoldBitwiseOp2() { fold("x = y & 1 & 1", "x = y & 1"); fold("x = y & 1 & 2", "x = y & 0"); fold("x = y & 3 & 1", "x = y & 1"); fold("x = 3 & y & 1", "x = y & 1"); fold("x = y & 3 & 3", "x = y & 3"); fold("x = 3 & y & 3", "x = y & 3"); fold("x = y | 1 | 1", "x = y | 1"); fold("x = y | 1 | 2", "x = y | 3"); fold("x = y | 3 | 1", "x = y | 3"); fold("x = 3 | y | 1", "x = y | 3"); fold("x = y | 3 | 3", "x = y | 3"); fold("x = 3 | y | 3", "x = y | 3"); fold("x = y ^ 1 ^ 1", "x = y ^ 0"); fold("x = y ^ 1 ^ 2", "x = y ^ 3"); fold("x = y ^ 3 ^ 1", "x = y ^ 2"); fold("x = 3 ^ y ^ 1", "x = y ^ 2"); fold("x = y ^ 3 ^ 3", "x = y ^ 0"); fold("x = 3 ^ y ^ 3", "x = y ^ 0"); fold("x = Infinity | NaN", "x=0"); fold("x = 12 | NaN", "x=12"); } public void testFoldingMixTypes() { fold("x = x + '2'", "x+='2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x-=2"); fold("x = x ^ '2'", "x^=2"); fold("x = '2' ^ x", "x^=2"); fold("x = '2' & x", "x&=2"); fold("x = '2' | x", "x|=2"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingAdd() { fold("x = null + true", "x=1"); foldSame("x = a + true"); } public void testFoldBitwiseOpStringCompare() { assertResultString("x = -1 | 0", "x=-1"); // EXPR_RESULT case is in in PeepholeIntegrationTest } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { // Negative numbers. assertResultString("x = -1 << 1", "x=-2"); assertResultString("x = -1 << 8", "x=-256"); assertResultString("x = -1 >> 1", "x=-1"); assertResultString("x = -2 >> 1", "x=-1"); assertResultString("x = -1 >> 0", "x=-1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = ''"); // cannot fold (but nice if we can) } public void testFoldConstructor() { fold("x = this[new String('a')]", "x = this['a']"); fold("x = ob[new String(12)]", "x = ob['12']"); fold("x = ob[new String(false)]", "x = ob['false']"); fold("x = ob[new String(null)]", "x = ob['null']"); foldSame("x = ob[new String(a)]"); foldSame("x = new String('a')"); foldSame("x = (new String('a'))[3]"); } public void testStringIndexOf() { fold("x = 'abcdef'.indexOf('b')", "x = 1"); fold("x = 'abcdefbe'.indexOf('b', 2)", "x = 6"); fold("x = 'abcdef'.indexOf('bcd')", "x = 1"); fold("x = 'abcdefsdfasdfbcdassd'.indexOf('bcd', 4)", "x = 13"); fold("x = 'abcdef'.lastIndexOf('b')", "x = 1"); fold("x = 'abcdefbe'.lastIndexOf('b')", "x = 6"); fold("x = 'abcdefbe'.lastIndexOf('b', 5)", "x = 1"); // Both elements must be string. Dont do anything if either one is not // string. fold("x = 'abc1def'.indexOf(1)", "x = 3"); fold("x = 'abcNaNdef'.indexOf(NaN)", "x = 3"); fold("x = 'abcundefineddef'.indexOf(undefined)", "x = 3"); fold("x = 'abcnulldef'.indexOf(null)", "x = 3"); fold("x = 'abctruedef'.indexOf(true)", "x = 3"); // The following testcase fails with JSC_PARSE_ERROR. Hence omitted. // foldSame("x = 1.indexOf('bcd');"); foldSame("x = NaN.indexOf('bcd')"); foldSame("x = undefined.indexOf('bcd')"); foldSame("x = null.indexOf('bcd')"); foldSame("x = true.indexOf('bcd')"); foldSame("x = false.indexOf('bcd')"); // Avoid dealing with regex or other types. foldSame("x = 'abcdef'.indexOf(/b./)"); foldSame("x = 'abcdef'.indexOf({a:2})"); foldSame("x = 'abcdef'.indexOf([1,2])"); } public void testStringJoinAddSparse() { fold("x = [,,'a'].join(',')", "x = ',,a'"); } public void testStringJoinAdd() { fold("x = ['a', 'b', 'c'].join('')", "x = \"abc\""); fold("x = [].join(',')", "x = \"\""); fold("x = ['a'].join(',')", "x = \"a\""); fold("x = ['a', 'b', 'c'].join(',')", "x = \"a,b,c\""); fold("x = ['a', foo, 'b', 'c'].join(',')", "x = [\"a\",foo,\"b,c\"].join(\",\")"); fold("x = [foo, 'a', 'b', 'c'].join(',')", "x = [foo,\"a,b,c\"].join(\",\")"); fold("x = ['a', 'b', 'c', foo].join(',')", "x = [\"a,b,c\",foo].join(\",\")"); // Works with numbers fold("x = ['a=', 5].join('')", "x = \"a=5\""); fold("x = ['a', '5'].join(7)", "x = \"a75\""); // Works on boolean fold("x = ['a=', false].join('')", "x = \"a=false\""); fold("x = ['a', '5'].join(true)", "x = \"atrue5\""); fold("x = ['a', '5'].join(false)", "x = \"afalse5\""); // Only optimize if it's a size win. fold("x = ['a', '5', 'c'].join('a very very very long chain')", "x = [\"a\",\"5\",\"c\"].join(\"a very very very long chain\")"); // TODO(user): Its possible to fold this better. foldSame("x = ['', foo].join(',')"); foldSame("x = ['', foo, ''].join(',')"); fold("x = ['', '', foo, ''].join(',')", "x = [',', foo, ''].join(',')"); fold("x = ['', '', foo, '', ''].join(',')", "x = [',', foo, ','].join(',')"); fold("x = ['', '', foo, '', '', bar].join(',')", "x = [',', foo, ',', bar].join(',')"); fold("x = [1,2,3].join('abcdef')", "x = '1abcdef2abcdef3'"); fold("x = [1,2].join()", "x = '1,2'"); fold("x = [null,undefined,''].join(',')", "x = ',,'"); fold("x = [null,undefined,0].join(',')", "x = ',,0'"); // This can be folded but we don't currently. foldSame("x = [[1,2],[3,4]].join()"); // would like: "x = '1,2,3,4'" } public void testStringJoinAdd_b1992789() { fold("x = ['a'].join('')", "x = \"a\""); fold("x = [foo()].join('')", "x = '' + foo()"); fold("[foo()].join('')", "'' + foo()"); } public void testFoldStringSubstr() { fold("x = 'abcde'.substr(0,2)", "x = 'ab'"); fold("x = 'abcde'.substr(1,2)", "x = 'bc'"); fold("x = 'abcde'['substr'](1,3)", "x = 'bcd'"); fold("x = 'abcde'.substr(2)", "x = 'cde'"); // we should be leaving negative indexes alone for now foldSame("x = 'abcde'.substr(-1)"); foldSame("x = 'abcde'.substr(1, -2)"); foldSame("x = 'abcde'.substr(1, 2, 3)"); foldSame("x = 'a'.substr(0, 2)"); } public void testFoldStringSubstring() { fold("x = 'abcde'.substring(0,2)", "x = 'ab'"); fold("x = 'abcde'.substring(1,2)", "x = 'b'"); fold("x = 'abcde'['substring'](1,3)", "x = 'bc'"); fold("x = 'abcde'.substring(2)", "x = 'cde'"); // we should be leaving negative indexes alone for now foldSame("x = 'abcde'.substring(-1)"); foldSame("x = 'abcde'.substring(1, -2)"); foldSame("x = 'abcde'.substring(1, 2, 3)"); foldSame("x = 'a'.substring(0, 2)"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "x = 1 / 0"); fold("x = 3 % 2", "x = 1"); fold("x = 3 % -2", "x = 1"); fold("x = -1 % 3", "x = -1"); fold("x = 1 % 0", "x = 1 % 0"); } public void testFoldArithmetic2() { foldSame("x = y + 10 + 20"); foldSame("x = y / 2 / 4"); fold("x = y * 2.25 * 3", "x = y * 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 864E5"); } public void testFoldArithmetic3() { fold("x = null * undefined", "x = NaN"); fold("x = null * 1", "x = 0"); fold("x = (null - 1) * 2", "x = -2"); fold("x = (null + 1) * 2", "x = 2"); } public void testFoldArithmeticInfinity() { fold("x=-Infinity-2", "x=-Infinity"); fold("x=Infinity-2", "x=Infinity"); fold("x=Infinity*5", "x=Infinity"); } public void testFoldArithmeticStringComp() { // Negative Numbers. assertResultString("x = 10 - 20", "x=-10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = true == true", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = true === true", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); // TODO(johnlenz): It would be nice to handle these cases as well. foldSame("1 === '1'"); foldSame("1 === true"); foldSame("1 !== '1'"); foldSame("1 !== true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldGetElem() { fold("x = [,10][0]", "x = void 0"); fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); fold("x = [10, 20][0.5]", "", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); fold("x = [10, 20][-1]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); fold("x = [10, 20][2]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldLeft() { foldSame("(+x - 1) + 2"); // not yet fold("(+x + 1) + 2", "+x + 3"); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Not handled yet fold("x = [,,1].length", "x = 3"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); fold("x = y.length", "x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); fold("x = typeof function() {}", "x = 'function'"); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("!0 instanceof Object", "false"); fold("!0 instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); fold("(function() {}) instanceof Object", "true"); // An unknown value should never be folded. foldSame("x instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 fold("print(1/3)", "print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOps() { fold("x=x+y", "x+=y"); foldSame("x=y+x"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); fold("x=x-y", "x-=y"); foldSame("x=y-x"); fold("x=x|y", "x|=y"); fold("x=y|x", "x|=y"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); } public void testFoldAdd1() { fold("x=false+1","x=1"); fold("x=true+1","x=2"); fold("x=1+false","x=1"); fold("x=1+true","x=2"); } public void testFoldLiteralNames() { foldSame("NaN == NaN"); foldSame("Infinity == Infinity"); foldSame("Infinity == NaN"); fold("undefined == NaN", "false"); fold("undefined == Infinity", "false"); foldSame("Infinity >= Infinity"); foldSame("NaN >= NaN"); } public void testFoldLiteralsTypeMismatches() { fold("true == true", "true"); fold("true == false", "false"); fold("true == null", "false"); fold("false == null", "false"); // relational operators convert its operands fold("null <= null", "true"); // 0 = 0 fold("null >= null", "true"); fold("null > null", "false"); fold("null < null", "false"); fold("false >= null", "true"); // 0 = 0 fold("false <= null", "true"); fold("false > null", "false"); fold("false < null", "false"); fold("true >= null", "true"); // 1 > 0 fold("true <= null", "false"); fold("true > null", "true"); fold("true < null", "false"); fold("true >= false", "true"); // 1 > 0 fold("true <= false", "false"); fold("true > false", "true"); fold("true < false", "false"); } public void testFoldLeftChildConcat() { foldSame("x +5 + \"1\""); fold("x+\"5\" + \"1\"", "x + \"51\""); // fold("\"a\"+(c+\"b\")","\"a\"+c+\"b\""); fold("\"a\"+(\"b\"+c)","\"ab\"+c"); } public void testFoldLeftChildOp() { fold("x * Infinity * 2", "x * Infinity"); foldSame("x - Infinity - 2"); // want "x-Infinity" foldSame("x - 1 + Infinity"); foldSame("x - 2 + 1"); foldSame("x - 2 + 3"); foldSame("1 + x - 2 + 1"); foldSame("1 + x - 2 + 3"); foldSame("1 + x - 2 + 3 - 1"); foldSame("f(x)-0"); foldSame("x-0-0"); foldSame("x+2-2+2"); foldSame("x+2-2+2-2"); foldSame("x-2+2"); foldSame("x-2+2-2"); foldSame("x-2+2-2+2"); foldSame("1+x-0-NaN"); foldSame("1+f(x)-0-NaN"); foldSame("1+x-0+NaN"); foldSame("1+f(x)-0+NaN"); foldSame("1+x+NaN"); // unfoldable foldSame("x+2-2"); // unfoldable foldSame("x+2"); // nothing to do foldSame("x-2"); // nothing to do } public void testFoldSimpleArithmeticOp() { foldSame("x*NaN"); foldSame("NaN/y"); foldSame("f(x)-0"); foldSame("f(x)*1"); foldSame("1*f(x)"); foldSame("0+a+b"); foldSame("0-a-b"); foldSame("a+b-0"); foldSame("(1+x)*NaN"); foldSame("(1+f(x))*NaN"); // don't fold side-effects } public void testFoldLiteralsAsNumbers() { fold("x/'12'","x/12"); fold("x/('12'+'6')", "x/126"); fold("true*x", "1*x"); fold("x/false", "x/0"); // should we add an error check? :) } public void testNotFoldBackToTrueFalse() { foldSame("!0"); foldSame("!1"); fold("!3", "false"); } public void testFoldBangConstants() { fold("1 + !0", "2"); fold("1 + !1", "1"); fold("'a ' + !1", "'a false'"); fold("'a ' + !0", "'a true'"); } public void testFoldMixed() { fold("''+[1]", "'1'"); foldSame("false+[]"); // would like: "\"false\"" } public void testFoldVoid() { foldSame("void 0"); fold("void 1", "void 0"); fold("void x", "void 0"); fold("void x()", "void x()"); } public void testJoinBug() { fold("var x = [].join();", "var x = '';"); fold("var x = [x].join();", "var x = '' + x;"); foldSame("var x = [x,y].join();"); foldSame("var x = [x,y,z].join();"); foldSame("shape['matrix'] = [\n" + " Number(headingCos2).toFixed(4),\n" + " Number(-headingSin2).toFixed(4),\n" + " Number(headingSin2 * yScale).toFixed(4),\n" + " Number(headingCos2 * yScale).toFixed(4),\n" + " 0,\n" + " 0\n" + " ].join()"); } public void testToUpper() { fold("'a'.toUpperCase()", "'A'"); fold("'A'.toUpperCase()", "'A'"); fold("'aBcDe'.toUpperCase()", "'ABCDE'"); } public void testToLower() { fold("'A'.toLowerCase()", "'a'"); fold("'a'.toLowerCase()", "'a'"); fold("'aBcDe'.toLowerCase()", "'abcde'"); } private static final List<String> LITERAL_OPERANDS = ImmutableList.of( "null", "undefined", "void 0", "true", "false", "0", "1", "''", "'123'", "'abc'", "'def'", "NaN", "Infinity" // TODO(nicksantos): Add more literals //-Infinity //"({})", //"[]", //"[0]", //"Object", //"(function() {})" ); public void testInvertibleOperators() { Map<String, String> inverses = ImmutableMap.<String, String>builder() .put("==", "!=") .put("===", "!==") .put("<=", ">") .put("<", ">=") .put(">=", "<") .put(">", "<=") .put("!=", "==") .put("!==", "===") .build(); Set<String> comparators = ImmutableSet.of("<=", "<", ">=", ">"); Set<String> equalitors = ImmutableSet.of("==", "==="); Set<String> uncomparables = ImmutableSet.of("undefined", "void 0"); List<String> operators = ImmutableList.copyOf(inverses.values()); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = 0; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); String inverse = inverses.get(op); // Test invertability. if (comparators.contains(op) && (uncomparables.contains(a) || uncomparables.contains(b))) { assertSameResults(join(a, op, b), "false"); assertSameResults(join(a, inverse, b), "false"); } else if (a.equals(b) && equalitors.contains(op)) { if (a.equals("NaN") || a.equals("Infinity")) { foldSame(join(a, op, b)); foldSame(join(a, inverse, b)); } else { assertSameResults(join(a, op, b), "true"); assertSameResults(join(a, inverse, b), "false"); } } else { assertNotSameResults(join(a, op, b), join(a, inverse, b)); } } } } } public void testCommutativeOperators() { List<String> operators = ImmutableList.of( "==", "!=", "===", "!==", "*", "|", "&", "^"); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = iOperandA; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); // Test commutativity. // TODO(nicksantos): Eventually, all cases should be collapsed. assertSameResultsOrUncollapsed(join(a, op, b), join(b, op, a)); } } } } private String join(String operandA, String op, String operandB) { return operandA + " " + op + " " + operandB; } private void assertSameResultsOrUncollapsed(String exprA, String exprB) { String resultA = process(exprA); String resultB = process(exprB); if (resultA.equals(print(exprA))) { foldSame(exprA); foldSame(exprB); } else { assertSameResults(exprA, exprB); } } private void assertSameResults(String exprA, String exprB) { assertEquals( "Expressions did not fold the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA), process(exprB)); } private void assertNotSameResults(String exprA, String exprB) { assertFalse( "Expressions folded the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA).equals(process(exprB))); } private String process(String js) { return printHelper(js, true); } private String print(String js) { return printHelper(js, false); } private String printHelper(String js, boolean runProcessor) { Compiler compiler = createCompiler(); CompilerOptions options = getOptions(); compiler.init( new JSSourceFile[] {}, new JSSourceFile[] { JSSourceFile.fromCode("testcode", js) }, options); Node root = compiler.parseInputs(); assertTrue("Unexpected parse error(s): " + Joiner.on("\n").join(compiler.getErrors()) + "\nEXPR: " + js, root != null); Node externsRoot = root.getFirstChild(); Node mainRoot = externsRoot.getNext(); if (runProcessor) { getProcessor(compiler).process(externsRoot, mainRoot); } return compiler.toSource(mainRoot); } }
// You are a professional Java test case writer, please create a test case named `testFoldArithmetic` for the issue `Closure-381`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-381 // // ## Issue-Title: // division by zero wrongly throws JSC_DIVIDE_BY_0_ERROR // // ## Issue-Description: // **What steps will reproduce the problem?** // // unaliased division by zero `1/0` // // **What is the expected output? What do you see instead?** // // I expect minified code, but an error is thrown instead. // // **What version of the product are you using? On what operating system?** // // appspot // // **Please provide any additional information below.** // // Division by zero is a perfectly sane operation in ECMAScript. See 11.5.2 [0] of the ECMAScript 5 specification. Aliased division by zero `(n=1)/0` is permitted. // // [0] http://es5.github.com/#x11.5.2 // // public void testFoldArithmetic() {
562
78
551
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
test
```markdown ## Issue-ID: Closure-381 ## Issue-Title: division by zero wrongly throws JSC_DIVIDE_BY_0_ERROR ## Issue-Description: **What steps will reproduce the problem?** unaliased division by zero `1/0` **What is the expected output? What do you see instead?** I expect minified code, but an error is thrown instead. **What version of the product are you using? On what operating system?** appspot **Please provide any additional information below.** Division by zero is a perfectly sane operation in ECMAScript. See 11.5.2 [0] of the ECMAScript 5 specification. Aliased division by zero `(n=1)/0` is permitted. [0] http://es5.github.com/#x11.5.2 ``` You are a professional Java test case writer, please create a test case named `testFoldArithmetic` for the issue `Closure-381`, utilizing the provided issue report information and the following function signature. ```java public void testFoldArithmetic() { ```
551
[ "com.google.javascript.jscomp.PeepholeFoldConstants" ]
18f5e363d1e14f733ef65c50b9a988d7c29b781dd496742aeb67b3a83d914e7d
public void testFoldArithmetic()
// You are a professional Java test case writer, please create a test case named `testFoldArithmetic` for the issue `Closure-381`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-381 // // ## Issue-Title: // division by zero wrongly throws JSC_DIVIDE_BY_0_ERROR // // ## Issue-Description: // **What steps will reproduce the problem?** // // unaliased division by zero `1/0` // // **What is the expected output? What do you see instead?** // // I expect minified code, but an error is thrown instead. // // **What version of the product are you using? On what operating system?** // // appspot // // **Please provide any additional information below.** // // Division by zero is a perfectly sane operation in ECMAScript. See 11.5.2 [0] of the ECMAScript 5 specification. Aliased division by zero `(n=1)/0` is permitted. // // [0] http://es5.github.com/#x11.5.2 // //
Closure
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.javascript.rhino.Node; import java.util.List; import java.util.Map; import java.util.Set; /** * Tests for {@link PeepholeFoldConstants} in isolation. Tests for * the interaction of multiple peephole passes are in * {@link PeepholeIntegrationTest}. */ public class PeepholeFoldConstantsTest extends CompilerTestCase { // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeFoldConstantsTest(boolean compareAsTree) { super("", compareAsTree); } public PeepholeFoldConstantsTest() { super(""); } @Override public void setUp() { enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants()); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } private void fold(String js, String expected, DiagnosticType warning) { test(js, expected, warning); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. private void assertResultString(String js, String expected) { PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false); scTest.test(js, expected); } public void testUndefinedComparison1() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUndefinedComparison2() { fold("\"123\" !== void 0", "true"); fold("\"123\" === void 0", "false"); fold("void 0 !== \"123\"", "true"); fold("void 0 === \"123\"", "false"); } public void testUndefinedComparison3() { fold("\"123\" !== undefined", "true"); fold("\"123\" === undefined", "false"); fold("undefined !== \"123\"", "true"); fold("undefined === \"123\"", "false"); } public void testUndefinedComparison4() { fold("1 !== void 0", "true"); fold("1 === void 0", "false"); fold("null !== void 0", "true"); fold("null === void 0", "false"); fold("undefined !== void 0", "false"); fold("undefined === void 0", "true"); } public void testUnaryOps() { // These cases are handled by PeepholeRemoveDeadCode. foldSame("!foo()"); foldSame("~foo()"); foldSame("-foo()"); // These cases are handled here. fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); fold("a=-0", "a=0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=+true", "a=1"); fold("a=+10", "a=10"); fold("a=+false", "a=0"); foldSame("a=+foo()"); foldSame("a=+f"); fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable fold("a=+0", "a=0"); fold("a=+Infinity", "a=Infinity"); fold("a=+NaN", "a=NaN"); fold("a=+-7", "a=-7"); fold("a=+.5", "a=.5"); fold("a=~0x100000000", "a=~0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~-0x100000000", "a=~-0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { // Negatives are folded into a single number node. assertResultString("a=-1", "a=-1"); assertResultString("a=~0", "a=-1"); assertResultString("a=~1", "a=-2"); assertResultString("a=~101", "a=-102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // unfoldable, because the right-side may be the result fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // folded, but not here. foldSame("a = x || false ? b : c"); foldSame("a = x && true ? b : c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || false || bar()", "x = foo()||bar()"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("x = foo() && false || bar()", "x = foo()&&false||bar()"); fold("1 && b()", "b()"); fold("a() && (1 && b())", "a() && b()"); // TODO(johnlenz): Consider folding the following to: // "(a(),1) && b(); fold("(a() && 1) && b()", "(a() && 1) && b()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = 1 ^ 1", "x = 0"); fold("x = 1 ^ 2", "x = 3"); fold("x = 3 ^ 1", "x = 2"); fold("x = 3 ^ 3", "x = 0"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1"); fold("x = 1.1 & 1", "x = 1"); fold("x = 1 & 3000000000", "x = 0"); fold("x = 3000000000 & 1", "x = 0"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1"); foldSame("x = 1 | 3E9"); fold("x = 1 | 3000000001", "x = -1294967295"); } public void testFoldBitwiseOp2() { fold("x = y & 1 & 1", "x = y & 1"); fold("x = y & 1 & 2", "x = y & 0"); fold("x = y & 3 & 1", "x = y & 1"); fold("x = 3 & y & 1", "x = y & 1"); fold("x = y & 3 & 3", "x = y & 3"); fold("x = 3 & y & 3", "x = y & 3"); fold("x = y | 1 | 1", "x = y | 1"); fold("x = y | 1 | 2", "x = y | 3"); fold("x = y | 3 | 1", "x = y | 3"); fold("x = 3 | y | 1", "x = y | 3"); fold("x = y | 3 | 3", "x = y | 3"); fold("x = 3 | y | 3", "x = y | 3"); fold("x = y ^ 1 ^ 1", "x = y ^ 0"); fold("x = y ^ 1 ^ 2", "x = y ^ 3"); fold("x = y ^ 3 ^ 1", "x = y ^ 2"); fold("x = 3 ^ y ^ 1", "x = y ^ 2"); fold("x = y ^ 3 ^ 3", "x = y ^ 0"); fold("x = 3 ^ y ^ 3", "x = y ^ 0"); fold("x = Infinity | NaN", "x=0"); fold("x = 12 | NaN", "x=12"); } public void testFoldingMixTypes() { fold("x = x + '2'", "x+='2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x-=2"); fold("x = x ^ '2'", "x^=2"); fold("x = '2' ^ x", "x^=2"); fold("x = '2' & x", "x&=2"); fold("x = '2' | x", "x|=2"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingAdd() { fold("x = null + true", "x=1"); foldSame("x = a + true"); } public void testFoldBitwiseOpStringCompare() { assertResultString("x = -1 | 0", "x=-1"); // EXPR_RESULT case is in in PeepholeIntegrationTest } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { // Negative numbers. assertResultString("x = -1 << 1", "x=-2"); assertResultString("x = -1 << 8", "x=-256"); assertResultString("x = -1 >> 1", "x=-1"); assertResultString("x = -2 >> 1", "x=-1"); assertResultString("x = -1 >> 0", "x=-1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = ''"); // cannot fold (but nice if we can) } public void testFoldConstructor() { fold("x = this[new String('a')]", "x = this['a']"); fold("x = ob[new String(12)]", "x = ob['12']"); fold("x = ob[new String(false)]", "x = ob['false']"); fold("x = ob[new String(null)]", "x = ob['null']"); foldSame("x = ob[new String(a)]"); foldSame("x = new String('a')"); foldSame("x = (new String('a'))[3]"); } public void testStringIndexOf() { fold("x = 'abcdef'.indexOf('b')", "x = 1"); fold("x = 'abcdefbe'.indexOf('b', 2)", "x = 6"); fold("x = 'abcdef'.indexOf('bcd')", "x = 1"); fold("x = 'abcdefsdfasdfbcdassd'.indexOf('bcd', 4)", "x = 13"); fold("x = 'abcdef'.lastIndexOf('b')", "x = 1"); fold("x = 'abcdefbe'.lastIndexOf('b')", "x = 6"); fold("x = 'abcdefbe'.lastIndexOf('b', 5)", "x = 1"); // Both elements must be string. Dont do anything if either one is not // string. fold("x = 'abc1def'.indexOf(1)", "x = 3"); fold("x = 'abcNaNdef'.indexOf(NaN)", "x = 3"); fold("x = 'abcundefineddef'.indexOf(undefined)", "x = 3"); fold("x = 'abcnulldef'.indexOf(null)", "x = 3"); fold("x = 'abctruedef'.indexOf(true)", "x = 3"); // The following testcase fails with JSC_PARSE_ERROR. Hence omitted. // foldSame("x = 1.indexOf('bcd');"); foldSame("x = NaN.indexOf('bcd')"); foldSame("x = undefined.indexOf('bcd')"); foldSame("x = null.indexOf('bcd')"); foldSame("x = true.indexOf('bcd')"); foldSame("x = false.indexOf('bcd')"); // Avoid dealing with regex or other types. foldSame("x = 'abcdef'.indexOf(/b./)"); foldSame("x = 'abcdef'.indexOf({a:2})"); foldSame("x = 'abcdef'.indexOf([1,2])"); } public void testStringJoinAddSparse() { fold("x = [,,'a'].join(',')", "x = ',,a'"); } public void testStringJoinAdd() { fold("x = ['a', 'b', 'c'].join('')", "x = \"abc\""); fold("x = [].join(',')", "x = \"\""); fold("x = ['a'].join(',')", "x = \"a\""); fold("x = ['a', 'b', 'c'].join(',')", "x = \"a,b,c\""); fold("x = ['a', foo, 'b', 'c'].join(',')", "x = [\"a\",foo,\"b,c\"].join(\",\")"); fold("x = [foo, 'a', 'b', 'c'].join(',')", "x = [foo,\"a,b,c\"].join(\",\")"); fold("x = ['a', 'b', 'c', foo].join(',')", "x = [\"a,b,c\",foo].join(\",\")"); // Works with numbers fold("x = ['a=', 5].join('')", "x = \"a=5\""); fold("x = ['a', '5'].join(7)", "x = \"a75\""); // Works on boolean fold("x = ['a=', false].join('')", "x = \"a=false\""); fold("x = ['a', '5'].join(true)", "x = \"atrue5\""); fold("x = ['a', '5'].join(false)", "x = \"afalse5\""); // Only optimize if it's a size win. fold("x = ['a', '5', 'c'].join('a very very very long chain')", "x = [\"a\",\"5\",\"c\"].join(\"a very very very long chain\")"); // TODO(user): Its possible to fold this better. foldSame("x = ['', foo].join(',')"); foldSame("x = ['', foo, ''].join(',')"); fold("x = ['', '', foo, ''].join(',')", "x = [',', foo, ''].join(',')"); fold("x = ['', '', foo, '', ''].join(',')", "x = [',', foo, ','].join(',')"); fold("x = ['', '', foo, '', '', bar].join(',')", "x = [',', foo, ',', bar].join(',')"); fold("x = [1,2,3].join('abcdef')", "x = '1abcdef2abcdef3'"); fold("x = [1,2].join()", "x = '1,2'"); fold("x = [null,undefined,''].join(',')", "x = ',,'"); fold("x = [null,undefined,0].join(',')", "x = ',,0'"); // This can be folded but we don't currently. foldSame("x = [[1,2],[3,4]].join()"); // would like: "x = '1,2,3,4'" } public void testStringJoinAdd_b1992789() { fold("x = ['a'].join('')", "x = \"a\""); fold("x = [foo()].join('')", "x = '' + foo()"); fold("[foo()].join('')", "'' + foo()"); } public void testFoldStringSubstr() { fold("x = 'abcde'.substr(0,2)", "x = 'ab'"); fold("x = 'abcde'.substr(1,2)", "x = 'bc'"); fold("x = 'abcde'['substr'](1,3)", "x = 'bcd'"); fold("x = 'abcde'.substr(2)", "x = 'cde'"); // we should be leaving negative indexes alone for now foldSame("x = 'abcde'.substr(-1)"); foldSame("x = 'abcde'.substr(1, -2)"); foldSame("x = 'abcde'.substr(1, 2, 3)"); foldSame("x = 'a'.substr(0, 2)"); } public void testFoldStringSubstring() { fold("x = 'abcde'.substring(0,2)", "x = 'ab'"); fold("x = 'abcde'.substring(1,2)", "x = 'b'"); fold("x = 'abcde'['substring'](1,3)", "x = 'bc'"); fold("x = 'abcde'.substring(2)", "x = 'cde'"); // we should be leaving negative indexes alone for now foldSame("x = 'abcde'.substring(-1)"); foldSame("x = 'abcde'.substring(1, -2)"); foldSame("x = 'abcde'.substring(1, 2, 3)"); foldSame("x = 'a'.substring(0, 2)"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "x = 1 / 0"); fold("x = 3 % 2", "x = 1"); fold("x = 3 % -2", "x = 1"); fold("x = -1 % 3", "x = -1"); fold("x = 1 % 0", "x = 1 % 0"); } public void testFoldArithmetic2() { foldSame("x = y + 10 + 20"); foldSame("x = y / 2 / 4"); fold("x = y * 2.25 * 3", "x = y * 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 864E5"); } public void testFoldArithmetic3() { fold("x = null * undefined", "x = NaN"); fold("x = null * 1", "x = 0"); fold("x = (null - 1) * 2", "x = -2"); fold("x = (null + 1) * 2", "x = 2"); } public void testFoldArithmeticInfinity() { fold("x=-Infinity-2", "x=-Infinity"); fold("x=Infinity-2", "x=Infinity"); fold("x=Infinity*5", "x=Infinity"); } public void testFoldArithmeticStringComp() { // Negative Numbers. assertResultString("x = 10 - 20", "x=-10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = true == true", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = true === true", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); // TODO(johnlenz): It would be nice to handle these cases as well. foldSame("1 === '1'"); foldSame("1 === true"); foldSame("1 !== '1'"); foldSame("1 !== true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldGetElem() { fold("x = [,10][0]", "x = void 0"); fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); fold("x = [10, 20][0.5]", "", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); fold("x = [10, 20][-1]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); fold("x = [10, 20][2]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldLeft() { foldSame("(+x - 1) + 2"); // not yet fold("(+x + 1) + 2", "+x + 3"); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Not handled yet fold("x = [,,1].length", "x = 3"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); fold("x = y.length", "x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); fold("x = typeof function() {}", "x = 'function'"); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("!0 instanceof Object", "false"); fold("!0 instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); fold("(function() {}) instanceof Object", "true"); // An unknown value should never be folded. foldSame("x instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 fold("print(1/3)", "print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOps() { fold("x=x+y", "x+=y"); foldSame("x=y+x"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); fold("x=x-y", "x-=y"); foldSame("x=y-x"); fold("x=x|y", "x|=y"); fold("x=y|x", "x|=y"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); } public void testFoldAdd1() { fold("x=false+1","x=1"); fold("x=true+1","x=2"); fold("x=1+false","x=1"); fold("x=1+true","x=2"); } public void testFoldLiteralNames() { foldSame("NaN == NaN"); foldSame("Infinity == Infinity"); foldSame("Infinity == NaN"); fold("undefined == NaN", "false"); fold("undefined == Infinity", "false"); foldSame("Infinity >= Infinity"); foldSame("NaN >= NaN"); } public void testFoldLiteralsTypeMismatches() { fold("true == true", "true"); fold("true == false", "false"); fold("true == null", "false"); fold("false == null", "false"); // relational operators convert its operands fold("null <= null", "true"); // 0 = 0 fold("null >= null", "true"); fold("null > null", "false"); fold("null < null", "false"); fold("false >= null", "true"); // 0 = 0 fold("false <= null", "true"); fold("false > null", "false"); fold("false < null", "false"); fold("true >= null", "true"); // 1 > 0 fold("true <= null", "false"); fold("true > null", "true"); fold("true < null", "false"); fold("true >= false", "true"); // 1 > 0 fold("true <= false", "false"); fold("true > false", "true"); fold("true < false", "false"); } public void testFoldLeftChildConcat() { foldSame("x +5 + \"1\""); fold("x+\"5\" + \"1\"", "x + \"51\""); // fold("\"a\"+(c+\"b\")","\"a\"+c+\"b\""); fold("\"a\"+(\"b\"+c)","\"ab\"+c"); } public void testFoldLeftChildOp() { fold("x * Infinity * 2", "x * Infinity"); foldSame("x - Infinity - 2"); // want "x-Infinity" foldSame("x - 1 + Infinity"); foldSame("x - 2 + 1"); foldSame("x - 2 + 3"); foldSame("1 + x - 2 + 1"); foldSame("1 + x - 2 + 3"); foldSame("1 + x - 2 + 3 - 1"); foldSame("f(x)-0"); foldSame("x-0-0"); foldSame("x+2-2+2"); foldSame("x+2-2+2-2"); foldSame("x-2+2"); foldSame("x-2+2-2"); foldSame("x-2+2-2+2"); foldSame("1+x-0-NaN"); foldSame("1+f(x)-0-NaN"); foldSame("1+x-0+NaN"); foldSame("1+f(x)-0+NaN"); foldSame("1+x+NaN"); // unfoldable foldSame("x+2-2"); // unfoldable foldSame("x+2"); // nothing to do foldSame("x-2"); // nothing to do } public void testFoldSimpleArithmeticOp() { foldSame("x*NaN"); foldSame("NaN/y"); foldSame("f(x)-0"); foldSame("f(x)*1"); foldSame("1*f(x)"); foldSame("0+a+b"); foldSame("0-a-b"); foldSame("a+b-0"); foldSame("(1+x)*NaN"); foldSame("(1+f(x))*NaN"); // don't fold side-effects } public void testFoldLiteralsAsNumbers() { fold("x/'12'","x/12"); fold("x/('12'+'6')", "x/126"); fold("true*x", "1*x"); fold("x/false", "x/0"); // should we add an error check? :) } public void testNotFoldBackToTrueFalse() { foldSame("!0"); foldSame("!1"); fold("!3", "false"); } public void testFoldBangConstants() { fold("1 + !0", "2"); fold("1 + !1", "1"); fold("'a ' + !1", "'a false'"); fold("'a ' + !0", "'a true'"); } public void testFoldMixed() { fold("''+[1]", "'1'"); foldSame("false+[]"); // would like: "\"false\"" } public void testFoldVoid() { foldSame("void 0"); fold("void 1", "void 0"); fold("void x", "void 0"); fold("void x()", "void x()"); } public void testJoinBug() { fold("var x = [].join();", "var x = '';"); fold("var x = [x].join();", "var x = '' + x;"); foldSame("var x = [x,y].join();"); foldSame("var x = [x,y,z].join();"); foldSame("shape['matrix'] = [\n" + " Number(headingCos2).toFixed(4),\n" + " Number(-headingSin2).toFixed(4),\n" + " Number(headingSin2 * yScale).toFixed(4),\n" + " Number(headingCos2 * yScale).toFixed(4),\n" + " 0,\n" + " 0\n" + " ].join()"); } public void testToUpper() { fold("'a'.toUpperCase()", "'A'"); fold("'A'.toUpperCase()", "'A'"); fold("'aBcDe'.toUpperCase()", "'ABCDE'"); } public void testToLower() { fold("'A'.toLowerCase()", "'a'"); fold("'a'.toLowerCase()", "'a'"); fold("'aBcDe'.toLowerCase()", "'abcde'"); } private static final List<String> LITERAL_OPERANDS = ImmutableList.of( "null", "undefined", "void 0", "true", "false", "0", "1", "''", "'123'", "'abc'", "'def'", "NaN", "Infinity" // TODO(nicksantos): Add more literals //-Infinity //"({})", //"[]", //"[0]", //"Object", //"(function() {})" ); public void testInvertibleOperators() { Map<String, String> inverses = ImmutableMap.<String, String>builder() .put("==", "!=") .put("===", "!==") .put("<=", ">") .put("<", ">=") .put(">=", "<") .put(">", "<=") .put("!=", "==") .put("!==", "===") .build(); Set<String> comparators = ImmutableSet.of("<=", "<", ">=", ">"); Set<String> equalitors = ImmutableSet.of("==", "==="); Set<String> uncomparables = ImmutableSet.of("undefined", "void 0"); List<String> operators = ImmutableList.copyOf(inverses.values()); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = 0; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); String inverse = inverses.get(op); // Test invertability. if (comparators.contains(op) && (uncomparables.contains(a) || uncomparables.contains(b))) { assertSameResults(join(a, op, b), "false"); assertSameResults(join(a, inverse, b), "false"); } else if (a.equals(b) && equalitors.contains(op)) { if (a.equals("NaN") || a.equals("Infinity")) { foldSame(join(a, op, b)); foldSame(join(a, inverse, b)); } else { assertSameResults(join(a, op, b), "true"); assertSameResults(join(a, inverse, b), "false"); } } else { assertNotSameResults(join(a, op, b), join(a, inverse, b)); } } } } } public void testCommutativeOperators() { List<String> operators = ImmutableList.of( "==", "!=", "===", "!==", "*", "|", "&", "^"); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = iOperandA; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); // Test commutativity. // TODO(nicksantos): Eventually, all cases should be collapsed. assertSameResultsOrUncollapsed(join(a, op, b), join(b, op, a)); } } } } private String join(String operandA, String op, String operandB) { return operandA + " " + op + " " + operandB; } private void assertSameResultsOrUncollapsed(String exprA, String exprB) { String resultA = process(exprA); String resultB = process(exprB); if (resultA.equals(print(exprA))) { foldSame(exprA); foldSame(exprB); } else { assertSameResults(exprA, exprB); } } private void assertSameResults(String exprA, String exprB) { assertEquals( "Expressions did not fold the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA), process(exprB)); } private void assertNotSameResults(String exprA, String exprB) { assertFalse( "Expressions folded the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA).equals(process(exprB))); } private String process(String js) { return printHelper(js, true); } private String print(String js) { return printHelper(js, false); } private String printHelper(String js, boolean runProcessor) { Compiler compiler = createCompiler(); CompilerOptions options = getOptions(); compiler.init( new JSSourceFile[] {}, new JSSourceFile[] { JSSourceFile.fromCode("testcode", js) }, options); Node root = compiler.parseInputs(); assertTrue("Unexpected parse error(s): " + Joiner.on("\n").join(compiler.getErrors()) + "\nEXPR: " + js, root != null); Node externsRoot = root.getFirstChild(); Node mainRoot = externsRoot.getNext(); if (runProcessor) { getProcessor(compiler).process(externsRoot, mainRoot); } return compiler.toSource(mainRoot); } }
public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); }
com.google.javascript.jscomp.TypeCheckTest::testIssue726
test/com/google/javascript/jscomp/TypeCheckTest.java
5,989
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue726
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2);" + "}", "Property name2 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testGenerics1() throws Exception { String FN_DECL = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( FN_DECL + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void disable_testBackwardsInferenceGoogArrayFilter1() throws Exception { // TODO(johnlenz): this doesn't fail because any Array is regarded as // a subtype of any other array regardless of the type parameter. testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testIssue726` for the issue `Closure-726`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-726 // // ## Issue-Title: // Wrong argument count error not reported on this aliasing (on function with @this annotation) // // ## Issue-Description: // The following code (attached as test2-1.js) when compiled with: // java -jar build/compiler.jar --compilation\_level=ADVANCED\_OPTIMIZATIONS --jscomp\_error=accessControls --jscomp\_error=checkTypes --jscomp\_error=checkVars --jscomp\_error=uselessCode --jscomp\_off=globalThis --js ~/Desktop/test2.js // // correctly fails with: // // /Users/dolapo/Desktop/test2.js:28: ERROR - Function Person.prototype.getName: called with 1 argument(s). Function requires at least 0 argument(s) and no more than 0 argument(s). // // However, if the say function is modified such that this is aliased and the function is called within a setTimeout (test2-2.js), the error is not caught // // // // // // test2-1.js: // 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 \*/ // var Person = function(name){}; // Person = makeClass(/\*\* @lends Person.prototype \*/ { // /\*\* @this {Person} \*/ // initialize: function(name) { // this.name = name; // }, // // /\*\* @this {Person} \*/ // getName: function() { return this.name; }, // // /\*\* // \* @param {string} message // \* @this {Person} // \*/ // say: function(message) { // window.console.log(this.getName(1) + ' says: ' + message); // } // }); // // // var joe = new Person('joe'); // joe.say('hi'); // var jane = new Person('jane'); // jane.say('hello'); // // // // test2-2.js: // // 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 \*/ // var Person = function(name){}; // Person = makeClass(/\*\* @lends Person.prototype \*/ { // /\*\* @this {Person} \*/ // initialize: function(name) { // this.name = name; // }, // // /\*\* @this {Person} \*/ // getName: function() { return this.name; }, // // /\*\* // \* @param {string} message // \* @this {Person} // \*/ // say: function(message) { // // window.console.log(this.getName(1) + ' says: ' + message); // var self = this; // setTimeout(function() { // window.console.log(self.getName(1) + ' says: ' + message); // }, 500); // } // }); // // // var joe = new Person('joe'); // joe.say('hi'); // var jane = new Person('jane'); // jane.say('hello'); // // public void testIssue726() throws Exception {
5,989
168
5,975
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-726 ## Issue-Title: Wrong argument count error not reported on this aliasing (on function with @this annotation) ## Issue-Description: The following code (attached as test2-1.js) when compiled with: java -jar build/compiler.jar --compilation\_level=ADVANCED\_OPTIMIZATIONS --jscomp\_error=accessControls --jscomp\_error=checkTypes --jscomp\_error=checkVars --jscomp\_error=uselessCode --jscomp\_off=globalThis --js ~/Desktop/test2.js correctly fails with: /Users/dolapo/Desktop/test2.js:28: ERROR - Function Person.prototype.getName: called with 1 argument(s). Function requires at least 0 argument(s) and no more than 0 argument(s). However, if the say function is modified such that this is aliased and the function is called within a setTimeout (test2-2.js), the error is not caught test2-1.js: 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 \*/ var Person = function(name){}; Person = makeClass(/\*\* @lends Person.prototype \*/ { /\*\* @this {Person} \*/ initialize: function(name) { this.name = name; }, /\*\* @this {Person} \*/ getName: function() { return this.name; }, /\*\* \* @param {string} message \* @this {Person} \*/ say: function(message) { window.console.log(this.getName(1) + ' says: ' + message); } }); var joe = new Person('joe'); joe.say('hi'); var jane = new Person('jane'); jane.say('hello'); test2-2.js: 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 \*/ var Person = function(name){}; Person = makeClass(/\*\* @lends Person.prototype \*/ { /\*\* @this {Person} \*/ initialize: function(name) { this.name = name; }, /\*\* @this {Person} \*/ getName: function() { return this.name; }, /\*\* \* @param {string} message \* @this {Person} \*/ say: function(message) { // window.console.log(this.getName(1) + ' says: ' + message); var self = this; setTimeout(function() { window.console.log(self.getName(1) + ' says: ' + message); }, 500); } }); var joe = new Person('joe'); joe.say('hi'); var jane = new Person('jane'); jane.say('hello'); ``` You are a professional Java test case writer, please create a test case named `testIssue726` for the issue `Closure-726`, utilizing the provided issue report information and the following function signature. ```java public void testIssue726() throws Exception { ```
5,975
[ "com.google.javascript.jscomp.TypedScopeCreator" ]
199ea3e222d53f8385e5d247529ebad222638a89260bf6a32925b33cffaf35dc
public void testIssue726() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue726` for the issue `Closure-726`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-726 // // ## Issue-Title: // Wrong argument count error not reported on this aliasing (on function with @this annotation) // // ## Issue-Description: // The following code (attached as test2-1.js) when compiled with: // java -jar build/compiler.jar --compilation\_level=ADVANCED\_OPTIMIZATIONS --jscomp\_error=accessControls --jscomp\_error=checkTypes --jscomp\_error=checkVars --jscomp\_error=uselessCode --jscomp\_off=globalThis --js ~/Desktop/test2.js // // correctly fails with: // // /Users/dolapo/Desktop/test2.js:28: ERROR - Function Person.prototype.getName: called with 1 argument(s). Function requires at least 0 argument(s) and no more than 0 argument(s). // // However, if the say function is modified such that this is aliased and the function is called within a setTimeout (test2-2.js), the error is not caught // // // // // // test2-1.js: // 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 \*/ // var Person = function(name){}; // Person = makeClass(/\*\* @lends Person.prototype \*/ { // /\*\* @this {Person} \*/ // initialize: function(name) { // this.name = name; // }, // // /\*\* @this {Person} \*/ // getName: function() { return this.name; }, // // /\*\* // \* @param {string} message // \* @this {Person} // \*/ // say: function(message) { // window.console.log(this.getName(1) + ' says: ' + message); // } // }); // // // var joe = new Person('joe'); // joe.say('hi'); // var jane = new Person('jane'); // jane.say('hello'); // // // // test2-2.js: // // 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 \*/ // var Person = function(name){}; // Person = makeClass(/\*\* @lends Person.prototype \*/ { // /\*\* @this {Person} \*/ // initialize: function(name) { // this.name = name; // }, // // /\*\* @this {Person} \*/ // getName: function() { return this.name; }, // // /\*\* // \* @param {string} message // \* @this {Person} // \*/ // say: function(message) { // // window.console.log(this.getName(1) + ' says: ' + message); // var self = this; // setTimeout(function() { // window.console.log(self.getName(1) + ' says: ' + message); // }, 500); // } // }); // // // var joe = new Person('joe'); // joe.say('hi'); // var jane = new Person('jane'); // jane.say('hello'); // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2);" + "}", "Property name2 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testGenerics1() throws Exception { String FN_DECL = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( FN_DECL + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void disable_testBackwardsInferenceGoogArrayFilter1() throws Exception { // TODO(johnlenz): this doesn't fail because any Array is regarded as // a subtype of any other array regardless of the type parameter. testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
@Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); }
org.jsoup.nodes.ElementTest::testNotPretty
src/test/java/org/jsoup/nodes/ElementTest.java
247
src/test/java/org/jsoup/nodes/ElementTest.java
testNotPretty
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Map; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class='mellow yellow'>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); assertFalse(doc.hasClass("mellow")); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\" /><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("class", "second").text("now"); assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\" />", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\" />", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } }
// You are a professional Java test case writer, please create a test case named `testNotPretty` for the issue `Jsoup-368`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-368 // // ## Issue-Title: // Whitespaces are discared in Element.html() method // // ## Issue-Description: // Hi, // // I'm trying to make an exact copy of a document (changing just a couple of attributes and appending a few nodes) and the trim() inside the Element.html() is killing me. // // I'm using Parsers.xml() and no prettyPrint. // // // I think this trim should be enabled for prettyPrint only. // // // // @Test public void testNotPretty() {
247
37
240
src/test/java/org/jsoup/nodes/ElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-368 ## Issue-Title: Whitespaces are discared in Element.html() method ## Issue-Description: Hi, I'm trying to make an exact copy of a document (changing just a couple of attributes and appending a few nodes) and the trim() inside the Element.html() is killing me. I'm using Parsers.xml() and no prettyPrint. I think this trim should be enabled for prettyPrint only. ``` You are a professional Java test case writer, please create a test case named `testNotPretty` for the issue `Jsoup-368`, utilizing the provided issue report information and the following function signature. ```java @Test public void testNotPretty() { ```
240
[ "org.jsoup.nodes.Element" ]
1a67e98d48a7e92a0da7a26a747d8248340f4873358e9fbb706312ade8adab08
@Test public void testNotPretty()
// You are a professional Java test case writer, please create a test case named `testNotPretty` for the issue `Jsoup-368`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-368 // // ## Issue-Title: // Whitespaces are discared in Element.html() method // // ## Issue-Description: // Hi, // // I'm trying to make an exact copy of a document (changing just a couple of attributes and appending a few nodes) and the trim() inside the Element.html() is killing me. // // I'm using Parsers.xml() and no prettyPrint. // // // I think this trim should be enabled for prettyPrint only. // // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Map; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class='mellow yellow'>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); assertFalse(doc.hasClass("mellow")); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\" /><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("class", "second").text("now"); assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\" />", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\" />", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } }
public void testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);" + "}"); }
com.google.javascript.jscomp.CommandLineRunnerTest::testIssue297
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
259
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
testIssue297
/* * Copyright 2009 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Lists; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; /** * Tests for {@link CommandLineRunner}. * * @author nicksantos@google.com (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; private CommandLineRunner lastCommandLineRunner = null; private List<Integer> exitCodes = null; private ByteArrayOutputStream outReader = null; private ByteArrayOutputStream errReader = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private ModulePattern useModules = ModulePattern.NONE; private enum ModulePattern { NONE, CHAIN, STAR } private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final List<JSSourceFile> externs = Lists.newArrayList( JSSourceFile.fromCode("externs", "var arguments;" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " */\n" + "function Function(var_args) {}\n" + "/**\n" + " * @param {...*} var_args\n" + " * @return {*}\n" + " */\n" + "Function.prototype.call = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @return {!Array}\n" + " */\n" + "function Array(var_args) {}" + "/**\n" + " * @param {*=} opt_begin\n" + " * @param {*=} opt_end\n" + " * @return {!Array}\n" + " * @this {Object}\n" + " */\n" + "Array.prototype.slice = function(opt_begin, opt_end) {};" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @nosideeffects */ function noSideEffects() {}") ); @Override public void setUp() throws Exception { super.setUp(); lastCompiler = null; outReader = new ByteArrayOutputStream(); errReader = new ByteArrayOutputStream(); useStringComparison = false; useModules = ModulePattern.NONE; args.clear(); exitCodes = Lists.newArrayList(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testTypeCheckingOffByDefault() { test("function f(x) { return x; } f();", "function f(a) { return a; } f();"); } public void testTypeCheckingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testTypeCheckOverride1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=checkTypes"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); } public void testTypeCheckOverride2() { args.add("--warning_level=DEFAULT"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); args.add("--jscomp_warning=checkTypes"); test("var x = x || {}; x.f = function() {}; x.f(3);", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testCheckSymbolsOffForDefault() { args.add("--warning_level=DEFAULT"); test("x = 3; var y; var y;", "x=3; var y;"); } public void testCheckSymbolsOnForVerbose() { args.add("--warning_level=VERBOSE"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); test("var y; var y;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testCheckSymbolsOverrideForVerbose() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=undefinedVars"); testSame("x = 3;"); } public void testCheckUndefinedProperties1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testCheckUndefinedProperties2() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=missingProperties"); test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testCheckUndefinedProperties3() { args.add("--warning_level=VERBOSE"); test("function f() {var x = {}; var y = x.bar;}", TypeCheck.INEXISTENT_PROPERTY); } public void testDuplicateParams() { test("function (a, a) {}", RhinoErrorReporter.DUPLICATE_PARAM); assertTrue(lastCompiler.hasHaltingErrors()); } public void testDefineFlag() { args.add("--define=FOO"); args.add("--define=\"BAR=5\""); args.add("--D"); args.add("CCC"); args.add("-D"); args.add("DDD"); test("/** @define {boolean} */ var FOO = false;" + "/** @define {number} */ var BAR = 3;" + "/** @define {boolean} */ var CCC = false;" + "/** @define {boolean} */ var DDD = false;", "var FOO = true, BAR = 5, CCC = true, DDD = true;"); } public void testDefineFlag2() { args.add("--define=FOO='x\"'"); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x\\\"\";"); } public void testDefineFlag3() { args.add("--define=FOO=\"x'\""); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x'\";"); } public void testScriptStrictModeNoWarning() { test("'use strict';", ""); test("'no use strict';", CheckSideEffects.USELESS_CODE_ERROR); } public void testFunctionStrictModeNoWarning() { test("function f() {'use strict';}", "function f() {}"); test("function f() {'no use strict';}", CheckSideEffects.USELESS_CODE_ERROR); } public void testQuietMode() { args.add("--warning_level=DEFAULT"); test("/** @type { not a type name } */ var x;", RhinoErrorReporter.PARSE_ERROR); args.add("--warning_level=QUIET"); testSame("/** @type { not a type name } */ var x;"); } public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {}; goog.dom = {};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); } ////////////////////////////////////////////////////////////////////////////// // Integration tests public void testIssue70() { test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue81() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); useStringComparison = true; test("eval('1'); var x = eval; x('2');", "eval(\"1\");(0,eval)(\"2\");"); } public void testIssue115() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--warning_level=VERBOSE"); test("function f() { " + " var arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}", "function f() { " + " arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}"); } public void testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);" + "}"); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); test("function foo(a) {}", "function foo() {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testDebugFlag3() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=false"); test("function Foo() {}" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "throw (new function() {}).a;"); } public void testDebugFlag4() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=true"); test("function Foo() {}" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "throw (new function Foo() {}).$x$;"); } public void testBooleanFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testBooleanFlag2() { args.add("--debug"); args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testHelpFlag() { args.add("--help"); assertFalse( createCommandLineRunner( new String[] {"function f() {}"}).shouldRunCompiler()); } public void testExternsLifting1() throws Exception{ String code = "/** @externs */ function f() {}"; test(new String[] {code}, new String[] {}); assertEquals(2, lastCompiler.getExternsForTesting().size()); CompilerInput extern = lastCompiler.getExternsForTesting().get(1); assertNull(extern.getModule()); assertTrue(extern.isExtern()); assertEquals(code, extern.getCode()); assertEquals(1, lastCompiler.getInputsForTesting().size()); CompilerInput input = lastCompiler.getInputsForTesting().get(0); assertNotNull(input.getModule()); assertFalse(input.isExtern()); assertEquals("", input.getCode()); } public void testExternsLifting2() { args.add("--warning_level=VERBOSE"); test(new String[] {"/** @externs */ function f() {}", "f(3);"}, new String[] {"f(3);"}, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testSourceSortingOff() { test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, ProcessClosurePrimitives.LATE_PROVIDE_ERROR); } public void testSourceSortingOn() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, new String[] { "var beer = {};", "" }); } public void testSourceSortingCircularDeps1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourceSortingCircularDeps2() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('roses.lime.juice');", "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');", "goog.provide('gimlet');" + " goog.require('gin'); goog.require('roses.lime.juice');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourcePruningOn1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "" }); } public void testSourcePruningOn2() { args.add("--closure_entry_point=guinness"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var guinness = {};" }); } public void testSourcePruningOn3() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var scotch = {}, x = 3;", }); } public void testSourcePruningOn4() { args.add("--closure_entry_point=scotch"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn5() { args.add("--closure_entry_point=shiraz"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, Compiler.MISSING_ENTRY_ERROR); } public void testSourcePruningOn6() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "", "var scotch = {}, x = 3;", }); } public void testForwardDeclareDroppedTypes() { args.add("--manage_closure_dependencies=true"); args.add("--warning_level=VERBOSE"); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}", "goog.provide('Scotch'); var x = 3;" }, new String[] { "var beer = {}; function f() {}", "" }); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}" }, new String[] { "var beer = {}; function f() {}", "" }, RhinoErrorReporter.PARSE_ERROR); } public void testSourceMapExpansion1() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--create_source_map=%outname%.map"); testSame("var x = 3;"); assertEquals("/path/to/out.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion2() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion3() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo_"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo_m0.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootModule())); } public void testSourceMapFormat1() { args.add("--js_output_file"); args.add("/path/to/out.js"); testSame("var x = 3;"); assertEquals(SourceMap.Format.LEGACY, lastCompiler.getOptions().sourceMapFormat); } public void testCharSetExpansion() { testSame(""); assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset); args.add("--charset=UTF-8"); testSame(""); assertEquals("UTF-8", lastCompiler.getOptions().outputCharset); } public void testChainModuleManifest() throws Exception { useModules = ModulePattern.CHAIN; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestTo( lastCompiler.getModuleGraph(), builder); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m1}\n" + "i2\n" + "\n" + "{m3:m2}\n" + "i3\n", builder.toString()); } public void testStarModuleManifest() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestTo( lastCompiler.getModuleGraph(), builder); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m0}\n" + "i2\n" + "\n" + "{m3:m0}\n" + "i3\n", builder.toString()); } public void testVersionFlag() { args.add("--version"); testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testPrintAstFlag() { args.add("--print_ast=true"); testSame(""); assertEquals( "digraph AST {\n" + " node [color=lightblue2, style=filled];\n" + " node0 [label=\"BLOCK\"];\n" + " node1 [label=\"SCRIPT\"];\n" + " node0 -> node1 [weight=1];\n" + " node1 -> RETURN [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> RETURN [label=\"SYN_BLOCK\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> node1 [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + "}\n\n", new String(outReader.toByteArray())); } /* Helper functions */ private void testSame(String original) { testSame(new String[] { original }); } private void testSame(String[] original) { test(original, original); } private void test(String original, String compiled) { test(new String[] { original }, new String[] { compiled }); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(String[] original, String[] compiled) { test(original, compiled, null); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. * If {@code warning} is non-null, we will also check if the given * warning type was emitted. */ private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); if (warning == null) { assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); } Node root = compiler.getRoot().getLastChild(); if (useStringComparison) { assertEquals(Joiner.on("").join(compiled), compiler.toSource()); } else { Node expectedRoot = parse(compiled); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } /** * Asserts that when compiling, there is an error or warning. */ private void test(String original, DiagnosticType warning) { test(new String[] { original }, warning); } /** * Asserts that when compiling, there is an error or warning. */ private void test(String[] original, DiagnosticType warning) { Compiler compiler = compile(original); assertEquals("Expected exactly one warning or error " + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 1, compiler.getErrors().length + compiler.getWarnings().length); assertTrue(exitCodes.size() > 0); int lastExitCode = exitCodes.get(exitCodes.size() - 1); if (compiler.getErrors().length > 0) { assertEquals(1, compiler.getErrors().length); assertEquals(warning, compiler.getErrors()[0].getType()); assertEquals(1, lastExitCode); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); assertEquals(0, lastExitCode); } } private CommandLineRunner createCommandLineRunner(String[] original) { for (int i = 0; i < original.length; i++) { args.add("--js"); args.add("/path/to/input" + i + ".js"); if (useModules == ModulePattern.CHAIN) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? (":mod" + (i - 1)) : "")); } else if (useModules == ModulePattern.STAR) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? ":mod0" : "")); } } String[] argStrings = args.toArray(new String[] {}); return new CommandLineRunner( argStrings, new PrintStream(outReader), new PrintStream(errReader)); } private Compiler compile(String[] original) { CommandLineRunner runner = createCommandLineRunner(original); assertTrue(runner.shouldRunCompiler()); Supplier<List<JSSourceFile>> inputsSupplier = null; Supplier<List<JSModule>> modulesSupplier = null; if (useModules == ModulePattern.NONE) { List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } inputsSupplier = Suppliers.ofInstance(inputs); } else if (useModules == ModulePattern.STAR) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleStar(original))); } else if (useModules == ModulePattern.CHAIN) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleChain(original))); } else { throw new IllegalArgumentException("Unknown module type: " + useModules); } runner.enableTestMode( Suppliers.<List<JSSourceFile>>ofInstance(externs), inputsSupplier, modulesSupplier, new Function<Integer, Boolean>() { @Override public Boolean apply(Integer code) { return exitCodes.add(code); } }); runner.run(); lastCompiler = runner.getCompiler(); lastCommandLineRunner = runner; return lastCompiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = new CommandLineRunner(argStrings); Compiler compiler = runner.createCompiler(); List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } compiler.init(externs, inputs, new CompilerOptions()); Node all = compiler.parseInputs(); Node n = all.getLastChild(); return n; } }
// You are a professional Java test case writer, please create a test case named `testIssue297` for the issue `Closure-297`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-297 // // ## Issue-Title: // Incorrect assignment removal from expression in simple mode. // // ## Issue-Description: // function closureCompilerTest(someNode) { // var nodeId; // return ((nodeId=someNode.id) && (nodeId=parseInt(nodeId.substr(1))) && nodeId>0); // } // // COMPILES TO: // // function closureCompilerTest(b){var a;return b.id&&(a=parseInt(a.substr(1)))&&a>0}; // // "nodeId=someNode.id" is replaced with simply "b.id" which is incorrect as the value of "nodeId" is used. // // public void testIssue297() {
259
88
249
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
test
```markdown ## Issue-ID: Closure-297 ## Issue-Title: Incorrect assignment removal from expression in simple mode. ## Issue-Description: function closureCompilerTest(someNode) { var nodeId; return ((nodeId=someNode.id) && (nodeId=parseInt(nodeId.substr(1))) && nodeId>0); } COMPILES TO: function closureCompilerTest(b){var a;return b.id&&(a=parseInt(a.substr(1)))&&a>0}; "nodeId=someNode.id" is replaced with simply "b.id" which is incorrect as the value of "nodeId" is used. ``` You are a professional Java test case writer, please create a test case named `testIssue297` for the issue `Closure-297`, utilizing the provided issue report information and the following function signature. ```java public void testIssue297() { ```
249
[ "com.google.javascript.jscomp.DeadAssignmentsElimination" ]
1a7621aa9995bb1d06cd00c4dd0280fa19d399730a2e625b9c1ce6a5ed26b5e6
public void testIssue297()
// You are a professional Java test case writer, please create a test case named `testIssue297` for the issue `Closure-297`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-297 // // ## Issue-Title: // Incorrect assignment removal from expression in simple mode. // // ## Issue-Description: // function closureCompilerTest(someNode) { // var nodeId; // return ((nodeId=someNode.id) && (nodeId=parseInt(nodeId.substr(1))) && nodeId>0); // } // // COMPILES TO: // // function closureCompilerTest(b){var a;return b.id&&(a=parseInt(a.substr(1)))&&a>0}; // // "nodeId=someNode.id" is replaced with simply "b.id" which is incorrect as the value of "nodeId" is used. // //
Closure
/* * Copyright 2009 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Lists; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; /** * Tests for {@link CommandLineRunner}. * * @author nicksantos@google.com (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; private CommandLineRunner lastCommandLineRunner = null; private List<Integer> exitCodes = null; private ByteArrayOutputStream outReader = null; private ByteArrayOutputStream errReader = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private ModulePattern useModules = ModulePattern.NONE; private enum ModulePattern { NONE, CHAIN, STAR } private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final List<JSSourceFile> externs = Lists.newArrayList( JSSourceFile.fromCode("externs", "var arguments;" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " */\n" + "function Function(var_args) {}\n" + "/**\n" + " * @param {...*} var_args\n" + " * @return {*}\n" + " */\n" + "Function.prototype.call = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @return {!Array}\n" + " */\n" + "function Array(var_args) {}" + "/**\n" + " * @param {*=} opt_begin\n" + " * @param {*=} opt_end\n" + " * @return {!Array}\n" + " * @this {Object}\n" + " */\n" + "Array.prototype.slice = function(opt_begin, opt_end) {};" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @nosideeffects */ function noSideEffects() {}") ); @Override public void setUp() throws Exception { super.setUp(); lastCompiler = null; outReader = new ByteArrayOutputStream(); errReader = new ByteArrayOutputStream(); useStringComparison = false; useModules = ModulePattern.NONE; args.clear(); exitCodes = Lists.newArrayList(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testTypeCheckingOffByDefault() { test("function f(x) { return x; } f();", "function f(a) { return a; } f();"); } public void testTypeCheckingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testTypeCheckOverride1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=checkTypes"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); } public void testTypeCheckOverride2() { args.add("--warning_level=DEFAULT"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); args.add("--jscomp_warning=checkTypes"); test("var x = x || {}; x.f = function() {}; x.f(3);", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testCheckSymbolsOffForDefault() { args.add("--warning_level=DEFAULT"); test("x = 3; var y; var y;", "x=3; var y;"); } public void testCheckSymbolsOnForVerbose() { args.add("--warning_level=VERBOSE"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); test("var y; var y;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testCheckSymbolsOverrideForVerbose() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=undefinedVars"); testSame("x = 3;"); } public void testCheckUndefinedProperties1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testCheckUndefinedProperties2() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=missingProperties"); test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testCheckUndefinedProperties3() { args.add("--warning_level=VERBOSE"); test("function f() {var x = {}; var y = x.bar;}", TypeCheck.INEXISTENT_PROPERTY); } public void testDuplicateParams() { test("function (a, a) {}", RhinoErrorReporter.DUPLICATE_PARAM); assertTrue(lastCompiler.hasHaltingErrors()); } public void testDefineFlag() { args.add("--define=FOO"); args.add("--define=\"BAR=5\""); args.add("--D"); args.add("CCC"); args.add("-D"); args.add("DDD"); test("/** @define {boolean} */ var FOO = false;" + "/** @define {number} */ var BAR = 3;" + "/** @define {boolean} */ var CCC = false;" + "/** @define {boolean} */ var DDD = false;", "var FOO = true, BAR = 5, CCC = true, DDD = true;"); } public void testDefineFlag2() { args.add("--define=FOO='x\"'"); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x\\\"\";"); } public void testDefineFlag3() { args.add("--define=FOO=\"x'\""); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x'\";"); } public void testScriptStrictModeNoWarning() { test("'use strict';", ""); test("'no use strict';", CheckSideEffects.USELESS_CODE_ERROR); } public void testFunctionStrictModeNoWarning() { test("function f() {'use strict';}", "function f() {}"); test("function f() {'no use strict';}", CheckSideEffects.USELESS_CODE_ERROR); } public void testQuietMode() { args.add("--warning_level=DEFAULT"); test("/** @type { not a type name } */ var x;", RhinoErrorReporter.PARSE_ERROR); args.add("--warning_level=QUIET"); testSame("/** @type { not a type name } */ var x;"); } public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {}; goog.dom = {};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); } ////////////////////////////////////////////////////////////////////////////// // Integration tests public void testIssue70() { test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue81() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); useStringComparison = true; test("eval('1'); var x = eval; x('2');", "eval(\"1\");(0,eval)(\"2\");"); } public void testIssue115() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--warning_level=VERBOSE"); test("function f() { " + " var arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}", "function f() { " + " arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}"); } public void testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);" + "}"); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); test("function foo(a) {}", "function foo() {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testDebugFlag3() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=false"); test("function Foo() {}" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "throw (new function() {}).a;"); } public void testDebugFlag4() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=true"); test("function Foo() {}" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "throw (new function Foo() {}).$x$;"); } public void testBooleanFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testBooleanFlag2() { args.add("--debug"); args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testHelpFlag() { args.add("--help"); assertFalse( createCommandLineRunner( new String[] {"function f() {}"}).shouldRunCompiler()); } public void testExternsLifting1() throws Exception{ String code = "/** @externs */ function f() {}"; test(new String[] {code}, new String[] {}); assertEquals(2, lastCompiler.getExternsForTesting().size()); CompilerInput extern = lastCompiler.getExternsForTesting().get(1); assertNull(extern.getModule()); assertTrue(extern.isExtern()); assertEquals(code, extern.getCode()); assertEquals(1, lastCompiler.getInputsForTesting().size()); CompilerInput input = lastCompiler.getInputsForTesting().get(0); assertNotNull(input.getModule()); assertFalse(input.isExtern()); assertEquals("", input.getCode()); } public void testExternsLifting2() { args.add("--warning_level=VERBOSE"); test(new String[] {"/** @externs */ function f() {}", "f(3);"}, new String[] {"f(3);"}, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testSourceSortingOff() { test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, ProcessClosurePrimitives.LATE_PROVIDE_ERROR); } public void testSourceSortingOn() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, new String[] { "var beer = {};", "" }); } public void testSourceSortingCircularDeps1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourceSortingCircularDeps2() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('roses.lime.juice');", "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');", "goog.provide('gimlet');" + " goog.require('gin'); goog.require('roses.lime.juice');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourcePruningOn1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "" }); } public void testSourcePruningOn2() { args.add("--closure_entry_point=guinness"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var guinness = {};" }); } public void testSourcePruningOn3() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var scotch = {}, x = 3;", }); } public void testSourcePruningOn4() { args.add("--closure_entry_point=scotch"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn5() { args.add("--closure_entry_point=shiraz"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, Compiler.MISSING_ENTRY_ERROR); } public void testSourcePruningOn6() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "", "var scotch = {}, x = 3;", }); } public void testForwardDeclareDroppedTypes() { args.add("--manage_closure_dependencies=true"); args.add("--warning_level=VERBOSE"); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}", "goog.provide('Scotch'); var x = 3;" }, new String[] { "var beer = {}; function f() {}", "" }); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}" }, new String[] { "var beer = {}; function f() {}", "" }, RhinoErrorReporter.PARSE_ERROR); } public void testSourceMapExpansion1() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--create_source_map=%outname%.map"); testSame("var x = 3;"); assertEquals("/path/to/out.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion2() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion3() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo_"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo_m0.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootModule())); } public void testSourceMapFormat1() { args.add("--js_output_file"); args.add("/path/to/out.js"); testSame("var x = 3;"); assertEquals(SourceMap.Format.LEGACY, lastCompiler.getOptions().sourceMapFormat); } public void testCharSetExpansion() { testSame(""); assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset); args.add("--charset=UTF-8"); testSame(""); assertEquals("UTF-8", lastCompiler.getOptions().outputCharset); } public void testChainModuleManifest() throws Exception { useModules = ModulePattern.CHAIN; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestTo( lastCompiler.getModuleGraph(), builder); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m1}\n" + "i2\n" + "\n" + "{m3:m2}\n" + "i3\n", builder.toString()); } public void testStarModuleManifest() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestTo( lastCompiler.getModuleGraph(), builder); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m0}\n" + "i2\n" + "\n" + "{m3:m0}\n" + "i3\n", builder.toString()); } public void testVersionFlag() { args.add("--version"); testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testPrintAstFlag() { args.add("--print_ast=true"); testSame(""); assertEquals( "digraph AST {\n" + " node [color=lightblue2, style=filled];\n" + " node0 [label=\"BLOCK\"];\n" + " node1 [label=\"SCRIPT\"];\n" + " node0 -> node1 [weight=1];\n" + " node1 -> RETURN [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> RETURN [label=\"SYN_BLOCK\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> node1 [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + "}\n\n", new String(outReader.toByteArray())); } /* Helper functions */ private void testSame(String original) { testSame(new String[] { original }); } private void testSame(String[] original) { test(original, original); } private void test(String original, String compiled) { test(new String[] { original }, new String[] { compiled }); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(String[] original, String[] compiled) { test(original, compiled, null); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. * If {@code warning} is non-null, we will also check if the given * warning type was emitted. */ private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); if (warning == null) { assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); } Node root = compiler.getRoot().getLastChild(); if (useStringComparison) { assertEquals(Joiner.on("").join(compiled), compiler.toSource()); } else { Node expectedRoot = parse(compiled); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } /** * Asserts that when compiling, there is an error or warning. */ private void test(String original, DiagnosticType warning) { test(new String[] { original }, warning); } /** * Asserts that when compiling, there is an error or warning. */ private void test(String[] original, DiagnosticType warning) { Compiler compiler = compile(original); assertEquals("Expected exactly one warning or error " + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 1, compiler.getErrors().length + compiler.getWarnings().length); assertTrue(exitCodes.size() > 0); int lastExitCode = exitCodes.get(exitCodes.size() - 1); if (compiler.getErrors().length > 0) { assertEquals(1, compiler.getErrors().length); assertEquals(warning, compiler.getErrors()[0].getType()); assertEquals(1, lastExitCode); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); assertEquals(0, lastExitCode); } } private CommandLineRunner createCommandLineRunner(String[] original) { for (int i = 0; i < original.length; i++) { args.add("--js"); args.add("/path/to/input" + i + ".js"); if (useModules == ModulePattern.CHAIN) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? (":mod" + (i - 1)) : "")); } else if (useModules == ModulePattern.STAR) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? ":mod0" : "")); } } String[] argStrings = args.toArray(new String[] {}); return new CommandLineRunner( argStrings, new PrintStream(outReader), new PrintStream(errReader)); } private Compiler compile(String[] original) { CommandLineRunner runner = createCommandLineRunner(original); assertTrue(runner.shouldRunCompiler()); Supplier<List<JSSourceFile>> inputsSupplier = null; Supplier<List<JSModule>> modulesSupplier = null; if (useModules == ModulePattern.NONE) { List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } inputsSupplier = Suppliers.ofInstance(inputs); } else if (useModules == ModulePattern.STAR) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleStar(original))); } else if (useModules == ModulePattern.CHAIN) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleChain(original))); } else { throw new IllegalArgumentException("Unknown module type: " + useModules); } runner.enableTestMode( Suppliers.<List<JSSourceFile>>ofInstance(externs), inputsSupplier, modulesSupplier, new Function<Integer, Boolean>() { @Override public Boolean apply(Integer code) { return exitCodes.add(code); } }); runner.run(); lastCompiler = runner.getCompiler(); lastCommandLineRunner = runner; return lastCompiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = new CommandLineRunner(argStrings); Compiler compiler = runner.createCompiler(); List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } compiler.init(externs, inputs, new CompilerOptions()); Node all = compiler.parseInputs(); Node n = all.getLastChild(); return n; } }
public void test_printParseZoneDawsonCreek() { // clashes with shorter Dawson DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, DateTimeZone.forID("America/Dawson_Creek")); assertEquals("2007-03-04 12:30 America/Dawson_Creek", f.print(dt)); assertEquals(dt, f.parseDateTime("2007-03-04 12:30 America/Dawson_Creek")); }
org.joda.time.format.TestDateTimeFormatterBuilder::test_printParseZoneDawsonCreek
src/test/java/org/joda/time/format/TestDateTimeFormatterBuilder.java
262
src/test/java/org/joda/time/format/TestDateTimeFormatterBuilder.java
test_printParseZoneDawsonCreek
/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; /** * This class is a Junit unit test for DateTimeFormatterBuilder. * * @author Stephen Colebourne * @author Brian S O'Neill */ public class TestDateTimeFormatterBuilder extends TestCase { private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFormatterBuilder.class); } public TestDateTimeFormatterBuilder(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_toFormatter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); try { bld.toFormatter(); fail(); } catch (UnsupportedOperationException ex) {} bld.appendLiteral('X'); assertNotNull(bld.toFormatter()); } public void test_toPrinter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); try { bld.toPrinter(); fail(); } catch (UnsupportedOperationException ex) {} bld.appendLiteral('X'); assertNotNull(bld.toPrinter()); } public void test_toParser() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); try { bld.toParser(); fail(); } catch (UnsupportedOperationException ex) {} bld.appendLiteral('X'); assertNotNull(bld.toParser()); } //----------------------------------------------------------------------- public void test_canBuildFormatter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); assertEquals(false, bld.canBuildFormatter()); bld.appendLiteral('X'); assertEquals(true, bld.canBuildFormatter()); } public void test_canBuildPrinter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); assertEquals(false, bld.canBuildPrinter()); bld.appendLiteral('X'); assertEquals(true, bld.canBuildPrinter()); } public void test_canBuildParser() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); assertEquals(false, bld.canBuildParser()); bld.appendLiteral('X'); assertEquals(true, bld.canBuildParser()); } //----------------------------------------------------------------------- public void test_append_Formatter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendLiteral('Y'); DateTimeFormatter f = bld.toFormatter(); DateTimeFormatterBuilder bld2 = new DateTimeFormatterBuilder(); bld2.appendLiteral('X'); bld2.append(f); bld2.appendLiteral('Z'); assertEquals("XYZ", bld2.toFormatter().print(0L)); } //----------------------------------------------------------------------- public void test_append_Printer() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendLiteral('Y'); DateTimePrinter p = bld.toPrinter(); DateTimeFormatterBuilder bld2 = new DateTimeFormatterBuilder(); bld2.appendLiteral('X'); bld2.append(p); bld2.appendLiteral('Z'); assertEquals("XYZ", bld2.toFormatter().print(0L)); } //----------------------------------------------------------------------- public void test_appendFixedDecimal() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendFixedDecimal(DateTimeFieldType.year(), 4); DateTimeFormatter f = bld.toFormatter(); assertEquals("2007", f.print(new DateTime("2007-01-01"))); assertEquals("0123", f.print(new DateTime("123-01-01"))); assertEquals("0001", f.print(new DateTime("1-2-3"))); assertEquals("99999", f.print(new DateTime("99999-2-3"))); assertEquals("-0099", f.print(new DateTime("-99-2-3"))); assertEquals("0000", f.print(new DateTime("0-2-3"))); assertEquals(2001, f.parseDateTime("2001").getYear()); try { f.parseDateTime("-2001"); fail(); } catch (IllegalArgumentException e) { } try { f.parseDateTime("200"); fail(); } catch (IllegalArgumentException e) { } try { f.parseDateTime("20016"); fail(); } catch (IllegalArgumentException e) { } bld = new DateTimeFormatterBuilder(); bld.appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2); bld.appendLiteral(':'); bld.appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2); bld.appendLiteral(':'); bld.appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2); f = bld.toFormatter(); assertEquals("01:02:34", f.print(new DateTime("T1:2:34"))); DateTime dt = f.parseDateTime("01:02:34"); assertEquals(1, dt.getHourOfDay()); assertEquals(2, dt.getMinuteOfHour()); assertEquals(34, dt.getSecondOfMinute()); try { f.parseDateTime("0145:02:34"); fail(); } catch (IllegalArgumentException e) { } try { f.parseDateTime("01:0:34"); fail(); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- public void test_appendFixedSignedDecimal() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendFixedSignedDecimal(DateTimeFieldType.year(), 4); DateTimeFormatter f = bld.toFormatter(); assertEquals("2007", f.print(new DateTime("2007-01-01"))); assertEquals("0123", f.print(new DateTime("123-01-01"))); assertEquals("0001", f.print(new DateTime("1-2-3"))); assertEquals("99999", f.print(new DateTime("99999-2-3"))); assertEquals("-0099", f.print(new DateTime("-99-2-3"))); assertEquals("0000", f.print(new DateTime("0-2-3"))); assertEquals(2001, f.parseDateTime("2001").getYear()); assertEquals(-2001, f.parseDateTime("-2001").getYear()); assertEquals(2001, f.parseDateTime("+2001").getYear()); try { f.parseDateTime("20016"); fail(); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- public void test_appendTimeZoneId() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); assertEquals("Asia/Tokyo", f.print(new DateTime(2007, 3, 4, 0, 0, 0, TOKYO))); assertEquals(TOKYO, f.parseDateTime("Asia/Tokyo").getZone()); try { f.parseDateTime("Nonsense"); fail(); } catch (IllegalArgumentException e) { } } public void test_printParseZoneTokyo() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 Asia/Tokyo", f.print(dt)); assertEquals(dt, f.parseDateTime("2007-03-04 12:30 Asia/Tokyo")); } public void test_printParseZoneParis() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, PARIS); assertEquals("2007-03-04 12:30 Europe/Paris", f.print(dt)); assertEquals(dt, f.parseDateTime("2007-03-04 12:30 Europe/Paris")); assertEquals(dt, f.withOffsetParsed().parseDateTime("2007-03-04 12:30 Europe/Paris")); } public void test_printParseZoneDawsonCreek() { // clashes with shorter Dawson DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, DateTimeZone.forID("America/Dawson_Creek")); assertEquals("2007-03-04 12:30 America/Dawson_Creek", f.print(dt)); assertEquals(dt, f.parseDateTime("2007-03-04 12:30 America/Dawson_Creek")); } public void test_printParseOffset() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 +09:00", f.print(dt)); assertEquals(dt.withZone(DateTimeZone.getDefault()), f.parseDateTime("2007-03-04 12:30 +09:00")); assertEquals(dt, f.withZone(TOKYO).parseDateTime("2007-03-04 12:30 +09:00")); assertEquals(dt.withZone(DateTimeZone.forOffsetHours(9)), f.withOffsetParsed().parseDateTime("2007-03-04 12:30 +09:00")); } public void test_printParseOffsetAndZone() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 +09:00 Asia/Tokyo", f.print(dt)); assertEquals(dt, f.withZone(TOKYO).parseDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); assertEquals(dt.withZone(PARIS), f.withZone(PARIS).parseDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); assertEquals(dt.withZone(DateTimeZone.forOffsetHours(9)), f.withOffsetParsed().parseDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); } public void test_parseWrongOffset() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2); DateTimeFormatter f = bld.toFormatter(); DateTime expected = new DateTime(2007, 3, 4, 12, 30, 0, DateTimeZone.forOffsetHours(7)); // parses offset time then adjusts to requested zone assertEquals(expected.withZone(TOKYO), f.withZone(TOKYO).parseDateTime("2007-03-04 12:30 +07:00")); // parses offset time returning offset zone assertEquals(expected, f.withOffsetParsed().parseDateTime("2007-03-04 12:30 +07:00")); // parses offset time then converts to default zone assertEquals(expected.withZone(DateTimeZone.getDefault()), f.parseDateTime("2007-03-04 12:30 +07:00")); } public void test_parseWrongOffsetAndZone() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime expected = new DateTime(2007, 3, 4, 12, 30, 0, DateTimeZone.forOffsetHours(7)); // parses offset time then adjusts to parsed zone assertEquals(expected.withZone(TOKYO), f.parseDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); // parses offset time then adjusts to requested zone assertEquals(expected.withZone(TOKYO), f.withZone(TOKYO).parseDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); // parses offset time returning offset zone (ignores zone) assertEquals(expected, f.withOffsetParsed().parseDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); } //----------------------------------------------------------------------- public void test_localPrintParseZoneTokyo() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 Asia/Tokyo", f.print(dt)); LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30); assertEquals(expected, f.parseLocalDateTime("2007-03-04 12:30 Asia/Tokyo")); } public void test_localPrintParseOffset() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 +09:00", f.print(dt)); LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30); assertEquals(expected, f.parseLocalDateTime("2007-03-04 12:30 +09:00")); assertEquals(expected, f.withZone(TOKYO).parseLocalDateTime("2007-03-04 12:30 +09:00")); assertEquals(expected, f.withOffsetParsed().parseLocalDateTime("2007-03-04 12:30 +09:00")); } public void test_localPrintParseOffsetAndZone() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 +09:00 Asia/Tokyo", f.print(dt)); LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30); assertEquals(expected, f.withZone(TOKYO).parseLocalDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); assertEquals(expected, f.withZone(PARIS).parseLocalDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); } public void test_localParseWrongOffsetAndZone() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30); // parses offset time then adjusts to parsed zone assertEquals(expected, f.parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); // parses offset time then adjusts to requested zone assertEquals(expected, f.withZone(TOKYO).parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); // parses offset time returning offset zone (ignores zone) assertEquals(expected, f.withOffsetParsed().parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); } //----------------------------------------------------------------------- public void test_printParseShortName() {} // Defects4J: flaky method // public void test_printParseShortName() { // DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() // .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneShortName(); // DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); // // DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); // assertEquals("2011-01-04 12:30 GMT", f.print(dt1)); // DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); // assertEquals("2011-07-04 12:30 BST", f.print(dt2)); // try { // f.parseDateTime("2007-03-04 12:30 GMT"); // fail(); // } catch (IllegalArgumentException e) { // } // } public void test_printParseShortNameWithLookup() {} // Defects4J: flaky method // public void test_printParseShortNameWithLookup() { // Map<String, DateTimeZone> lookup = new LinkedHashMap<String, DateTimeZone>(); // lookup.put("GMT", LONDON); // lookup.put("BST", LONDON); // DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() // .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneShortName(lookup); // DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); // // DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); // assertEquals("2011-01-04 12:30 GMT", f.print(dt1)); // DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); // assertEquals("2011-07-04 12:30 BST", f.print(dt2)); // // assertEquals(dt1, f.parseDateTime("2011-01-04 12:30 GMT")); // assertEquals(dt2, f.parseDateTime("2011-07-04 12:30 BST")); // try { // f.parseDateTime("2007-03-04 12:30 EST"); // fail(); // } catch (IllegalArgumentException e) { // } // } //----------------------------------------------------------------------- public void test_printParseLongName() {} // Defects4J: flaky method // public void test_printParseLongName() { // DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() // .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneName(); // DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); // // DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); // assertEquals("2011-01-04 12:30 Greenwich Mean Time", f.print(dt1)); // DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); // assertEquals("2011-07-04 12:30 British Summer Time", f.print(dt2)); // try { // f.parseDateTime("2007-03-04 12:30 GMT"); // fail(); // } catch (IllegalArgumentException e) { // } // } public void test_printParseLongNameWithLookup() {} // Defects4J: flaky method // public void test_printParseLongNameWithLookup() { // Map<String, DateTimeZone> lookup = new LinkedHashMap<String, DateTimeZone>(); // lookup.put("Greenwich Mean Time", LONDON); // lookup.put("British Summer Time", LONDON); // DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() // .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneName(lookup); // DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); // // DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); // assertEquals("2011-01-04 12:30 Greenwich Mean Time", f.print(dt1)); // DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); // assertEquals("2011-07-04 12:30 British Summer Time", f.print(dt2)); // // assertEquals(dt1, f.parseDateTime("2011-01-04 12:30 Greenwich Mean Time")); // assertEquals(dt2, f.parseDateTime("2011-07-04 12:30 British Summer Time")); // try { // f.parseDateTime("2007-03-04 12:30 EST"); // fail(); // } catch (IllegalArgumentException e) { // } // } }
// You are a professional Java test case writer, please create a test case named `test_printParseZoneDawsonCreek` for the issue `Time-126`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Time-126 // // ## Issue-Title: // #126 Errors creating/parsing dates with specific time zones. // // // // // // ## Issue-Description: // Consider the following test code using Joda 2.0 // // // import org.joda.time.DateTime; // // import org.joda.time.DateTimeZone; // // import org.joda.time.format.DateTimeFormat; // // import org.joda.time.format.DateTimeFormatter; // // // import java.util.Set; // // // public class JodaDateTimeZoneTester { // // // // ``` // private static DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss.SSS ZZZ"); // private static int numTimeZonesTested = 0; // private static int numTimeZonesPassed = 0; // private static int numTimeZonesFailed = 0; // private static int numTimeZonesException = 0; // // private static String convertDateTimeToFormattedString(DateTime dateTime) { // return formatter.print(dateTime); // } // // private static DateTime parseStringToDateTime(String formattedDateTime) { // return formatter.parseDateTime(formattedDateTime); // } // // private static void testDateTimeFormatter(DateTime dateTime, String timeZone) { // numTimeZonesTested++; // // final String dateTimeZoneId = dateTime.getZone().getID(); // // if (!timeZone.equals(dateTimeZoneId)) { // numTimeZonesFailed++; // System.out.println(timeZone + " failed to construct into the proper date time zone - constructed time zone = " + dateTimeZoneId); // return; // } // try { // DateTime convertedDateTime = parseStringToDateTime(convertDateTimeToFormattedString(dateTime)); // // if (dateTime.equals(convertedDateTime)) { // numTimeZonesPassed++; // //System.out.println(dateTime.getZone().getID() + " passed."); // } else { // numTimeZonesFailed++; // System.out.println("Formatter failed for time zone ID: " + dateTimeZoneId + " converted it to: " + convertedDateTime.getZone().getID()); // } // } catch (IllegalArgumentException iae) { // numTimeZonesException++; // System.out.println("Formatter threw exception for time zone id: " + dateTimeZoneId); // } // } // // public static void main(String[] args) { // Set<String> timeZones = DateTimeZone.getAvailableIDs(); // // for (String timeZone : timeZones) { // testDateTimeFormatter(DateTime.now().withZone(DateTimeZone.forID(timeZone)), timeZone); // } // // System.out.println(); // System.out.println("Number of Time Zones tested: " + numTimeZonesTested); // System.out.println("Number passed: " + numTimeZonesPassed); // System.out.println("Number failed: " + numTimeZonesFailed); // System.out.println("Number exceptions: " + numTimeZonesException); // System.out.println(); // } // // ``` // // } // // // The results are out of 572 time zones 130 fail and 30 throw exceptions. // // // The failures are the most interesting. When I query DateTimeZone to get its time zone ids I will get a time zone like America/Atka. When I take that id and create a date time with it its time zone id is America/Adak. It is like there are multiple list of time zones in Joda time and they are out of sync. // // // Source code is attached. // // // // public void test_printParseZoneDawsonCreek() {
262
20
254
src/test/java/org/joda/time/format/TestDateTimeFormatterBuilder.java
src/test/java
```markdown ## Issue-ID: Time-126 ## Issue-Title: #126 Errors creating/parsing dates with specific time zones. ## Issue-Description: Consider the following test code using Joda 2.0 import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.Set; public class JodaDateTimeZoneTester { ``` private static DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss.SSS ZZZ"); private static int numTimeZonesTested = 0; private static int numTimeZonesPassed = 0; private static int numTimeZonesFailed = 0; private static int numTimeZonesException = 0; private static String convertDateTimeToFormattedString(DateTime dateTime) { return formatter.print(dateTime); } private static DateTime parseStringToDateTime(String formattedDateTime) { return formatter.parseDateTime(formattedDateTime); } private static void testDateTimeFormatter(DateTime dateTime, String timeZone) { numTimeZonesTested++; final String dateTimeZoneId = dateTime.getZone().getID(); if (!timeZone.equals(dateTimeZoneId)) { numTimeZonesFailed++; System.out.println(timeZone + " failed to construct into the proper date time zone - constructed time zone = " + dateTimeZoneId); return; } try { DateTime convertedDateTime = parseStringToDateTime(convertDateTimeToFormattedString(dateTime)); if (dateTime.equals(convertedDateTime)) { numTimeZonesPassed++; //System.out.println(dateTime.getZone().getID() + " passed."); } else { numTimeZonesFailed++; System.out.println("Formatter failed for time zone ID: " + dateTimeZoneId + " converted it to: " + convertedDateTime.getZone().getID()); } } catch (IllegalArgumentException iae) { numTimeZonesException++; System.out.println("Formatter threw exception for time zone id: " + dateTimeZoneId); } } public static void main(String[] args) { Set<String> timeZones = DateTimeZone.getAvailableIDs(); for (String timeZone : timeZones) { testDateTimeFormatter(DateTime.now().withZone(DateTimeZone.forID(timeZone)), timeZone); } System.out.println(); System.out.println("Number of Time Zones tested: " + numTimeZonesTested); System.out.println("Number passed: " + numTimeZonesPassed); System.out.println("Number failed: " + numTimeZonesFailed); System.out.println("Number exceptions: " + numTimeZonesException); System.out.println(); } ``` } The results are out of 572 time zones 130 fail and 30 throw exceptions. The failures are the most interesting. When I query DateTimeZone to get its time zone ids I will get a time zone like America/Atka. When I take that id and create a date time with it its time zone id is America/Adak. It is like there are multiple list of time zones in Joda time and they are out of sync. Source code is attached. ``` You are a professional Java test case writer, please create a test case named `test_printParseZoneDawsonCreek` for the issue `Time-126`, utilizing the provided issue report information and the following function signature. ```java public void test_printParseZoneDawsonCreek() { ```
254
[ "org.joda.time.format.DateTimeFormatterBuilder" ]
1b0e880585fbed52665bcfe24cfad4dab0088a0011b334831eea21f79cfd511f
public void test_printParseZoneDawsonCreek()
// You are a professional Java test case writer, please create a test case named `test_printParseZoneDawsonCreek` for the issue `Time-126`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Time-126 // // ## Issue-Title: // #126 Errors creating/parsing dates with specific time zones. // // // // // // ## Issue-Description: // Consider the following test code using Joda 2.0 // // // import org.joda.time.DateTime; // // import org.joda.time.DateTimeZone; // // import org.joda.time.format.DateTimeFormat; // // import org.joda.time.format.DateTimeFormatter; // // // import java.util.Set; // // // public class JodaDateTimeZoneTester { // // // // ``` // private static DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss.SSS ZZZ"); // private static int numTimeZonesTested = 0; // private static int numTimeZonesPassed = 0; // private static int numTimeZonesFailed = 0; // private static int numTimeZonesException = 0; // // private static String convertDateTimeToFormattedString(DateTime dateTime) { // return formatter.print(dateTime); // } // // private static DateTime parseStringToDateTime(String formattedDateTime) { // return formatter.parseDateTime(formattedDateTime); // } // // private static void testDateTimeFormatter(DateTime dateTime, String timeZone) { // numTimeZonesTested++; // // final String dateTimeZoneId = dateTime.getZone().getID(); // // if (!timeZone.equals(dateTimeZoneId)) { // numTimeZonesFailed++; // System.out.println(timeZone + " failed to construct into the proper date time zone - constructed time zone = " + dateTimeZoneId); // return; // } // try { // DateTime convertedDateTime = parseStringToDateTime(convertDateTimeToFormattedString(dateTime)); // // if (dateTime.equals(convertedDateTime)) { // numTimeZonesPassed++; // //System.out.println(dateTime.getZone().getID() + " passed."); // } else { // numTimeZonesFailed++; // System.out.println("Formatter failed for time zone ID: " + dateTimeZoneId + " converted it to: " + convertedDateTime.getZone().getID()); // } // } catch (IllegalArgumentException iae) { // numTimeZonesException++; // System.out.println("Formatter threw exception for time zone id: " + dateTimeZoneId); // } // } // // public static void main(String[] args) { // Set<String> timeZones = DateTimeZone.getAvailableIDs(); // // for (String timeZone : timeZones) { // testDateTimeFormatter(DateTime.now().withZone(DateTimeZone.forID(timeZone)), timeZone); // } // // System.out.println(); // System.out.println("Number of Time Zones tested: " + numTimeZonesTested); // System.out.println("Number passed: " + numTimeZonesPassed); // System.out.println("Number failed: " + numTimeZonesFailed); // System.out.println("Number exceptions: " + numTimeZonesException); // System.out.println(); // } // // ``` // // } // // // The results are out of 572 time zones 130 fail and 30 throw exceptions. // // // The failures are the most interesting. When I query DateTimeZone to get its time zone ids I will get a time zone like America/Atka. When I take that id and create a date time with it its time zone id is America/Adak. It is like there are multiple list of time zones in Joda time and they are out of sync. // // // Source code is attached. // // // //
Time
/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time.format; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; /** * This class is a Junit unit test for DateTimeFormatterBuilder. * * @author Stephen Colebourne * @author Brian S O'Neill */ public class TestDateTimeFormatterBuilder extends TestCase { private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFormatterBuilder.class); } public TestDateTimeFormatterBuilder(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_toFormatter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); try { bld.toFormatter(); fail(); } catch (UnsupportedOperationException ex) {} bld.appendLiteral('X'); assertNotNull(bld.toFormatter()); } public void test_toPrinter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); try { bld.toPrinter(); fail(); } catch (UnsupportedOperationException ex) {} bld.appendLiteral('X'); assertNotNull(bld.toPrinter()); } public void test_toParser() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); try { bld.toParser(); fail(); } catch (UnsupportedOperationException ex) {} bld.appendLiteral('X'); assertNotNull(bld.toParser()); } //----------------------------------------------------------------------- public void test_canBuildFormatter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); assertEquals(false, bld.canBuildFormatter()); bld.appendLiteral('X'); assertEquals(true, bld.canBuildFormatter()); } public void test_canBuildPrinter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); assertEquals(false, bld.canBuildPrinter()); bld.appendLiteral('X'); assertEquals(true, bld.canBuildPrinter()); } public void test_canBuildParser() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); assertEquals(false, bld.canBuildParser()); bld.appendLiteral('X'); assertEquals(true, bld.canBuildParser()); } //----------------------------------------------------------------------- public void test_append_Formatter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendLiteral('Y'); DateTimeFormatter f = bld.toFormatter(); DateTimeFormatterBuilder bld2 = new DateTimeFormatterBuilder(); bld2.appendLiteral('X'); bld2.append(f); bld2.appendLiteral('Z'); assertEquals("XYZ", bld2.toFormatter().print(0L)); } //----------------------------------------------------------------------- public void test_append_Printer() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendLiteral('Y'); DateTimePrinter p = bld.toPrinter(); DateTimeFormatterBuilder bld2 = new DateTimeFormatterBuilder(); bld2.appendLiteral('X'); bld2.append(p); bld2.appendLiteral('Z'); assertEquals("XYZ", bld2.toFormatter().print(0L)); } //----------------------------------------------------------------------- public void test_appendFixedDecimal() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendFixedDecimal(DateTimeFieldType.year(), 4); DateTimeFormatter f = bld.toFormatter(); assertEquals("2007", f.print(new DateTime("2007-01-01"))); assertEquals("0123", f.print(new DateTime("123-01-01"))); assertEquals("0001", f.print(new DateTime("1-2-3"))); assertEquals("99999", f.print(new DateTime("99999-2-3"))); assertEquals("-0099", f.print(new DateTime("-99-2-3"))); assertEquals("0000", f.print(new DateTime("0-2-3"))); assertEquals(2001, f.parseDateTime("2001").getYear()); try { f.parseDateTime("-2001"); fail(); } catch (IllegalArgumentException e) { } try { f.parseDateTime("200"); fail(); } catch (IllegalArgumentException e) { } try { f.parseDateTime("20016"); fail(); } catch (IllegalArgumentException e) { } bld = new DateTimeFormatterBuilder(); bld.appendFixedDecimal(DateTimeFieldType.hourOfDay(), 2); bld.appendLiteral(':'); bld.appendFixedDecimal(DateTimeFieldType.minuteOfHour(), 2); bld.appendLiteral(':'); bld.appendFixedDecimal(DateTimeFieldType.secondOfMinute(), 2); f = bld.toFormatter(); assertEquals("01:02:34", f.print(new DateTime("T1:2:34"))); DateTime dt = f.parseDateTime("01:02:34"); assertEquals(1, dt.getHourOfDay()); assertEquals(2, dt.getMinuteOfHour()); assertEquals(34, dt.getSecondOfMinute()); try { f.parseDateTime("0145:02:34"); fail(); } catch (IllegalArgumentException e) { } try { f.parseDateTime("01:0:34"); fail(); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- public void test_appendFixedSignedDecimal() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendFixedSignedDecimal(DateTimeFieldType.year(), 4); DateTimeFormatter f = bld.toFormatter(); assertEquals("2007", f.print(new DateTime("2007-01-01"))); assertEquals("0123", f.print(new DateTime("123-01-01"))); assertEquals("0001", f.print(new DateTime("1-2-3"))); assertEquals("99999", f.print(new DateTime("99999-2-3"))); assertEquals("-0099", f.print(new DateTime("-99-2-3"))); assertEquals("0000", f.print(new DateTime("0-2-3"))); assertEquals(2001, f.parseDateTime("2001").getYear()); assertEquals(-2001, f.parseDateTime("-2001").getYear()); assertEquals(2001, f.parseDateTime("+2001").getYear()); try { f.parseDateTime("20016"); fail(); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- public void test_appendTimeZoneId() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); assertEquals("Asia/Tokyo", f.print(new DateTime(2007, 3, 4, 0, 0, 0, TOKYO))); assertEquals(TOKYO, f.parseDateTime("Asia/Tokyo").getZone()); try { f.parseDateTime("Nonsense"); fail(); } catch (IllegalArgumentException e) { } } public void test_printParseZoneTokyo() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 Asia/Tokyo", f.print(dt)); assertEquals(dt, f.parseDateTime("2007-03-04 12:30 Asia/Tokyo")); } public void test_printParseZoneParis() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, PARIS); assertEquals("2007-03-04 12:30 Europe/Paris", f.print(dt)); assertEquals(dt, f.parseDateTime("2007-03-04 12:30 Europe/Paris")); assertEquals(dt, f.withOffsetParsed().parseDateTime("2007-03-04 12:30 Europe/Paris")); } public void test_printParseZoneDawsonCreek() { // clashes with shorter Dawson DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, DateTimeZone.forID("America/Dawson_Creek")); assertEquals("2007-03-04 12:30 America/Dawson_Creek", f.print(dt)); assertEquals(dt, f.parseDateTime("2007-03-04 12:30 America/Dawson_Creek")); } public void test_printParseOffset() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 +09:00", f.print(dt)); assertEquals(dt.withZone(DateTimeZone.getDefault()), f.parseDateTime("2007-03-04 12:30 +09:00")); assertEquals(dt, f.withZone(TOKYO).parseDateTime("2007-03-04 12:30 +09:00")); assertEquals(dt.withZone(DateTimeZone.forOffsetHours(9)), f.withOffsetParsed().parseDateTime("2007-03-04 12:30 +09:00")); } public void test_printParseOffsetAndZone() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 +09:00 Asia/Tokyo", f.print(dt)); assertEquals(dt, f.withZone(TOKYO).parseDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); assertEquals(dt.withZone(PARIS), f.withZone(PARIS).parseDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); assertEquals(dt.withZone(DateTimeZone.forOffsetHours(9)), f.withOffsetParsed().parseDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); } public void test_parseWrongOffset() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2); DateTimeFormatter f = bld.toFormatter(); DateTime expected = new DateTime(2007, 3, 4, 12, 30, 0, DateTimeZone.forOffsetHours(7)); // parses offset time then adjusts to requested zone assertEquals(expected.withZone(TOKYO), f.withZone(TOKYO).parseDateTime("2007-03-04 12:30 +07:00")); // parses offset time returning offset zone assertEquals(expected, f.withOffsetParsed().parseDateTime("2007-03-04 12:30 +07:00")); // parses offset time then converts to default zone assertEquals(expected.withZone(DateTimeZone.getDefault()), f.parseDateTime("2007-03-04 12:30 +07:00")); } public void test_parseWrongOffsetAndZone() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime expected = new DateTime(2007, 3, 4, 12, 30, 0, DateTimeZone.forOffsetHours(7)); // parses offset time then adjusts to parsed zone assertEquals(expected.withZone(TOKYO), f.parseDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); // parses offset time then adjusts to requested zone assertEquals(expected.withZone(TOKYO), f.withZone(TOKYO).parseDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); // parses offset time returning offset zone (ignores zone) assertEquals(expected, f.withOffsetParsed().parseDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); } //----------------------------------------------------------------------- public void test_localPrintParseZoneTokyo() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 Asia/Tokyo", f.print(dt)); LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30); assertEquals(expected, f.parseLocalDateTime("2007-03-04 12:30 Asia/Tokyo")); } public void test_localPrintParseOffset() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 +09:00", f.print(dt)); LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30); assertEquals(expected, f.parseLocalDateTime("2007-03-04 12:30 +09:00")); assertEquals(expected, f.withZone(TOKYO).parseLocalDateTime("2007-03-04 12:30 +09:00")); assertEquals(expected, f.withOffsetParsed().parseLocalDateTime("2007-03-04 12:30 +09:00")); } public void test_localPrintParseOffsetAndZone() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO); assertEquals("2007-03-04 12:30 +09:00 Asia/Tokyo", f.print(dt)); LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30); assertEquals(expected, f.withZone(TOKYO).parseLocalDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); assertEquals(expected, f.withZone(PARIS).parseLocalDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo")); } public void test_localParseWrongOffsetAndZone() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId(); DateTimeFormatter f = bld.toFormatter(); LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30); // parses offset time then adjusts to parsed zone assertEquals(expected, f.parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); // parses offset time then adjusts to requested zone assertEquals(expected, f.withZone(TOKYO).parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); // parses offset time returning offset zone (ignores zone) assertEquals(expected, f.withOffsetParsed().parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo")); } //----------------------------------------------------------------------- public void test_printParseShortName() {} // Defects4J: flaky method // public void test_printParseShortName() { // DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() // .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneShortName(); // DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); // // DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); // assertEquals("2011-01-04 12:30 GMT", f.print(dt1)); // DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); // assertEquals("2011-07-04 12:30 BST", f.print(dt2)); // try { // f.parseDateTime("2007-03-04 12:30 GMT"); // fail(); // } catch (IllegalArgumentException e) { // } // } public void test_printParseShortNameWithLookup() {} // Defects4J: flaky method // public void test_printParseShortNameWithLookup() { // Map<String, DateTimeZone> lookup = new LinkedHashMap<String, DateTimeZone>(); // lookup.put("GMT", LONDON); // lookup.put("BST", LONDON); // DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() // .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneShortName(lookup); // DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); // // DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); // assertEquals("2011-01-04 12:30 GMT", f.print(dt1)); // DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); // assertEquals("2011-07-04 12:30 BST", f.print(dt2)); // // assertEquals(dt1, f.parseDateTime("2011-01-04 12:30 GMT")); // assertEquals(dt2, f.parseDateTime("2011-07-04 12:30 BST")); // try { // f.parseDateTime("2007-03-04 12:30 EST"); // fail(); // } catch (IllegalArgumentException e) { // } // } //----------------------------------------------------------------------- public void test_printParseLongName() {} // Defects4J: flaky method // public void test_printParseLongName() { // DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() // .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneName(); // DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); // // DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); // assertEquals("2011-01-04 12:30 Greenwich Mean Time", f.print(dt1)); // DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); // assertEquals("2011-07-04 12:30 British Summer Time", f.print(dt2)); // try { // f.parseDateTime("2007-03-04 12:30 GMT"); // fail(); // } catch (IllegalArgumentException e) { // } // } public void test_printParseLongNameWithLookup() {} // Defects4J: flaky method // public void test_printParseLongNameWithLookup() { // Map<String, DateTimeZone> lookup = new LinkedHashMap<String, DateTimeZone>(); // lookup.put("Greenwich Mean Time", LONDON); // lookup.put("British Summer Time", LONDON); // DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder() // .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneName(lookup); // DateTimeFormatter f = bld.toFormatter().withLocale(Locale.ENGLISH); // // DateTime dt1 = new DateTime(2011, 1, 4, 12, 30, 0, LONDON); // assertEquals("2011-01-04 12:30 Greenwich Mean Time", f.print(dt1)); // DateTime dt2 = new DateTime(2011, 7, 4, 12, 30, 0, LONDON); // assertEquals("2011-07-04 12:30 British Summer Time", f.print(dt2)); // // assertEquals(dt1, f.parseDateTime("2011-01-04 12:30 Greenwich Mean Time")); // assertEquals(dt2, f.parseDateTime("2011-07-04 12:30 British Summer Time")); // try { // f.parseDateTime("2007-03-04 12:30 EST"); // fail(); // } catch (IllegalArgumentException e) { // } // } }
@Test public void testLang865() { assertValidToLocale("_GB", "", "GB", ""); assertValidToLocale("_GB_P", "", "GB", "P"); assertValidToLocale("_GB_POSIX", "", "GB", "POSIX"); try { LocaleUtils.toLocale("_G"); fail("Must be at least 3 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_Gb"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_gB"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_1B"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_G1"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GB_"); fail("Must be at least 5 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GBAP"); fail("Must have underscore after the country if starts with underscore and is at least 5 chars"); } catch (final IllegalArgumentException iae) { } }
org.apache.commons.lang3.LocaleUtilsTest::testLang865
src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
542
src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
testLang865
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link LocaleUtils}. * * @version $Id$ */ public class LocaleUtilsTest { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); @Before public void setUp() throws Exception { // Testing #LANG-304. Must be called before availableLocaleSet is called. LocaleUtils.isAvailableLocale(Locale.getDefault()); } //----------------------------------------------------------------------- /** * Test that constructors are public, and work, etc. */ @Test public void testConstructor() { assertNotNull(new LocaleUtils()); Constructor<?>[] cons = LocaleUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(LocaleUtils.class.getModifiers())); assertFalse(Modifier.isFinal(LocaleUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Pass in a valid language, test toLocale. * * @param language the language string */ private void assertValidToLocale(String language) { Locale locale = LocaleUtils.toLocale(language); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); //country and variant are empty assertTrue(locale.getCountry() == null || locale.getCountry().isEmpty()); assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale */ private void assertValidToLocale(String localeString, String language, String country) { Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); //variant is empty assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale * @param variant of the resulting Locale */ private void assertValidToLocale( String localeString, String language, String country, String variant) { Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); assertEquals(variant, locale.getVariant()); } /** * Test toLocale() method. */ @Test public void testToLocale_1Part() { assertEquals(null, LocaleUtils.toLocale((String) null)); assertValidToLocale("us"); assertValidToLocale("fr"); assertValidToLocale("de"); assertValidToLocale("zh"); // Valid format but lang doesnt exist, should make instance anyway assertValidToLocale("qq"); try { LocaleUtils.toLocale("Us"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("US"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u#"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uuu"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_U"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} } /** * Test toLocale() method. */ @Test public void testToLocale_2Part() { assertValidToLocale("us_EN", "us", "EN"); //valid though doesnt exist assertValidToLocale("us_ZH", "us", "ZH"); try { LocaleUtils.toLocale("us-EN"); fail("Should fail as not underscore"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_En"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_en"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_eN"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS_EN"); fail("Should fail first part not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_E3"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} } /** * Test toLocale() method. */ @Test public void testToLocale_3Part() { assertValidToLocale("us_EN_A", "us", "EN", "A"); // this isn't pretty, but was caused by a jdk bug it seems // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210525 if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertValidToLocale("us_EN_a", "us", "EN", "a"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF"); } else { assertValidToLocale("us_EN_a", "us", "EN", "A"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF"); } try { LocaleUtils.toLocale("us_EN-a"); fail("Should fail as not underscore"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_UU_"); fail("Must be 3, 5 or 7+ in length"); } catch (IllegalArgumentException iae) {} } //----------------------------------------------------------------------- /** * Helper method for local lookups. * * @param locale the input locale * @param defaultLocale the input default locale * @param expected expected results */ private void assertLocaleLookupList(Locale locale, Locale defaultLocale, Locale[] expected) { List<Locale> localeList = defaultLocale == null ? LocaleUtils.localeLookupList(locale) : LocaleUtils.localeLookupList(locale, defaultLocale); assertEquals(expected.length, localeList.size()); assertEquals(Arrays.asList(expected), localeList); assertUnmodifiableCollection(localeList); } //----------------------------------------------------------------------- /** * Test localeLookupList() method. */ @Test public void testLocaleLookupList_Locale() { assertLocaleLookupList(null, null, new Locale[0]); assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, null, new Locale[] { LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); } /** * Test localeLookupList() method. */ @Test public void testLocaleLookupList_LocaleLocale() { assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, LOCALE_EN, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_EN_US, new Locale[]{ LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_EN_US_ZZZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_FR_CA, LOCALE_EN, new Locale[] { LOCALE_FR_CA, LOCALE_FR, LOCALE_EN}); } //----------------------------------------------------------------------- /** * Test availableLocaleList() method. */ @Test public void testAvailableLocaleList() { List<Locale> list = LocaleUtils.availableLocaleList(); List<Locale> list2 = LocaleUtils.availableLocaleList(); assertNotNull(list); assertSame(list, list2); assertUnmodifiableCollection(list); Locale[] jdkLocaleArray = Locale.getAvailableLocales(); List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); assertEquals(jdkLocaleList, list); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ @Test public void testAvailableLocaleSet() { Set<Locale> set = LocaleUtils.availableLocaleSet(); Set<Locale> set2 = LocaleUtils.availableLocaleSet(); assertNotNull(set); assertSame(set, set2); assertUnmodifiableCollection(set); Locale[] jdkLocaleArray = Locale.getAvailableLocales(); List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); Set<Locale> jdkLocaleSet = new HashSet<Locale>(jdkLocaleList); assertEquals(jdkLocaleSet, set); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale() { Set<Locale> set = LocaleUtils.availableLocaleSet(); assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN)); assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US)); assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ)); assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR)); assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA)); assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ)); assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ)); } //----------------------------------------------------------------------- /** * Make sure the language by country is correct. It checks that * the LocaleUtils.languagesByCountry(country) call contains the * array of languages passed in. It may contain more due to JVM * variations. * * @param country * @param languages array of languages that should be returned */ private void assertLanguageByCountry(String country, String[] languages) { List<Locale> list = LocaleUtils.languagesByCountry(country); List<Locale> list2 = LocaleUtils.languagesByCountry(country); assertNotNull(list); assertSame(list, list2); //search through langauges for (String language : languages) { Iterator<Locale> iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { Locale locale = iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); assertEquals(country, locale.getCountry()); if (language.equals(locale.getLanguage())) { found = true; break; } } if (!found) { fail("Cound not find language: " + language + " for country: " + country); } } assertUnmodifiableCollection(list); } /** * Test languagesByCountry() method. */ @Test public void testLanguagesByCountry() { assertLanguageByCountry(null, new String[0]); assertLanguageByCountry("GB", new String[]{"en"}); assertLanguageByCountry("ZZ", new String[0]); assertLanguageByCountry("CH", new String[]{"fr", "de", "it"}); } //----------------------------------------------------------------------- /** * Make sure the country by language is correct. It checks that * the LocaleUtils.countryByLanguage(language) call contains the * array of countries passed in. It may contain more due to JVM * variations. * * * @param language * @param countries array of countries that should be returned */ private void assertCountriesByLanguage(String language, String[] countries) { List<Locale> list = LocaleUtils.countriesByLanguage(language); List<Locale> list2 = LocaleUtils.countriesByLanguage(language); assertNotNull(list); assertSame(list, list2); //search through langauges for (String countrie : countries) { Iterator<Locale> iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { Locale locale = iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); assertEquals(language, locale.getLanguage()); if (countrie.equals(locale.getCountry())) { found = true; break; } } if (!found) { fail("Cound not find language: " + countrie + " for country: " + language); } } assertUnmodifiableCollection(list); } /** * Test countriesByLanguage() method. */ @Test public void testCountriesByLanguage() { assertCountriesByLanguage(null, new String[0]); assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"}); assertCountriesByLanguage("zz", new String[0]); assertCountriesByLanguage("it", new String[]{"IT", "CH"}); } /** * @param coll the collection to check */ private static void assertUnmodifiableCollection(Collection<?> coll) { try { coll.add(null); fail(); } catch (UnsupportedOperationException ex) {} } /** * Tests #LANG-328 - only language+variant */ @Test public void testLang328() { assertValidToLocale("fr__P", "fr", "", "P"); assertValidToLocale("fr__POSIX", "fr", "", "POSIX"); } /** * Tests #LANG-865, strings starting with an underscore. */ @Test public void testLang865() { assertValidToLocale("_GB", "", "GB", ""); assertValidToLocale("_GB_P", "", "GB", "P"); assertValidToLocale("_GB_POSIX", "", "GB", "POSIX"); try { LocaleUtils.toLocale("_G"); fail("Must be at least 3 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_Gb"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_gB"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_1B"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_G1"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GB_"); fail("Must be at least 5 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GBAP"); fail("Must have underscore after the country if starts with underscore and is at least 5 chars"); } catch (final IllegalArgumentException iae) { } } }
// You are a professional Java test case writer, please create a test case named `testLang865` for the issue `Lang-LANG-865`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-865 // // ## Issue-Title: // LocaleUtils.toLocale does not parse strings starting with an underscore // // ## Issue-Description: // // Hi, // // // Javadocs of Locale.toString() states that "If the language is missing, the string will begin with an underbar.". This is not handled in the LocaleUtils.toLocale method if it is meant to be the inversion method of Locale.toString(). // // // The fix for the ticket 328 does not handle well the case "fr\_\_P", which I found out during fixing the first bug. // // // I am attaching the patch for both problems. // // // // // @Test public void testLang865() {
542
/** * Tests #LANG-865, strings starting with an underscore. */
5
502
src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-865 ## Issue-Title: LocaleUtils.toLocale does not parse strings starting with an underscore ## Issue-Description: Hi, Javadocs of Locale.toString() states that "If the language is missing, the string will begin with an underbar.". This is not handled in the LocaleUtils.toLocale method if it is meant to be the inversion method of Locale.toString(). The fix for the ticket 328 does not handle well the case "fr\_\_P", which I found out during fixing the first bug. I am attaching the patch for both problems. ``` You are a professional Java test case writer, please create a test case named `testLang865` for the issue `Lang-LANG-865`, utilizing the provided issue report information and the following function signature. ```java @Test public void testLang865() { ```
502
[ "org.apache.commons.lang3.LocaleUtils" ]
1b593893d4222634b37867e70b3d4dbb16746a55cf72fbd809ed123623e57211
@Test public void testLang865()
// You are a professional Java test case writer, please create a test case named `testLang865` for the issue `Lang-LANG-865`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-865 // // ## Issue-Title: // LocaleUtils.toLocale does not parse strings starting with an underscore // // ## Issue-Description: // // Hi, // // // Javadocs of Locale.toString() states that "If the language is missing, the string will begin with an underbar.". This is not handled in the LocaleUtils.toLocale method if it is meant to be the inversion method of Locale.toString(). // // // The fix for the ticket 328 does not handle well the case "fr\_\_P", which I found out during fixing the first bug. // // // I am attaching the patch for both problems. // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link LocaleUtils}. * * @version $Id$ */ public class LocaleUtilsTest { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); @Before public void setUp() throws Exception { // Testing #LANG-304. Must be called before availableLocaleSet is called. LocaleUtils.isAvailableLocale(Locale.getDefault()); } //----------------------------------------------------------------------- /** * Test that constructors are public, and work, etc. */ @Test public void testConstructor() { assertNotNull(new LocaleUtils()); Constructor<?>[] cons = LocaleUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(LocaleUtils.class.getModifiers())); assertFalse(Modifier.isFinal(LocaleUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Pass in a valid language, test toLocale. * * @param language the language string */ private void assertValidToLocale(String language) { Locale locale = LocaleUtils.toLocale(language); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); //country and variant are empty assertTrue(locale.getCountry() == null || locale.getCountry().isEmpty()); assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale */ private void assertValidToLocale(String localeString, String language, String country) { Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); //variant is empty assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale * @param variant of the resulting Locale */ private void assertValidToLocale( String localeString, String language, String country, String variant) { Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); assertEquals(variant, locale.getVariant()); } /** * Test toLocale() method. */ @Test public void testToLocale_1Part() { assertEquals(null, LocaleUtils.toLocale((String) null)); assertValidToLocale("us"); assertValidToLocale("fr"); assertValidToLocale("de"); assertValidToLocale("zh"); // Valid format but lang doesnt exist, should make instance anyway assertValidToLocale("qq"); try { LocaleUtils.toLocale("Us"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("US"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u#"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uuu"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_U"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} } /** * Test toLocale() method. */ @Test public void testToLocale_2Part() { assertValidToLocale("us_EN", "us", "EN"); //valid though doesnt exist assertValidToLocale("us_ZH", "us", "ZH"); try { LocaleUtils.toLocale("us-EN"); fail("Should fail as not underscore"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_En"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_en"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_eN"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS_EN"); fail("Should fail first part not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_E3"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} } /** * Test toLocale() method. */ @Test public void testToLocale_3Part() { assertValidToLocale("us_EN_A", "us", "EN", "A"); // this isn't pretty, but was caused by a jdk bug it seems // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210525 if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertValidToLocale("us_EN_a", "us", "EN", "a"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF"); } else { assertValidToLocale("us_EN_a", "us", "EN", "A"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF"); } try { LocaleUtils.toLocale("us_EN-a"); fail("Should fail as not underscore"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_UU_"); fail("Must be 3, 5 or 7+ in length"); } catch (IllegalArgumentException iae) {} } //----------------------------------------------------------------------- /** * Helper method for local lookups. * * @param locale the input locale * @param defaultLocale the input default locale * @param expected expected results */ private void assertLocaleLookupList(Locale locale, Locale defaultLocale, Locale[] expected) { List<Locale> localeList = defaultLocale == null ? LocaleUtils.localeLookupList(locale) : LocaleUtils.localeLookupList(locale, defaultLocale); assertEquals(expected.length, localeList.size()); assertEquals(Arrays.asList(expected), localeList); assertUnmodifiableCollection(localeList); } //----------------------------------------------------------------------- /** * Test localeLookupList() method. */ @Test public void testLocaleLookupList_Locale() { assertLocaleLookupList(null, null, new Locale[0]); assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, null, new Locale[] { LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); } /** * Test localeLookupList() method. */ @Test public void testLocaleLookupList_LocaleLocale() { assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, LOCALE_EN, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_EN_US, new Locale[]{ LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_EN_US_ZZZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_FR_CA, LOCALE_EN, new Locale[] { LOCALE_FR_CA, LOCALE_FR, LOCALE_EN}); } //----------------------------------------------------------------------- /** * Test availableLocaleList() method. */ @Test public void testAvailableLocaleList() { List<Locale> list = LocaleUtils.availableLocaleList(); List<Locale> list2 = LocaleUtils.availableLocaleList(); assertNotNull(list); assertSame(list, list2); assertUnmodifiableCollection(list); Locale[] jdkLocaleArray = Locale.getAvailableLocales(); List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); assertEquals(jdkLocaleList, list); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ @Test public void testAvailableLocaleSet() { Set<Locale> set = LocaleUtils.availableLocaleSet(); Set<Locale> set2 = LocaleUtils.availableLocaleSet(); assertNotNull(set); assertSame(set, set2); assertUnmodifiableCollection(set); Locale[] jdkLocaleArray = Locale.getAvailableLocales(); List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); Set<Locale> jdkLocaleSet = new HashSet<Locale>(jdkLocaleList); assertEquals(jdkLocaleSet, set); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale() { Set<Locale> set = LocaleUtils.availableLocaleSet(); assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN)); assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US)); assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ)); assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR)); assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA)); assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ)); assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ)); } //----------------------------------------------------------------------- /** * Make sure the language by country is correct. It checks that * the LocaleUtils.languagesByCountry(country) call contains the * array of languages passed in. It may contain more due to JVM * variations. * * @param country * @param languages array of languages that should be returned */ private void assertLanguageByCountry(String country, String[] languages) { List<Locale> list = LocaleUtils.languagesByCountry(country); List<Locale> list2 = LocaleUtils.languagesByCountry(country); assertNotNull(list); assertSame(list, list2); //search through langauges for (String language : languages) { Iterator<Locale> iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { Locale locale = iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); assertEquals(country, locale.getCountry()); if (language.equals(locale.getLanguage())) { found = true; break; } } if (!found) { fail("Cound not find language: " + language + " for country: " + country); } } assertUnmodifiableCollection(list); } /** * Test languagesByCountry() method. */ @Test public void testLanguagesByCountry() { assertLanguageByCountry(null, new String[0]); assertLanguageByCountry("GB", new String[]{"en"}); assertLanguageByCountry("ZZ", new String[0]); assertLanguageByCountry("CH", new String[]{"fr", "de", "it"}); } //----------------------------------------------------------------------- /** * Make sure the country by language is correct. It checks that * the LocaleUtils.countryByLanguage(language) call contains the * array of countries passed in. It may contain more due to JVM * variations. * * * @param language * @param countries array of countries that should be returned */ private void assertCountriesByLanguage(String language, String[] countries) { List<Locale> list = LocaleUtils.countriesByLanguage(language); List<Locale> list2 = LocaleUtils.countriesByLanguage(language); assertNotNull(list); assertSame(list, list2); //search through langauges for (String countrie : countries) { Iterator<Locale> iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { Locale locale = iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); assertEquals(language, locale.getLanguage()); if (countrie.equals(locale.getCountry())) { found = true; break; } } if (!found) { fail("Cound not find language: " + countrie + " for country: " + language); } } assertUnmodifiableCollection(list); } /** * Test countriesByLanguage() method. */ @Test public void testCountriesByLanguage() { assertCountriesByLanguage(null, new String[0]); assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"}); assertCountriesByLanguage("zz", new String[0]); assertCountriesByLanguage("it", new String[]{"IT", "CH"}); } /** * @param coll the collection to check */ private static void assertUnmodifiableCollection(Collection<?> coll) { try { coll.add(null); fail(); } catch (UnsupportedOperationException ex) {} } /** * Tests #LANG-328 - only language+variant */ @Test public void testLang328() { assertValidToLocale("fr__P", "fr", "", "P"); assertValidToLocale("fr__POSIX", "fr", "", "POSIX"); } /** * Tests #LANG-865, strings starting with an underscore. */ @Test public void testLang865() { assertValidToLocale("_GB", "", "GB", ""); assertValidToLocale("_GB_P", "", "GB", "P"); assertValidToLocale("_GB_POSIX", "", "GB", "POSIX"); try { LocaleUtils.toLocale("_G"); fail("Must be at least 3 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_Gb"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_gB"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_1B"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_G1"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GB_"); fail("Must be at least 5 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GBAP"); fail("Must have underscore after the country if starts with underscore and is at least 5 chars"); } catch (final IllegalArgumentException iae) { } } }
@Test(expected=NumberIsTooLargeException.class) public void testBoundaryRangeTooLarge() { final CMAESOptimizer optimizer = new CMAESOptimizer(); final MultivariateFunction fitnessFunction = new MultivariateFunction() { public double value(double[] parameters) { if (Double.isNaN(parameters[0])) { throw new MathIllegalStateException(); } final double target = 1; final double error = target - parameters[0]; return error * error; } }; final double[] start = { 0 }; // The difference between upper and lower bounds is used to used // normalize the variables: In case of overflow, NaN is produced. final double max = Double.MAX_VALUE / 2; final double tooLarge = FastMath.nextUp(max); final double[] lower = { -tooLarge }; final double[] upper = { tooLarge }; final double[] result = optimizer.optimize(10000, fitnessFunction, GoalType.MINIMIZE, start, lower, upper).getPoint(); }
org.apache.commons.math3.optimization.direct.CMAESOptimizerTest::testBoundaryRangeTooLarge
src/test/java/org/apache/commons/math3/optimization/direct/CMAESOptimizerTest.java
431
src/test/java/org/apache/commons/math3/optimization/direct/CMAESOptimizerTest.java
testBoundaryRangeTooLarge
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.optimization.direct; import java.util.Arrays; import java.util.Random; import org.apache.commons.math3.Retry; import org.apache.commons.math3.RetryRunner; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.optimization.PointValuePair; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test for {@link CMAESOptimizer}. */ @RunWith(RetryRunner.class) public class CMAESOptimizerTest { static final int DIM = 13; static final int LAMBDA = 4 + (int)(3.*Math.log(DIM)); @Test(expected = NumberIsTooLargeException.class) public void testInitOutofbounds1() { double[] startPoint = point(DIM,3); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = NumberIsTooSmallException.class) public void testInitOutofbounds2() { double[] startPoint = point(DIM, -2); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = DimensionMismatchException.class) public void testBoundariesDimensionMismatch() { double[] startPoint = point(DIM,0.5); double[] insigma = null; double[][] boundaries = boundaries(DIM+1,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = MathUnsupportedOperationException.class) public void testUnsupportedBoundaries1() { double[] startPoint = point(DIM,0.5); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1, Double.POSITIVE_INFINITY); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = MathUnsupportedOperationException.class) public void testUnsupportedBoundaries2() { double[] startPoint = point(DIM, 0.5); double[] insigma = null; final double[] lB = new double[] { -1, -1, -1, -1, -1, Double.NEGATIVE_INFINITY, -1, -1, -1, -1, -1, -1, -1 }; final double[] uB = new double[] { 2, 2, 2, Double.POSITIVE_INFINITY, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; double[][] boundaries = new double[2][]; boundaries[0] = lB; boundaries[1] = uB; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = NotPositiveException.class) public void testInputSigmaNegative() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM,-0.5); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = OutOfRangeException.class) public void testInputSigmaOutOfRange() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM, 1.1); double[][] boundaries = boundaries(DIM,-0.5,0.5); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = DimensionMismatchException.class) public void testInputSigmaDimensionMismatch() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM+1,-0.5); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test @Retry(3) public void testRosen() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test @Retry(3) public void testMaximize() {} // Defects4J: flaky method // public void testMaximize() { // double[] startPoint = point(DIM,1.0); // double[] insigma = point(DIM,0.1); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,0.0),1.0); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, true, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, false, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // boundaries = boundaries(DIM,-0.3,0.3); // startPoint = point(DIM,0.1); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, true, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // } @Test public void testEllipse() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Elli(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Elli(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testElliRotated() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new ElliRotated(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new ElliRotated(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testCigar() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Cigar(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new Cigar(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testTwoAxes() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new TwoAxes(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new TwoAxes(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-8, 1e-3, 200000, expected); } @Test public void testCigTab() {} // Defects4J: flaky method // @Test // public void testCigTab() { // double[] startPoint = point(DIM,1.0); // double[] insigma = point(DIM,0.3); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,0.0),0.0); // doTest(new CigTab(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, // 1e-13, 5e-5, 100000, expected); // doTest(new CigTab(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, // 1e-13, 5e-5, 100000, expected); // } @Test public void testSphere() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Sphere(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Sphere(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testTablet() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Tablet(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Tablet(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testDiffPow() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new DiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, true, 0, 1e-13, 1e-8, 1e-1, 100000, expected); doTest(new DiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, false, 0, 1e-13, 1e-8, 2e-1, 100000, expected); } @Test public void testSsDiffPow() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new SsDiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, true, 0, 1e-13, 1e-4, 1e-1, 200000, expected); doTest(new SsDiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, false, 0, 1e-13, 1e-4, 1e-1, 200000, expected); } @Test public void testAckley() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,1.0); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Ackley(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-9, 1e-5, 100000, expected); doTest(new Ackley(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-9, 1e-5, 100000, expected); } @Test public void testRastrigin() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Rastrigin(), startPoint, insigma, boundaries, GoalType.MINIMIZE, (int)(200*Math.sqrt(DIM)), true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new Rastrigin(), startPoint, insigma, boundaries, GoalType.MINIMIZE, (int)(200*Math.sqrt(DIM)), false, 0, 1e-13, 1e-13, 1e-6, 200000, expected); } @Test public void testConstrainedRosen() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testDiagonalRosen() {} // Defects4J: flaky method // @Test // public void testDiagonalRosen() { // double[] startPoint = point(DIM,0.1); // double[] insigma = point(DIM,0.1); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,1.0),0.0); // doTest(new Rosen(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, false, 1, 1e-13, // 1e-10, 1e-4, 1000000, expected); // } @Test public void testMath864() { final CMAESOptimizer optimizer = new CMAESOptimizer(); final MultivariateFunction fitnessFunction = new MultivariateFunction() { public double value(double[] parameters) { final double target = 1; final double error = target - parameters[0]; return error * error; } }; final double[] start = { 0 }; final double[] lower = { -1e6 }; final double[] upper = { 0.5 }; final double[] result = optimizer.optimize(10000, fitnessFunction, GoalType.MINIMIZE, start, lower, upper).getPoint(); Assert.assertTrue("Out of bounds (" + result[0] + " > " + upper[0] + ")", result[0] <= upper[0]); } /** * Cf. MATH-865 */ @Test(expected=NumberIsTooLargeException.class) public void testBoundaryRangeTooLarge() { final CMAESOptimizer optimizer = new CMAESOptimizer(); final MultivariateFunction fitnessFunction = new MultivariateFunction() { public double value(double[] parameters) { if (Double.isNaN(parameters[0])) { throw new MathIllegalStateException(); } final double target = 1; final double error = target - parameters[0]; return error * error; } }; final double[] start = { 0 }; // The difference between upper and lower bounds is used to used // normalize the variables: In case of overflow, NaN is produced. final double max = Double.MAX_VALUE / 2; final double tooLarge = FastMath.nextUp(max); final double[] lower = { -tooLarge }; final double[] upper = { tooLarge }; final double[] result = optimizer.optimize(10000, fitnessFunction, GoalType.MINIMIZE, start, lower, upper).getPoint(); } /** * @param func Function to optimize. * @param startPoint Starting point. * @param inSigma Individual input sigma. * @param boundaries Upper / lower point limit. * @param goal Minimization or maximization. * @param lambda Population size used for offspring. * @param isActive Covariance update mechanism. * @param diagonalOnly Simplified covariance update. * @param stopValue Termination criteria for optimization. * @param fTol Tolerance relative error on the objective function. * @param pointTol Tolerance for checking that the optimum is correct. * @param maxEvaluations Maximum number of evaluations. * @param expected Expected point / value. */ private void doTest(MultivariateFunction func, double[] startPoint, double[] inSigma, double[][] boundaries, GoalType goal, int lambda, boolean isActive, int diagonalOnly, double stopValue, double fTol, double pointTol, int maxEvaluations, PointValuePair expected) { int dim = startPoint.length; // test diagonalOnly = 0 - slow but normally fewer feval# CMAESOptimizer optim = new CMAESOptimizer( lambda, inSigma, 30000, stopValue, isActive, diagonalOnly, 0, new MersenneTwister(), false); final double[] lB = boundaries == null ? null : boundaries[0]; final double[] uB = boundaries == null ? null : boundaries[1]; PointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); Assert.assertEquals(expected.getValue(), result.getValue(), fTol); for (int i = 0; i < dim; i++) { Assert.assertEquals(expected.getPoint()[i], result.getPoint()[i], pointTol); } } private static double[] point(int n, double value) { double[] ds = new double[n]; Arrays.fill(ds, value); return ds; } private static double[][] boundaries(int dim, double lower, double upper) { double[][] boundaries = new double[2][dim]; for (int i = 0; i < dim; i++) boundaries[0][i] = lower; for (int i = 0; i < dim; i++) boundaries[1][i] = upper; return boundaries; } private static class Sphere implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class Cigar implements MultivariateFunction { private double factor; Cigar() { this(1e3); } Cigar(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += factor * x[i] * x[i]; return f; } } private static class Tablet implements MultivariateFunction { private double factor; Tablet() { this(1e3); } Tablet(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = factor * x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class CigTab implements MultivariateFunction { private double factor; CigTab() { this(1e4); } CigTab(double axisratio) { factor = axisratio; } public double value(double[] x) { int end = x.length - 1; double f = x[0] * x[0] / factor + factor * x[end] * x[end]; for (int i = 1; i < end; ++i) f += x[i] * x[i]; return f; } } private static class TwoAxes implements MultivariateFunction { private double factor; TwoAxes() { this(1e6); } TwoAxes(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += (i < x.length / 2 ? factor : 1) * x[i] * x[i]; return f; } } private static class ElliRotated implements MultivariateFunction { private Basis B = new Basis(); private double factor; ElliRotated() { this(1e3); } ElliRotated(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; x = B.Rotate(x); for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class Elli implements MultivariateFunction { private double factor; Elli() { this(1e3); } Elli(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class MinusElli implements MultivariateFunction { public double value(double[] x) { return 1.0-(new Elli().value(x)); } } private static class DiffPow implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(Math.abs(x[i]), 2. + 10 * (double) i / (x.length - 1.)); return f; } } private static class SsDiffPow implements MultivariateFunction { public double value(double[] x) { double f = Math.pow(new DiffPow().value(x), 0.25); return f; } } private static class Rosen implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length - 1; ++i) f += 1e2 * (x[i] * x[i] - x[i + 1]) * (x[i] * x[i] - x[i + 1]) + (x[i] - 1.) * (x[i] - 1.); return f; } } private static class Ackley implements MultivariateFunction { private double axisratio; Ackley(double axra) { axisratio = axra; } public Ackley() { this(1); } public double value(double[] x) { double f = 0; double res2 = 0; double fac = 0; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); f += fac * fac * x[i] * x[i]; res2 += Math.cos(2. * Math.PI * fac * x[i]); } f = (20. - 20. * Math.exp(-0.2 * Math.sqrt(f / x.length)) + Math.exp(1.) - Math.exp(res2 / x.length)); return f; } } private static class Rastrigin implements MultivariateFunction { private double axisratio; private double amplitude; Rastrigin() { this(1, 10); } Rastrigin(double axisratio, double amplitude) { this.axisratio = axisratio; this.amplitude = amplitude; } public double value(double[] x) { double f = 0; double fac; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); if (i == 0 && x[i] < 0) fac *= 1.; f += fac * fac * x[i] * x[i] + amplitude * (1. - Math.cos(2. * Math.PI * fac * x[i])); } return f; } } private static class Basis { double[][] basis; Random rand = new Random(2); // use not always the same basis double[] Rotate(double[] x) { GenBasis(x.length); double[] y = new double[x.length]; for (int i = 0; i < x.length; ++i) { y[i] = 0; for (int j = 0; j < x.length; ++j) y[i] += basis[i][j] * x[j]; } return y; } void GenBasis(int DIM) { if (basis != null ? basis.length == DIM : false) return; double sp; int i, j, k; /* generate orthogonal basis */ basis = new double[DIM][DIM]; for (i = 0; i < DIM; ++i) { /* sample components gaussian */ for (j = 0; j < DIM; ++j) basis[i][j] = rand.nextGaussian(); /* substract projection of previous vectors */ for (j = i - 1; j >= 0; --j) { for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[j][k]; /* scalar product */ for (k = 0; k < DIM; ++k) basis[i][k] -= sp * basis[j][k]; /* substract */ } /* normalize */ for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[i][k]; /* squared norm */ for (k = 0; k < DIM; ++k) basis[i][k] /= Math.sqrt(sp); } } } }
// You are a professional Java test case writer, please create a test case named `testBoundaryRangeTooLarge` for the issue `Math-MATH-865`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-865 // // ## Issue-Title: // Wide bounds to CMAESOptimizer result in NaN parameters passed to fitness function // // ## Issue-Description: // // If you give large values as lower/upper bounds (for example -Double.MAX\_VALUE as a lower bound), the optimizer can call the fitness function with parameters set to NaN. My guess is this is due to FitnessFunction.encode/decode generating NaN when normalizing/denormalizing parameters. For example, if the difference between the lower and upper bound is greater than Double.MAX\_VALUE, encode could divide infinity by infinity. // // // // // @Test(expected=NumberIsTooLargeException.class) public void testBoundaryRangeTooLarge() {
431
/** * Cf. MATH-865 */
19
407
src/test/java/org/apache/commons/math3/optimization/direct/CMAESOptimizerTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-865 ## Issue-Title: Wide bounds to CMAESOptimizer result in NaN parameters passed to fitness function ## Issue-Description: If you give large values as lower/upper bounds (for example -Double.MAX\_VALUE as a lower bound), the optimizer can call the fitness function with parameters set to NaN. My guess is this is due to FitnessFunction.encode/decode generating NaN when normalizing/denormalizing parameters. For example, if the difference between the lower and upper bound is greater than Double.MAX\_VALUE, encode could divide infinity by infinity. ``` You are a professional Java test case writer, please create a test case named `testBoundaryRangeTooLarge` for the issue `Math-MATH-865`, utilizing the provided issue report information and the following function signature. ```java @Test(expected=NumberIsTooLargeException.class) public void testBoundaryRangeTooLarge() { ```
407
[ "org.apache.commons.math3.optimization.direct.CMAESOptimizer" ]
1b6a56c7454019a3520d75cd976c3f3cf577c479632964a6d106ca6532ddb021
@Test(expected=NumberIsTooLargeException.class) public void testBoundaryRangeTooLarge()
// You are a professional Java test case writer, please create a test case named `testBoundaryRangeTooLarge` for the issue `Math-MATH-865`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-865 // // ## Issue-Title: // Wide bounds to CMAESOptimizer result in NaN parameters passed to fitness function // // ## Issue-Description: // // If you give large values as lower/upper bounds (for example -Double.MAX\_VALUE as a lower bound), the optimizer can call the fitness function with parameters set to NaN. My guess is this is due to FitnessFunction.encode/decode generating NaN when normalizing/denormalizing parameters. For example, if the difference between the lower and upper bound is greater than Double.MAX\_VALUE, encode could divide infinity by infinity. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.optimization.direct; import java.util.Arrays; import java.util.Random; import org.apache.commons.math3.Retry; import org.apache.commons.math3.RetryRunner; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.optimization.PointValuePair; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test for {@link CMAESOptimizer}. */ @RunWith(RetryRunner.class) public class CMAESOptimizerTest { static final int DIM = 13; static final int LAMBDA = 4 + (int)(3.*Math.log(DIM)); @Test(expected = NumberIsTooLargeException.class) public void testInitOutofbounds1() { double[] startPoint = point(DIM,3); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = NumberIsTooSmallException.class) public void testInitOutofbounds2() { double[] startPoint = point(DIM, -2); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = DimensionMismatchException.class) public void testBoundariesDimensionMismatch() { double[] startPoint = point(DIM,0.5); double[] insigma = null; double[][] boundaries = boundaries(DIM+1,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = MathUnsupportedOperationException.class) public void testUnsupportedBoundaries1() { double[] startPoint = point(DIM,0.5); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1, Double.POSITIVE_INFINITY); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = MathUnsupportedOperationException.class) public void testUnsupportedBoundaries2() { double[] startPoint = point(DIM, 0.5); double[] insigma = null; final double[] lB = new double[] { -1, -1, -1, -1, -1, Double.NEGATIVE_INFINITY, -1, -1, -1, -1, -1, -1, -1 }; final double[] uB = new double[] { 2, 2, 2, Double.POSITIVE_INFINITY, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; double[][] boundaries = new double[2][]; boundaries[0] = lB; boundaries[1] = uB; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = NotPositiveException.class) public void testInputSigmaNegative() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM,-0.5); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = OutOfRangeException.class) public void testInputSigmaOutOfRange() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM, 1.1); double[][] boundaries = boundaries(DIM,-0.5,0.5); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = DimensionMismatchException.class) public void testInputSigmaDimensionMismatch() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM+1,-0.5); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test @Retry(3) public void testRosen() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test @Retry(3) public void testMaximize() {} // Defects4J: flaky method // public void testMaximize() { // double[] startPoint = point(DIM,1.0); // double[] insigma = point(DIM,0.1); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,0.0),1.0); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, true, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, false, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // boundaries = boundaries(DIM,-0.3,0.3); // startPoint = point(DIM,0.1); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, true, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // } @Test public void testEllipse() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Elli(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Elli(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testElliRotated() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new ElliRotated(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new ElliRotated(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testCigar() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Cigar(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new Cigar(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testTwoAxes() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new TwoAxes(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new TwoAxes(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-8, 1e-3, 200000, expected); } @Test public void testCigTab() {} // Defects4J: flaky method // @Test // public void testCigTab() { // double[] startPoint = point(DIM,1.0); // double[] insigma = point(DIM,0.3); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,0.0),0.0); // doTest(new CigTab(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, // 1e-13, 5e-5, 100000, expected); // doTest(new CigTab(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, // 1e-13, 5e-5, 100000, expected); // } @Test public void testSphere() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Sphere(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Sphere(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testTablet() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Tablet(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Tablet(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testDiffPow() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new DiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, true, 0, 1e-13, 1e-8, 1e-1, 100000, expected); doTest(new DiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, false, 0, 1e-13, 1e-8, 2e-1, 100000, expected); } @Test public void testSsDiffPow() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new SsDiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, true, 0, 1e-13, 1e-4, 1e-1, 200000, expected); doTest(new SsDiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, false, 0, 1e-13, 1e-4, 1e-1, 200000, expected); } @Test public void testAckley() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,1.0); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Ackley(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-9, 1e-5, 100000, expected); doTest(new Ackley(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-9, 1e-5, 100000, expected); } @Test public void testRastrigin() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Rastrigin(), startPoint, insigma, boundaries, GoalType.MINIMIZE, (int)(200*Math.sqrt(DIM)), true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new Rastrigin(), startPoint, insigma, boundaries, GoalType.MINIMIZE, (int)(200*Math.sqrt(DIM)), false, 0, 1e-13, 1e-13, 1e-6, 200000, expected); } @Test public void testConstrainedRosen() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testDiagonalRosen() {} // Defects4J: flaky method // @Test // public void testDiagonalRosen() { // double[] startPoint = point(DIM,0.1); // double[] insigma = point(DIM,0.1); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,1.0),0.0); // doTest(new Rosen(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, false, 1, 1e-13, // 1e-10, 1e-4, 1000000, expected); // } @Test public void testMath864() { final CMAESOptimizer optimizer = new CMAESOptimizer(); final MultivariateFunction fitnessFunction = new MultivariateFunction() { public double value(double[] parameters) { final double target = 1; final double error = target - parameters[0]; return error * error; } }; final double[] start = { 0 }; final double[] lower = { -1e6 }; final double[] upper = { 0.5 }; final double[] result = optimizer.optimize(10000, fitnessFunction, GoalType.MINIMIZE, start, lower, upper).getPoint(); Assert.assertTrue("Out of bounds (" + result[0] + " > " + upper[0] + ")", result[0] <= upper[0]); } /** * Cf. MATH-865 */ @Test(expected=NumberIsTooLargeException.class) public void testBoundaryRangeTooLarge() { final CMAESOptimizer optimizer = new CMAESOptimizer(); final MultivariateFunction fitnessFunction = new MultivariateFunction() { public double value(double[] parameters) { if (Double.isNaN(parameters[0])) { throw new MathIllegalStateException(); } final double target = 1; final double error = target - parameters[0]; return error * error; } }; final double[] start = { 0 }; // The difference between upper and lower bounds is used to used // normalize the variables: In case of overflow, NaN is produced. final double max = Double.MAX_VALUE / 2; final double tooLarge = FastMath.nextUp(max); final double[] lower = { -tooLarge }; final double[] upper = { tooLarge }; final double[] result = optimizer.optimize(10000, fitnessFunction, GoalType.MINIMIZE, start, lower, upper).getPoint(); } /** * @param func Function to optimize. * @param startPoint Starting point. * @param inSigma Individual input sigma. * @param boundaries Upper / lower point limit. * @param goal Minimization or maximization. * @param lambda Population size used for offspring. * @param isActive Covariance update mechanism. * @param diagonalOnly Simplified covariance update. * @param stopValue Termination criteria for optimization. * @param fTol Tolerance relative error on the objective function. * @param pointTol Tolerance for checking that the optimum is correct. * @param maxEvaluations Maximum number of evaluations. * @param expected Expected point / value. */ private void doTest(MultivariateFunction func, double[] startPoint, double[] inSigma, double[][] boundaries, GoalType goal, int lambda, boolean isActive, int diagonalOnly, double stopValue, double fTol, double pointTol, int maxEvaluations, PointValuePair expected) { int dim = startPoint.length; // test diagonalOnly = 0 - slow but normally fewer feval# CMAESOptimizer optim = new CMAESOptimizer( lambda, inSigma, 30000, stopValue, isActive, diagonalOnly, 0, new MersenneTwister(), false); final double[] lB = boundaries == null ? null : boundaries[0]; final double[] uB = boundaries == null ? null : boundaries[1]; PointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); Assert.assertEquals(expected.getValue(), result.getValue(), fTol); for (int i = 0; i < dim; i++) { Assert.assertEquals(expected.getPoint()[i], result.getPoint()[i], pointTol); } } private static double[] point(int n, double value) { double[] ds = new double[n]; Arrays.fill(ds, value); return ds; } private static double[][] boundaries(int dim, double lower, double upper) { double[][] boundaries = new double[2][dim]; for (int i = 0; i < dim; i++) boundaries[0][i] = lower; for (int i = 0; i < dim; i++) boundaries[1][i] = upper; return boundaries; } private static class Sphere implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class Cigar implements MultivariateFunction { private double factor; Cigar() { this(1e3); } Cigar(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += factor * x[i] * x[i]; return f; } } private static class Tablet implements MultivariateFunction { private double factor; Tablet() { this(1e3); } Tablet(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = factor * x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class CigTab implements MultivariateFunction { private double factor; CigTab() { this(1e4); } CigTab(double axisratio) { factor = axisratio; } public double value(double[] x) { int end = x.length - 1; double f = x[0] * x[0] / factor + factor * x[end] * x[end]; for (int i = 1; i < end; ++i) f += x[i] * x[i]; return f; } } private static class TwoAxes implements MultivariateFunction { private double factor; TwoAxes() { this(1e6); } TwoAxes(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += (i < x.length / 2 ? factor : 1) * x[i] * x[i]; return f; } } private static class ElliRotated implements MultivariateFunction { private Basis B = new Basis(); private double factor; ElliRotated() { this(1e3); } ElliRotated(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; x = B.Rotate(x); for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class Elli implements MultivariateFunction { private double factor; Elli() { this(1e3); } Elli(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class MinusElli implements MultivariateFunction { public double value(double[] x) { return 1.0-(new Elli().value(x)); } } private static class DiffPow implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(Math.abs(x[i]), 2. + 10 * (double) i / (x.length - 1.)); return f; } } private static class SsDiffPow implements MultivariateFunction { public double value(double[] x) { double f = Math.pow(new DiffPow().value(x), 0.25); return f; } } private static class Rosen implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length - 1; ++i) f += 1e2 * (x[i] * x[i] - x[i + 1]) * (x[i] * x[i] - x[i + 1]) + (x[i] - 1.) * (x[i] - 1.); return f; } } private static class Ackley implements MultivariateFunction { private double axisratio; Ackley(double axra) { axisratio = axra; } public Ackley() { this(1); } public double value(double[] x) { double f = 0; double res2 = 0; double fac = 0; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); f += fac * fac * x[i] * x[i]; res2 += Math.cos(2. * Math.PI * fac * x[i]); } f = (20. - 20. * Math.exp(-0.2 * Math.sqrt(f / x.length)) + Math.exp(1.) - Math.exp(res2 / x.length)); return f; } } private static class Rastrigin implements MultivariateFunction { private double axisratio; private double amplitude; Rastrigin() { this(1, 10); } Rastrigin(double axisratio, double amplitude) { this.axisratio = axisratio; this.amplitude = amplitude; } public double value(double[] x) { double f = 0; double fac; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); if (i == 0 && x[i] < 0) fac *= 1.; f += fac * fac * x[i] * x[i] + amplitude * (1. - Math.cos(2. * Math.PI * fac * x[i])); } return f; } } private static class Basis { double[][] basis; Random rand = new Random(2); // use not always the same basis double[] Rotate(double[] x) { GenBasis(x.length); double[] y = new double[x.length]; for (int i = 0; i < x.length; ++i) { y[i] = 0; for (int j = 0; j < x.length; ++j) y[i] += basis[i][j] * x[j]; } return y; } void GenBasis(int DIM) { if (basis != null ? basis.length == DIM : false) return; double sp; int i, j, k; /* generate orthogonal basis */ basis = new double[DIM][DIM]; for (i = 0; i < DIM; ++i) { /* sample components gaussian */ for (j = 0; j < DIM; ++j) basis[i][j] = rand.nextGaussian(); /* substract projection of previous vectors */ for (j = i - 1; j >= 0; --j) { for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[j][k]; /* scalar product */ for (k = 0; k < DIM; ++k) basis[i][k] -= sp * basis[j][k]; /* substract */ } /* normalize */ for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[i][k]; /* squared norm */ for (k = 0; k < DIM; ++k) basis[i][k] /= Math.sqrt(sp); } } } }
public void testEmptyNodeSetOperations() { assertXPathValue(context, "/idonotexist = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist != 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist >= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist <= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] != 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] >= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] <= 0", Boolean.FALSE, Boolean.class); }
org.apache.commons.jxpath.ri.compiler.CoreOperationTest::testEmptyNodeSetOperations
src/test/org/apache/commons/jxpath/ri/compiler/CoreOperationTest.java
127
src/test/org/apache/commons/jxpath/ri/compiler/CoreOperationTest.java
testEmptyNodeSetOperations
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jxpath.ri.compiler; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathTestCase; import org.apache.commons.jxpath.Variables; /** * Test basic functionality of JXPath - infoset types, * operations. * * @author Dmitri Plotnikov * @version $Revision$ $Date$ */ public class CoreOperationTest extends JXPathTestCase { private JXPathContext context; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public CoreOperationTest(String name) { super(name); } public void setUp() { if (context == null) { context = JXPathContext.newContext(null); Variables vars = context.getVariables(); vars.declareVariable("integer", new Integer(1)); vars.declareVariable("array", new double[] { 0.25, 0.5, 0.75 }); vars.declareVariable("nan", new Double(Double.NaN)); } } public void testInfoSetTypes() { // Numbers assertXPathValue(context, "1", new Double(1.0)); assertXPathPointer(context, "1", "1"); assertXPathValueIterator(context, "1", list(new Double(1.0))); assertXPathPointerIterator(context, "1", list("1")); assertXPathValue(context, "-1", new Double(-1.0)); assertXPathValue(context, "2 + 2", new Double(4.0)); assertXPathValue(context, "3 - 2", new Double(1.0)); assertXPathValue(context, "1 + 2 + 3 - 4 + 5", new Double(7.0)); assertXPathValue(context, "3 * 2", new Double(3.0 * 2.0)); assertXPathValue(context, "3 div 2", new Double(3.0 / 2.0)); assertXPathValue(context, "5 mod 2", new Double(1.0)); // This test produces a different result with Xalan? assertXPathValue(context, "5.9 mod 2.1", new Double(1.0)); assertXPathValue(context, "5 mod -2", new Double(1.0)); assertXPathValue(context, "-5 mod 2", new Double(-1.0)); assertXPathValue(context, "-5 mod -2", new Double(-1.0)); assertXPathValue(context, "1 < 2", Boolean.TRUE); assertXPathValue(context, "1 > 2", Boolean.FALSE); assertXPathValue(context, "1 <= 1", Boolean.TRUE); assertXPathValue(context, "1 >= 2", Boolean.FALSE); assertXPathValue(context, "3 > 2 > 1", Boolean.FALSE); assertXPathValue(context, "3 > 2 and 2 > 1", Boolean.TRUE); assertXPathValue(context, "3 > 2 and 2 < 1", Boolean.FALSE); assertXPathValue(context, "3 < 2 or 2 > 1", Boolean.TRUE); assertXPathValue(context, "3 < 2 or 2 < 1", Boolean.FALSE); assertXPathValue(context, "1 = 1", Boolean.TRUE); assertXPathValue(context, "1 = '1'", Boolean.TRUE); assertXPathValue(context, "1 > 2 = 2 > 3", Boolean.TRUE); assertXPathValue(context, "1 > 2 = 0", Boolean.TRUE); assertXPathValue(context, "1 = 2", Boolean.FALSE); assertXPathValue(context, "$integer", new Double(1), Double.class); assertXPathValue(context, "2 + 3", "5.0", String.class); assertXPathValue(context, "2 + 3", Boolean.TRUE, boolean.class); assertXPathValue(context, "'true'", Boolean.TRUE, Boolean.class); } public void testNodeSetOperations() { assertXPathValue(context, "$array > 0", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array >= 0", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array = 0.25", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.5", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.50000", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.75", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array < 1", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array <= 1", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array < 0", Boolean.FALSE, Boolean.class); } public void testEmptyNodeSetOperations() { assertXPathValue(context, "/idonotexist = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist != 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist >= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist <= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] != 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] >= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] <= 0", Boolean.FALSE, Boolean.class); } public void testNan() { assertXPathValue(context, "$nan > $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan <= $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= $nan and $nan <= $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan != $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan <= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= 0 and $nan <= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan != 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan <= 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= 1 and $nan <= 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan != 1", Boolean.FALSE, Boolean.class); } }
// You are a professional Java test case writer, please create a test case named `testEmptyNodeSetOperations` for the issue `JxPath-JXPATH-93`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JxPath-JXPATH-93 // // ## Issue-Title: // Binary operators behaviour involving node-sets is incorrect // // ## Issue-Description: // // According to XPath specification: // // "If both objects to be compared are node-sets, then the comparison will be true if and only if there is a node in the first node-set and a node in the second node-set such that the result of performing the comparison on the string-values of the two nodes is true. If one object to be compared is a node-set and the other is a number, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the number to be compared and on the result of converting the string-value of that node to a number using the number function is true." // // // But following example illustrates, that this is not a JXPath behaviour: // // // JXPathContext pathContext = JXPathContext // // .newContext(DocumentBuilderFactory.newInstance() // // .newDocumentBuilder().parse( // // new InputSource(new StringReader( // // "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" // // + "<doc/>")))); // // Boolean result = (Boolean) pathContext.getValue("2.0 > child1", // // Boolean.class); // // assertFalse(result.booleanValue()); // // // "child1" is not found - right operand node set is empty, but result is TRUE, instead of FALSE. // // // Please, check greaterThan(), lesserThan(), etc methods of org.apache.xpath.objects.XObject for possible solution ![](/jira/images/icons/emoticons/smile.png) // // // // // public void testEmptyNodeSetOperations() {
127
10
114
src/test/org/apache/commons/jxpath/ri/compiler/CoreOperationTest.java
src/test
```markdown ## Issue-ID: JxPath-JXPATH-93 ## Issue-Title: Binary operators behaviour involving node-sets is incorrect ## Issue-Description: According to XPath specification: "If both objects to be compared are node-sets, then the comparison will be true if and only if there is a node in the first node-set and a node in the second node-set such that the result of performing the comparison on the string-values of the two nodes is true. If one object to be compared is a node-set and the other is a number, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the number to be compared and on the result of converting the string-value of that node to a number using the number function is true." But following example illustrates, that this is not a JXPath behaviour: JXPathContext pathContext = JXPathContext .newContext(DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse( new InputSource(new StringReader( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + "<doc/>")))); Boolean result = (Boolean) pathContext.getValue("2.0 > child1", Boolean.class); assertFalse(result.booleanValue()); "child1" is not found - right operand node set is empty, but result is TRUE, instead of FALSE. Please, check greaterThan(), lesserThan(), etc methods of org.apache.xpath.objects.XObject for possible solution ![](/jira/images/icons/emoticons/smile.png) ``` You are a professional Java test case writer, please create a test case named `testEmptyNodeSetOperations` for the issue `JxPath-JXPATH-93`, utilizing the provided issue report information and the following function signature. ```java public void testEmptyNodeSetOperations() { ```
114
[ "org.apache.commons.jxpath.ri.compiler.CoreOperationRelationalExpression" ]
1ba5768921cc37e5f1537562cb80b66637d038c9dc16621317051effd33bbf8f
public void testEmptyNodeSetOperations()
// You are a professional Java test case writer, please create a test case named `testEmptyNodeSetOperations` for the issue `JxPath-JXPATH-93`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JxPath-JXPATH-93 // // ## Issue-Title: // Binary operators behaviour involving node-sets is incorrect // // ## Issue-Description: // // According to XPath specification: // // "If both objects to be compared are node-sets, then the comparison will be true if and only if there is a node in the first node-set and a node in the second node-set such that the result of performing the comparison on the string-values of the two nodes is true. If one object to be compared is a node-set and the other is a number, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the number to be compared and on the result of converting the string-value of that node to a number using the number function is true." // // // But following example illustrates, that this is not a JXPath behaviour: // // // JXPathContext pathContext = JXPathContext // // .newContext(DocumentBuilderFactory.newInstance() // // .newDocumentBuilder().parse( // // new InputSource(new StringReader( // // "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" // // + "<doc/>")))); // // Boolean result = (Boolean) pathContext.getValue("2.0 > child1", // // Boolean.class); // // assertFalse(result.booleanValue()); // // // "child1" is not found - right operand node set is empty, but result is TRUE, instead of FALSE. // // // Please, check greaterThan(), lesserThan(), etc methods of org.apache.xpath.objects.XObject for possible solution ![](/jira/images/icons/emoticons/smile.png) // // // // //
JxPath
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jxpath.ri.compiler; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathTestCase; import org.apache.commons.jxpath.Variables; /** * Test basic functionality of JXPath - infoset types, * operations. * * @author Dmitri Plotnikov * @version $Revision$ $Date$ */ public class CoreOperationTest extends JXPathTestCase { private JXPathContext context; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public CoreOperationTest(String name) { super(name); } public void setUp() { if (context == null) { context = JXPathContext.newContext(null); Variables vars = context.getVariables(); vars.declareVariable("integer", new Integer(1)); vars.declareVariable("array", new double[] { 0.25, 0.5, 0.75 }); vars.declareVariable("nan", new Double(Double.NaN)); } } public void testInfoSetTypes() { // Numbers assertXPathValue(context, "1", new Double(1.0)); assertXPathPointer(context, "1", "1"); assertXPathValueIterator(context, "1", list(new Double(1.0))); assertXPathPointerIterator(context, "1", list("1")); assertXPathValue(context, "-1", new Double(-1.0)); assertXPathValue(context, "2 + 2", new Double(4.0)); assertXPathValue(context, "3 - 2", new Double(1.0)); assertXPathValue(context, "1 + 2 + 3 - 4 + 5", new Double(7.0)); assertXPathValue(context, "3 * 2", new Double(3.0 * 2.0)); assertXPathValue(context, "3 div 2", new Double(3.0 / 2.0)); assertXPathValue(context, "5 mod 2", new Double(1.0)); // This test produces a different result with Xalan? assertXPathValue(context, "5.9 mod 2.1", new Double(1.0)); assertXPathValue(context, "5 mod -2", new Double(1.0)); assertXPathValue(context, "-5 mod 2", new Double(-1.0)); assertXPathValue(context, "-5 mod -2", new Double(-1.0)); assertXPathValue(context, "1 < 2", Boolean.TRUE); assertXPathValue(context, "1 > 2", Boolean.FALSE); assertXPathValue(context, "1 <= 1", Boolean.TRUE); assertXPathValue(context, "1 >= 2", Boolean.FALSE); assertXPathValue(context, "3 > 2 > 1", Boolean.FALSE); assertXPathValue(context, "3 > 2 and 2 > 1", Boolean.TRUE); assertXPathValue(context, "3 > 2 and 2 < 1", Boolean.FALSE); assertXPathValue(context, "3 < 2 or 2 > 1", Boolean.TRUE); assertXPathValue(context, "3 < 2 or 2 < 1", Boolean.FALSE); assertXPathValue(context, "1 = 1", Boolean.TRUE); assertXPathValue(context, "1 = '1'", Boolean.TRUE); assertXPathValue(context, "1 > 2 = 2 > 3", Boolean.TRUE); assertXPathValue(context, "1 > 2 = 0", Boolean.TRUE); assertXPathValue(context, "1 = 2", Boolean.FALSE); assertXPathValue(context, "$integer", new Double(1), Double.class); assertXPathValue(context, "2 + 3", "5.0", String.class); assertXPathValue(context, "2 + 3", Boolean.TRUE, boolean.class); assertXPathValue(context, "'true'", Boolean.TRUE, Boolean.class); } public void testNodeSetOperations() { assertXPathValue(context, "$array > 0", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array >= 0", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array = 0.25", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.5", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.50000", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.75", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array < 1", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array <= 1", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array < 0", Boolean.FALSE, Boolean.class); } public void testEmptyNodeSetOperations() { assertXPathValue(context, "/idonotexist = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist != 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist >= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "/idonotexist <= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] != 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] >= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array[position() < 1] <= 0", Boolean.FALSE, Boolean.class); } public void testNan() { assertXPathValue(context, "$nan > $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan <= $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= $nan and $nan <= $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan != $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan <= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= 0 and $nan <= 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan != 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan <= 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan >= 1 and $nan <= 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan != 1", Boolean.FALSE, Boolean.class); } }
public void testCanonicalNames() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(java.util.Calendar.class); String can = t.toCanonical(); assertEquals("java.util.Calendar", can); assertEquals(t, tf.constructFromCanonical(can)); // Generic maps and collections will default to Object.class if type-erased t = tf.constructType(java.util.ArrayList.class); can = t.toCanonical(); assertEquals("java.util.ArrayList<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); t = tf.constructType(java.util.TreeMap.class); can = t.toCanonical(); assertEquals("java.util.TreeMap<java.lang.Object,java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); // And then EnumMap (actual use case for us) t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class); can = t.toCanonical(); assertEquals("java.util.EnumMap<com.fasterxml.jackson.databind.type.TestTypeFactory$EnumForCanonical,java.lang.String>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#2109]: also ReferenceTypes t = tf.constructType(new TypeReference<AtomicReference<Long>>() { }); can = t.toCanonical(); assertEquals("java.util.concurrent.atomic.AtomicReference<java.lang.Long>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#1941]: allow "raw" types too t = tf.constructFromCanonical("java.util.List"); assertEquals(List.class, t.getRawClass()); assertEquals(CollectionType.class, t.getClass()); // 01-Mar-2018, tatu: not 100% should we expect type parameters here... // But currently we do NOT get any /* assertEquals(1, t.containedTypeCount()); assertEquals(Object.class, t.containedType(0).getRawClass()); */ assertEquals(Object.class, t.getContentType().getRawClass()); can = t.toCanonical(); assertEquals("java.util.List<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); }
com.fasterxml.jackson.databind.type.TestTypeFactory::testCanonicalNames
src/test/java/com/fasterxml/jackson/databind/type/TestTypeFactory.java
255
src/test/java/com/fasterxml/jackson/databind/type/TestTypeFactory.java
testCanonicalNames
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; /** * Simple tests to verify that the {@link TypeFactory} constructs * type information as expected. */ public class TestTypeFactory extends BaseMapTest { /* /********************************************************** /* Helper types /********************************************************** */ enum EnumForCanonical { YES, NO; } static class SingleArgGeneric<X> { } abstract static class MyMap extends IntermediateMap<String,Long> { } abstract static class IntermediateMap<K,V> implements Map<K,V> { } abstract static class MyList extends IntermediateList<Long> { } abstract static class IntermediateList<E> implements List<E> { } @SuppressWarnings("serial") static class GenericList<T> extends ArrayList<T> { } interface MapInterface extends Cloneable, IntermediateInterfaceMap<String> { } interface IntermediateInterfaceMap<FOO> extends Map<FOO, Integer> { } @SuppressWarnings("serial") static class MyStringIntMap extends MyStringXMap<Integer> { } @SuppressWarnings("serial") static class MyStringXMap<V> extends HashMap<String,V> { } // And one more, now with obfuscated type names; essentially it's just Map<Int,Long> static abstract class IntLongMap extends XLongMap<Integer> { } // trick here is that V now refers to key type, not value type static abstract class XLongMap<V> extends XXMap<V,Long> { } static abstract class XXMap<K,V> implements Map<K,V> { } static class SneakyBean { public IntLongMap intMap; public MyList longList; } static class SneakyBean2 { // self-reference; should be resolved as "Comparable<Object>" public <T extends Comparable<T>> T getFoobar() { return null; } } @SuppressWarnings("serial") public static class LongValuedMap<K> extends HashMap<K, Long> { } static class StringLongMapBean { public LongValuedMap<String> value; } static class StringListBean { public GenericList<String> value; } static class CollectionLike<E> { } static class MapLike<K,V> { } static class Wrapper1297<T> { public T content; } /* /********************************************************** /* Unit tests /********************************************************** */ public void testSimpleTypes() { Class<?>[] classes = new Class<?>[] { boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class, Boolean.class, Byte.class, Character.class, Short.class, Integer.class, Long.class, Float.class, Double.class, String.class, Object.class, Calendar.class, Date.class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); assertSame(clz, tf.constructType(clz).getRawClass()); } } public void testArrays() { Class<?>[] classes = new Class<?>[] { boolean[].class, byte[].class, char[].class, short[].class, int[].class, long[].class, float[].class, double[].class, String[].class, Object[].class, Calendar[].class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); Class<?> elemType = clz.getComponentType(); assertSame(clz, tf.constructArrayType(elemType).getRawClass()); } } // [databind#810]: Fake Map type for Properties as <String,String> public void testProperties() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(Properties.class); assertEquals(MapType.class, t.getClass()); assertSame(Properties.class, t.getRawClass()); MapType mt = (MapType) t; // so far so good. But how about parameterization? assertSame(String.class, mt.getKeyType().getRawClass()); assertSame(String.class, mt.getContentType().getRawClass()); } public void testIterator() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(new TypeReference<Iterator<String>>() { }); assertEquals(SimpleType.class, t.getClass()); assertSame(Iterator.class, t.getRawClass()); assertEquals(1, t.containedTypeCount()); assertEquals(tf.constructType(String.class), t.containedType(0)); assertNull(t.containedType(1)); } /** * Test for verifying that parametric types can be constructed * programmatically */ @SuppressWarnings("deprecation") public void testParametricTypes() { TypeFactory tf = TypeFactory.defaultInstance(); // first, simple class based JavaType t = tf.constructParametrizedType(ArrayList.class, Collection.class, String.class); // ArrayList<String> assertEquals(CollectionType.class, t.getClass()); JavaType strC = tf.constructType(String.class); assertEquals(1, t.containedTypeCount()); assertEquals(strC, t.containedType(0)); assertNull(t.containedType(1)); // Then using JavaType JavaType t2 = tf.constructParametrizedType(Map.class, Map.class, strC, t); // Map<String,ArrayList<String>> // should actually produce a MapType assertEquals(MapType.class, t2.getClass()); assertEquals(2, t2.containedTypeCount()); assertEquals(strC, t2.containedType(0)); assertEquals(t, t2.containedType(1)); assertNull(t2.containedType(2)); // and then custom generic type as well JavaType custom = tf.constructParametrizedType(SingleArgGeneric.class, SingleArgGeneric.class, String.class); assertEquals(SimpleType.class, custom.getClass()); assertEquals(1, custom.containedTypeCount()); assertEquals(strC, custom.containedType(0)); assertNull(custom.containedType(1)); // should also be able to access variable name: assertEquals("X", custom.containedTypeName(0)); // And finally, ensure that we can't create invalid combinations try { // Maps must take 2 type parameters, not just one tf.constructParametrizedType(Map.class, Map.class, strC); } catch (IllegalArgumentException e) { verifyException(e, "Can not create TypeBindings for class java.util.Map"); } try { // Type only accepts one type param tf.constructParametrizedType(SingleArgGeneric.class, SingleArgGeneric.class, strC, strC); } catch (IllegalArgumentException e) { verifyException(e, "Can not create TypeBindings for class "); } } /** * Test for checking that canonical name handling works ok */ public void testCanonicalNames() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(java.util.Calendar.class); String can = t.toCanonical(); assertEquals("java.util.Calendar", can); assertEquals(t, tf.constructFromCanonical(can)); // Generic maps and collections will default to Object.class if type-erased t = tf.constructType(java.util.ArrayList.class); can = t.toCanonical(); assertEquals("java.util.ArrayList<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); t = tf.constructType(java.util.TreeMap.class); can = t.toCanonical(); assertEquals("java.util.TreeMap<java.lang.Object,java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); // And then EnumMap (actual use case for us) t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class); can = t.toCanonical(); assertEquals("java.util.EnumMap<com.fasterxml.jackson.databind.type.TestTypeFactory$EnumForCanonical,java.lang.String>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#2109]: also ReferenceTypes t = tf.constructType(new TypeReference<AtomicReference<Long>>() { }); can = t.toCanonical(); assertEquals("java.util.concurrent.atomic.AtomicReference<java.lang.Long>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#1941]: allow "raw" types too t = tf.constructFromCanonical("java.util.List"); assertEquals(List.class, t.getRawClass()); assertEquals(CollectionType.class, t.getClass()); // 01-Mar-2018, tatu: not 100% should we expect type parameters here... // But currently we do NOT get any /* assertEquals(1, t.containedTypeCount()); assertEquals(Object.class, t.containedType(0).getRawClass()); */ assertEquals(Object.class, t.getContentType().getRawClass()); can = t.toCanonical(); assertEquals("java.util.List<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); } // [databind#1768] @SuppressWarnings("serial") public void testCanonicalWithSpaces() { TypeFactory tf = TypeFactory.defaultInstance(); Object objects = new TreeMap<Object, Object>() { }; // to get subtype String reflectTypeName = objects.getClass().getGenericSuperclass().toString(); JavaType t1 = tf.constructType(objects.getClass().getGenericSuperclass()); // This will throw an Exception if you don't remove all white spaces from the String. JavaType t2 = tf.constructFromCanonical(reflectTypeName); assertNotNull(t2); assertEquals(t2, t1); } /* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */ public void testCollections() { // Ok, first: let's test what happens when we pass 'raw' Collection: TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(ArrayList.class); assertEquals(CollectionType.class, t.getClass()); assertSame(ArrayList.class, t.getRawClass()); // And then the proper way t = tf.constructType(new TypeReference<ArrayList<String>>() { }); assertEquals(CollectionType.class, t.getClass()); assertSame(ArrayList.class, t.getRawClass()); JavaType elemType = ((CollectionType) t).getContentType(); assertNotNull(elemType); assertSame(SimpleType.class, elemType.getClass()); assertSame(String.class, elemType.getRawClass()); // And alternate method too t = tf.constructCollectionType(ArrayList.class, String.class); assertEquals(CollectionType.class, t.getClass()); assertSame(String.class, ((CollectionType) t).getContentType().getRawClass()); } // since 2.7 public void testCollectionTypesRefined() { TypeFactory tf = newTypeFactory(); JavaType type = tf.constructType(new TypeReference<List<Long>>() { }); assertEquals(List.class, type.getRawClass()); assertEquals(Long.class, type.getContentType().getRawClass()); // No super-class, since it's an interface: assertNull(type.getSuperClass()); // But then refine to reflect sub-classing JavaType subtype = tf.constructSpecializedType(type, ArrayList.class); assertEquals(ArrayList.class, subtype.getRawClass()); assertEquals(Long.class, subtype.getContentType().getRawClass()); // but with refinement, should have non-null super class JavaType superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(AbstractList.class, superType.getRawClass()); } /* /********************************************************** /* Unit tests: map type parameter resolution /********************************************************** */ public void testMaps() { TypeFactory tf = newTypeFactory(); // Ok, first: let's test what happens when we pass 'raw' Map: JavaType t = tf.constructType(HashMap.class); assertEquals(MapType.class, t.getClass()); assertSame(HashMap.class, t.getRawClass()); // Then explicit construction t = tf.constructMapType(TreeMap.class, String.class, Integer.class); assertEquals(MapType.class, t.getClass()); assertSame(String.class, ((MapType) t).getKeyType().getRawClass()); assertSame(Integer.class, ((MapType) t).getContentType().getRawClass()); // And then with TypeReference t = tf.constructType(new TypeReference<HashMap<String,Integer>>() { }); assertEquals(MapType.class, t.getClass()); assertSame(HashMap.class, t.getRawClass()); MapType mt = (MapType) t; assertEquals(tf.constructType(String.class), mt.getKeyType()); assertEquals(tf.constructType(Integer.class), mt.getContentType()); t = tf.constructType(new TypeReference<LongValuedMap<Boolean>>() { }); assertEquals(MapType.class, t.getClass()); assertSame(LongValuedMap.class, t.getRawClass()); mt = (MapType) t; assertEquals(tf.constructType(Boolean.class), mt.getKeyType()); assertEquals(tf.constructType(Long.class), mt.getContentType()); JavaType type = tf.constructType(new TypeReference<Map<String,Boolean>>() { }); MapType mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Boolean.class), mapType.getContentType()); } // since 2.7 public void testMapTypesRefined() { TypeFactory tf = newTypeFactory(); JavaType type = tf.constructType(new TypeReference<Map<String,List<Integer>>>() { }); MapType mapType = (MapType) type; assertEquals(Map.class, mapType.getRawClass()); assertEquals(String.class, mapType.getKeyType().getRawClass()); assertEquals(List.class, mapType.getContentType().getRawClass()); assertEquals(Integer.class, mapType.getContentType().getContentType().getRawClass()); // No super-class, since it's an interface: assertNull(type.getSuperClass()); // But then refine to reflect sub-classing JavaType subtype = tf.constructSpecializedType(type, LinkedHashMap.class); assertEquals(LinkedHashMap.class, subtype.getRawClass()); assertEquals(String.class, subtype.getKeyType().getRawClass()); assertEquals(List.class, subtype.getContentType().getRawClass()); assertEquals(Integer.class, subtype.getContentType().getContentType().getRawClass()); // but with refinement, should have non-null super class // 20-Oct-2015, tatu: For now refinement does not faithfully replicate the // structure, it only retains most important information. Here it means // that actually existing super-classes are skipped, and only original // type is linked as expected JavaType superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(HashMap.class, superType.getRawClass()); // which also should have proper typing assertEquals(String.class, superType.getKeyType().getRawClass()); assertEquals(List.class, superType.getContentType().getRawClass()); assertEquals(Integer.class, superType.getContentType().getContentType().getRawClass()); } public void testMapTypesRaw() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(HashMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(Object.class), mapType.getKeyType()); assertEquals(tf.constructType(Object.class), mapType.getContentType()); } public void testMapTypesAdvanced() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(MyMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); type = tf.constructType(MapInterface.class); mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Integer.class), mapType.getContentType()); type = tf.constructType(MyStringIntMap.class); mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Integer.class), mapType.getContentType()); } /** * Specific test to verify that complicate name mangling schemes * do not fool type resolver */ public void testMapTypesSneaky() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(IntLongMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(Integer.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); } /** * Plus sneaky types may be found via introspection as well. */ public void testSneakyFieldTypes() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Field field = SneakyBean.class.getDeclaredField("intMap"); JavaType type = tf.constructType(field.getGenericType()); assertTrue(type instanceof MapType); MapType mapType = (MapType) type; assertEquals(tf.constructType(Integer.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); field = SneakyBean.class.getDeclaredField("longList"); type = tf.constructType(field.getGenericType()); assertTrue(type instanceof CollectionType); CollectionType collectionType = (CollectionType) type; assertEquals(tf.constructType(Long.class), collectionType.getContentType()); } /** * Looks like type handling actually differs for properties, too. */ public void testSneakyBeanProperties() throws Exception { ObjectMapper mapper = new ObjectMapper(); StringLongMapBean bean = mapper.readValue("{\"value\":{\"a\":123}}", StringLongMapBean.class); assertNotNull(bean); Map<String,Long> map = bean.value; assertEquals(1, map.size()); assertEquals(Long.valueOf(123), map.get("a")); StringListBean bean2 = mapper.readValue("{\"value\":[\"...\"]}", StringListBean.class); assertNotNull(bean2); List<String> list = bean2.value; assertSame(GenericList.class, list.getClass()); assertEquals(1, list.size()); assertEquals("...", list.get(0)); } public void testSneakySelfRefs() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(new SneakyBean2()); assertEquals("{\"foobar\":null}", json); } /* /********************************************************** /* Unit tests: handling of specific JDK types /********************************************************** */ public void testAtomicArrayRefParameters() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(new TypeReference<AtomicReference<long[]>>() { }); JavaType[] params = tf.findTypeParameters(type, AtomicReference.class); assertNotNull(params); assertEquals(1, params.length); assertEquals(tf.constructType(long[].class), params[0]); } static abstract class StringIntMapEntry implements Map.Entry<String,Integer> { } public void testMapEntryResolution() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(StringIntMapEntry.class); JavaType mapEntryType = t.findSuperType(Map.Entry.class); assertNotNull(mapEntryType); assertTrue(mapEntryType.hasGenericTypes()); assertEquals(2, mapEntryType.containedTypeCount()); assertEquals(String.class, mapEntryType.containedType(0).getRawClass()); assertEquals(Integer.class, mapEntryType.containedType(1).getRawClass()); } /* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */ public void testRawCollections() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawCollectionType(ArrayList.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawCollectionLikeType(CollectionLike.class); // must have type vars assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawCollectionLikeType(String.class); assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); } public void testRawMaps() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawMapType(HashMap.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawMapLikeType(MapLike.class); // must have type vars assertTrue(type.isMapLikeType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawMapLikeType(String.class); assertTrue(type.isMapLikeType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); } /* /********************************************************** /* Unit tests: other /********************************************************** */ public void testMoreSpecificType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t1 = tf.constructCollectionType(Collection.class, Object.class); JavaType t2 = tf.constructCollectionType(List.class, Object.class); assertSame(t2, tf.moreSpecificType(t1, t2)); assertSame(t2, tf.moreSpecificType(t2, t1)); t1 = tf.constructType(Double.class); t2 = tf.constructType(Number.class); assertSame(t1, tf.moreSpecificType(t1, t2)); assertSame(t1, tf.moreSpecificType(t2, t1)); // and then unrelated, return first t1 = tf.constructType(Double.class); t2 = tf.constructType(String.class); assertSame(t1, tf.moreSpecificType(t1, t2)); assertSame(t2, tf.moreSpecificType(t2, t1)); } // [databind#489] public void testCacheClearing() { TypeFactory tf = TypeFactory.defaultInstance().withModifier(null); assertEquals(0, tf._typeCache.size()); tf.constructType(getClass()); // 19-Oct-2015, tatu: This is pretty fragile but assertEquals(6, tf._typeCache.size()); tf.clearCache(); assertEquals(0, tf._typeCache.size()); } // for [databind#1297] public void testRawMapType() { TypeFactory tf = TypeFactory.defaultInstance().withModifier(null); // to get a new copy JavaType type = tf.constructParametricType(Wrapper1297.class, Map.class); assertNotNull(type); assertEquals(Wrapper1297.class, type.getRawClass()); } }
// You are a professional Java test case writer, please create a test case named `testCanonicalNames` for the issue `JacksonDatabind-2109`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2109 // // ## Issue-Title: // Canonical string for reference type is built incorrectly // // ## Issue-Description: // Canonical string for reference type is built incorrectly. // // E.g.: // // `new ReferenceType(new TypeFactory(new LRUMap<Object, JavaType>(0, 10000)).constructType(Object.class), new PlaceholderForType(0)).toCanonical()` // // yields: // // `java.lang.Object<$1` // // while the expected value is: // // `java.lang.Object<$1>` // // // // public void testCanonicalNames() {
255
/** * Test for checking that canonical name handling works ok */
99
208
src/test/java/com/fasterxml/jackson/databind/type/TestTypeFactory.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-2109 ## Issue-Title: Canonical string for reference type is built incorrectly ## Issue-Description: Canonical string for reference type is built incorrectly. E.g.: `new ReferenceType(new TypeFactory(new LRUMap<Object, JavaType>(0, 10000)).constructType(Object.class), new PlaceholderForType(0)).toCanonical()` yields: `java.lang.Object<$1` while the expected value is: `java.lang.Object<$1>` ``` You are a professional Java test case writer, please create a test case named `testCanonicalNames` for the issue `JacksonDatabind-2109`, utilizing the provided issue report information and the following function signature. ```java public void testCanonicalNames() { ```
208
[ "com.fasterxml.jackson.databind.type.ReferenceType" ]
1c444f66eb72a23b9b413cda62b8427cccf4239865dc76a9428d985cf3385103
public void testCanonicalNames()
// You are a professional Java test case writer, please create a test case named `testCanonicalNames` for the issue `JacksonDatabind-2109`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2109 // // ## Issue-Title: // Canonical string for reference type is built incorrectly // // ## Issue-Description: // Canonical string for reference type is built incorrectly. // // E.g.: // // `new ReferenceType(new TypeFactory(new LRUMap<Object, JavaType>(0, 10000)).constructType(Object.class), new PlaceholderForType(0)).toCanonical()` // // yields: // // `java.lang.Object<$1` // // while the expected value is: // // `java.lang.Object<$1>` // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; /** * Simple tests to verify that the {@link TypeFactory} constructs * type information as expected. */ public class TestTypeFactory extends BaseMapTest { /* /********************************************************** /* Helper types /********************************************************** */ enum EnumForCanonical { YES, NO; } static class SingleArgGeneric<X> { } abstract static class MyMap extends IntermediateMap<String,Long> { } abstract static class IntermediateMap<K,V> implements Map<K,V> { } abstract static class MyList extends IntermediateList<Long> { } abstract static class IntermediateList<E> implements List<E> { } @SuppressWarnings("serial") static class GenericList<T> extends ArrayList<T> { } interface MapInterface extends Cloneable, IntermediateInterfaceMap<String> { } interface IntermediateInterfaceMap<FOO> extends Map<FOO, Integer> { } @SuppressWarnings("serial") static class MyStringIntMap extends MyStringXMap<Integer> { } @SuppressWarnings("serial") static class MyStringXMap<V> extends HashMap<String,V> { } // And one more, now with obfuscated type names; essentially it's just Map<Int,Long> static abstract class IntLongMap extends XLongMap<Integer> { } // trick here is that V now refers to key type, not value type static abstract class XLongMap<V> extends XXMap<V,Long> { } static abstract class XXMap<K,V> implements Map<K,V> { } static class SneakyBean { public IntLongMap intMap; public MyList longList; } static class SneakyBean2 { // self-reference; should be resolved as "Comparable<Object>" public <T extends Comparable<T>> T getFoobar() { return null; } } @SuppressWarnings("serial") public static class LongValuedMap<K> extends HashMap<K, Long> { } static class StringLongMapBean { public LongValuedMap<String> value; } static class StringListBean { public GenericList<String> value; } static class CollectionLike<E> { } static class MapLike<K,V> { } static class Wrapper1297<T> { public T content; } /* /********************************************************** /* Unit tests /********************************************************** */ public void testSimpleTypes() { Class<?>[] classes = new Class<?>[] { boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class, Boolean.class, Byte.class, Character.class, Short.class, Integer.class, Long.class, Float.class, Double.class, String.class, Object.class, Calendar.class, Date.class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); assertSame(clz, tf.constructType(clz).getRawClass()); } } public void testArrays() { Class<?>[] classes = new Class<?>[] { boolean[].class, byte[].class, char[].class, short[].class, int[].class, long[].class, float[].class, double[].class, String[].class, Object[].class, Calendar[].class, }; TypeFactory tf = TypeFactory.defaultInstance(); for (Class<?> clz : classes) { assertSame(clz, tf.constructType(clz).getRawClass()); Class<?> elemType = clz.getComponentType(); assertSame(clz, tf.constructArrayType(elemType).getRawClass()); } } // [databind#810]: Fake Map type for Properties as <String,String> public void testProperties() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(Properties.class); assertEquals(MapType.class, t.getClass()); assertSame(Properties.class, t.getRawClass()); MapType mt = (MapType) t; // so far so good. But how about parameterization? assertSame(String.class, mt.getKeyType().getRawClass()); assertSame(String.class, mt.getContentType().getRawClass()); } public void testIterator() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(new TypeReference<Iterator<String>>() { }); assertEquals(SimpleType.class, t.getClass()); assertSame(Iterator.class, t.getRawClass()); assertEquals(1, t.containedTypeCount()); assertEquals(tf.constructType(String.class), t.containedType(0)); assertNull(t.containedType(1)); } /** * Test for verifying that parametric types can be constructed * programmatically */ @SuppressWarnings("deprecation") public void testParametricTypes() { TypeFactory tf = TypeFactory.defaultInstance(); // first, simple class based JavaType t = tf.constructParametrizedType(ArrayList.class, Collection.class, String.class); // ArrayList<String> assertEquals(CollectionType.class, t.getClass()); JavaType strC = tf.constructType(String.class); assertEquals(1, t.containedTypeCount()); assertEquals(strC, t.containedType(0)); assertNull(t.containedType(1)); // Then using JavaType JavaType t2 = tf.constructParametrizedType(Map.class, Map.class, strC, t); // Map<String,ArrayList<String>> // should actually produce a MapType assertEquals(MapType.class, t2.getClass()); assertEquals(2, t2.containedTypeCount()); assertEquals(strC, t2.containedType(0)); assertEquals(t, t2.containedType(1)); assertNull(t2.containedType(2)); // and then custom generic type as well JavaType custom = tf.constructParametrizedType(SingleArgGeneric.class, SingleArgGeneric.class, String.class); assertEquals(SimpleType.class, custom.getClass()); assertEquals(1, custom.containedTypeCount()); assertEquals(strC, custom.containedType(0)); assertNull(custom.containedType(1)); // should also be able to access variable name: assertEquals("X", custom.containedTypeName(0)); // And finally, ensure that we can't create invalid combinations try { // Maps must take 2 type parameters, not just one tf.constructParametrizedType(Map.class, Map.class, strC); } catch (IllegalArgumentException e) { verifyException(e, "Can not create TypeBindings for class java.util.Map"); } try { // Type only accepts one type param tf.constructParametrizedType(SingleArgGeneric.class, SingleArgGeneric.class, strC, strC); } catch (IllegalArgumentException e) { verifyException(e, "Can not create TypeBindings for class "); } } /** * Test for checking that canonical name handling works ok */ public void testCanonicalNames() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(java.util.Calendar.class); String can = t.toCanonical(); assertEquals("java.util.Calendar", can); assertEquals(t, tf.constructFromCanonical(can)); // Generic maps and collections will default to Object.class if type-erased t = tf.constructType(java.util.ArrayList.class); can = t.toCanonical(); assertEquals("java.util.ArrayList<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); t = tf.constructType(java.util.TreeMap.class); can = t.toCanonical(); assertEquals("java.util.TreeMap<java.lang.Object,java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); // And then EnumMap (actual use case for us) t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class); can = t.toCanonical(); assertEquals("java.util.EnumMap<com.fasterxml.jackson.databind.type.TestTypeFactory$EnumForCanonical,java.lang.String>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#2109]: also ReferenceTypes t = tf.constructType(new TypeReference<AtomicReference<Long>>() { }); can = t.toCanonical(); assertEquals("java.util.concurrent.atomic.AtomicReference<java.lang.Long>", can); assertEquals(t, tf.constructFromCanonical(can)); // [databind#1941]: allow "raw" types too t = tf.constructFromCanonical("java.util.List"); assertEquals(List.class, t.getRawClass()); assertEquals(CollectionType.class, t.getClass()); // 01-Mar-2018, tatu: not 100% should we expect type parameters here... // But currently we do NOT get any /* assertEquals(1, t.containedTypeCount()); assertEquals(Object.class, t.containedType(0).getRawClass()); */ assertEquals(Object.class, t.getContentType().getRawClass()); can = t.toCanonical(); assertEquals("java.util.List<java.lang.Object>", can); assertEquals(t, tf.constructFromCanonical(can)); } // [databind#1768] @SuppressWarnings("serial") public void testCanonicalWithSpaces() { TypeFactory tf = TypeFactory.defaultInstance(); Object objects = new TreeMap<Object, Object>() { }; // to get subtype String reflectTypeName = objects.getClass().getGenericSuperclass().toString(); JavaType t1 = tf.constructType(objects.getClass().getGenericSuperclass()); // This will throw an Exception if you don't remove all white spaces from the String. JavaType t2 = tf.constructFromCanonical(reflectTypeName); assertNotNull(t2); assertEquals(t2, t1); } /* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */ public void testCollections() { // Ok, first: let's test what happens when we pass 'raw' Collection: TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(ArrayList.class); assertEquals(CollectionType.class, t.getClass()); assertSame(ArrayList.class, t.getRawClass()); // And then the proper way t = tf.constructType(new TypeReference<ArrayList<String>>() { }); assertEquals(CollectionType.class, t.getClass()); assertSame(ArrayList.class, t.getRawClass()); JavaType elemType = ((CollectionType) t).getContentType(); assertNotNull(elemType); assertSame(SimpleType.class, elemType.getClass()); assertSame(String.class, elemType.getRawClass()); // And alternate method too t = tf.constructCollectionType(ArrayList.class, String.class); assertEquals(CollectionType.class, t.getClass()); assertSame(String.class, ((CollectionType) t).getContentType().getRawClass()); } // since 2.7 public void testCollectionTypesRefined() { TypeFactory tf = newTypeFactory(); JavaType type = tf.constructType(new TypeReference<List<Long>>() { }); assertEquals(List.class, type.getRawClass()); assertEquals(Long.class, type.getContentType().getRawClass()); // No super-class, since it's an interface: assertNull(type.getSuperClass()); // But then refine to reflect sub-classing JavaType subtype = tf.constructSpecializedType(type, ArrayList.class); assertEquals(ArrayList.class, subtype.getRawClass()); assertEquals(Long.class, subtype.getContentType().getRawClass()); // but with refinement, should have non-null super class JavaType superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(AbstractList.class, superType.getRawClass()); } /* /********************************************************** /* Unit tests: map type parameter resolution /********************************************************** */ public void testMaps() { TypeFactory tf = newTypeFactory(); // Ok, first: let's test what happens when we pass 'raw' Map: JavaType t = tf.constructType(HashMap.class); assertEquals(MapType.class, t.getClass()); assertSame(HashMap.class, t.getRawClass()); // Then explicit construction t = tf.constructMapType(TreeMap.class, String.class, Integer.class); assertEquals(MapType.class, t.getClass()); assertSame(String.class, ((MapType) t).getKeyType().getRawClass()); assertSame(Integer.class, ((MapType) t).getContentType().getRawClass()); // And then with TypeReference t = tf.constructType(new TypeReference<HashMap<String,Integer>>() { }); assertEquals(MapType.class, t.getClass()); assertSame(HashMap.class, t.getRawClass()); MapType mt = (MapType) t; assertEquals(tf.constructType(String.class), mt.getKeyType()); assertEquals(tf.constructType(Integer.class), mt.getContentType()); t = tf.constructType(new TypeReference<LongValuedMap<Boolean>>() { }); assertEquals(MapType.class, t.getClass()); assertSame(LongValuedMap.class, t.getRawClass()); mt = (MapType) t; assertEquals(tf.constructType(Boolean.class), mt.getKeyType()); assertEquals(tf.constructType(Long.class), mt.getContentType()); JavaType type = tf.constructType(new TypeReference<Map<String,Boolean>>() { }); MapType mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Boolean.class), mapType.getContentType()); } // since 2.7 public void testMapTypesRefined() { TypeFactory tf = newTypeFactory(); JavaType type = tf.constructType(new TypeReference<Map<String,List<Integer>>>() { }); MapType mapType = (MapType) type; assertEquals(Map.class, mapType.getRawClass()); assertEquals(String.class, mapType.getKeyType().getRawClass()); assertEquals(List.class, mapType.getContentType().getRawClass()); assertEquals(Integer.class, mapType.getContentType().getContentType().getRawClass()); // No super-class, since it's an interface: assertNull(type.getSuperClass()); // But then refine to reflect sub-classing JavaType subtype = tf.constructSpecializedType(type, LinkedHashMap.class); assertEquals(LinkedHashMap.class, subtype.getRawClass()); assertEquals(String.class, subtype.getKeyType().getRawClass()); assertEquals(List.class, subtype.getContentType().getRawClass()); assertEquals(Integer.class, subtype.getContentType().getContentType().getRawClass()); // but with refinement, should have non-null super class // 20-Oct-2015, tatu: For now refinement does not faithfully replicate the // structure, it only retains most important information. Here it means // that actually existing super-classes are skipped, and only original // type is linked as expected JavaType superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(HashMap.class, superType.getRawClass()); // which also should have proper typing assertEquals(String.class, superType.getKeyType().getRawClass()); assertEquals(List.class, superType.getContentType().getRawClass()); assertEquals(Integer.class, superType.getContentType().getContentType().getRawClass()); } public void testMapTypesRaw() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(HashMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(Object.class), mapType.getKeyType()); assertEquals(tf.constructType(Object.class), mapType.getContentType()); } public void testMapTypesAdvanced() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(MyMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); type = tf.constructType(MapInterface.class); mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Integer.class), mapType.getContentType()); type = tf.constructType(MyStringIntMap.class); mapType = (MapType) type; assertEquals(tf.constructType(String.class), mapType.getKeyType()); assertEquals(tf.constructType(Integer.class), mapType.getContentType()); } /** * Specific test to verify that complicate name mangling schemes * do not fool type resolver */ public void testMapTypesSneaky() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(IntLongMap.class); MapType mapType = (MapType) type; assertEquals(tf.constructType(Integer.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); } /** * Plus sneaky types may be found via introspection as well. */ public void testSneakyFieldTypes() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Field field = SneakyBean.class.getDeclaredField("intMap"); JavaType type = tf.constructType(field.getGenericType()); assertTrue(type instanceof MapType); MapType mapType = (MapType) type; assertEquals(tf.constructType(Integer.class), mapType.getKeyType()); assertEquals(tf.constructType(Long.class), mapType.getContentType()); field = SneakyBean.class.getDeclaredField("longList"); type = tf.constructType(field.getGenericType()); assertTrue(type instanceof CollectionType); CollectionType collectionType = (CollectionType) type; assertEquals(tf.constructType(Long.class), collectionType.getContentType()); } /** * Looks like type handling actually differs for properties, too. */ public void testSneakyBeanProperties() throws Exception { ObjectMapper mapper = new ObjectMapper(); StringLongMapBean bean = mapper.readValue("{\"value\":{\"a\":123}}", StringLongMapBean.class); assertNotNull(bean); Map<String,Long> map = bean.value; assertEquals(1, map.size()); assertEquals(Long.valueOf(123), map.get("a")); StringListBean bean2 = mapper.readValue("{\"value\":[\"...\"]}", StringListBean.class); assertNotNull(bean2); List<String> list = bean2.value; assertSame(GenericList.class, list.getClass()); assertEquals(1, list.size()); assertEquals("...", list.get(0)); } public void testSneakySelfRefs() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(new SneakyBean2()); assertEquals("{\"foobar\":null}", json); } /* /********************************************************** /* Unit tests: handling of specific JDK types /********************************************************** */ public void testAtomicArrayRefParameters() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructType(new TypeReference<AtomicReference<long[]>>() { }); JavaType[] params = tf.findTypeParameters(type, AtomicReference.class); assertNotNull(params); assertEquals(1, params.length); assertEquals(tf.constructType(long[].class), params[0]); } static abstract class StringIntMapEntry implements Map.Entry<String,Integer> { } public void testMapEntryResolution() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(StringIntMapEntry.class); JavaType mapEntryType = t.findSuperType(Map.Entry.class); assertNotNull(mapEntryType); assertTrue(mapEntryType.hasGenericTypes()); assertEquals(2, mapEntryType.containedTypeCount()); assertEquals(String.class, mapEntryType.containedType(0).getRawClass()); assertEquals(Integer.class, mapEntryType.containedType(1).getRawClass()); } /* /********************************************************** /* Unit tests: construction of "raw" types /********************************************************** */ public void testRawCollections() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawCollectionType(ArrayList.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawCollectionLikeType(CollectionLike.class); // must have type vars assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawCollectionLikeType(String.class); assertTrue(type.isCollectionLikeType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); } public void testRawMaps() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType type = tf.constructRawMapType(HashMap.class); assertTrue(type.isContainerType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); type = tf.constructRawMapLikeType(MapLike.class); // must have type vars assertTrue(type.isMapLikeType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); // actually, should also allow "no type vars" case type = tf.constructRawMapLikeType(String.class); assertTrue(type.isMapLikeType()); assertEquals(TypeFactory.unknownType(), type.getKeyType()); assertEquals(TypeFactory.unknownType(), type.getContentType()); } /* /********************************************************** /* Unit tests: other /********************************************************** */ public void testMoreSpecificType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t1 = tf.constructCollectionType(Collection.class, Object.class); JavaType t2 = tf.constructCollectionType(List.class, Object.class); assertSame(t2, tf.moreSpecificType(t1, t2)); assertSame(t2, tf.moreSpecificType(t2, t1)); t1 = tf.constructType(Double.class); t2 = tf.constructType(Number.class); assertSame(t1, tf.moreSpecificType(t1, t2)); assertSame(t1, tf.moreSpecificType(t2, t1)); // and then unrelated, return first t1 = tf.constructType(Double.class); t2 = tf.constructType(String.class); assertSame(t1, tf.moreSpecificType(t1, t2)); assertSame(t2, tf.moreSpecificType(t2, t1)); } // [databind#489] public void testCacheClearing() { TypeFactory tf = TypeFactory.defaultInstance().withModifier(null); assertEquals(0, tf._typeCache.size()); tf.constructType(getClass()); // 19-Oct-2015, tatu: This is pretty fragile but assertEquals(6, tf._typeCache.size()); tf.clearCache(); assertEquals(0, tf._typeCache.size()); } // for [databind#1297] public void testRawMapType() { TypeFactory tf = TypeFactory.defaultInstance().withModifier(null); // to get a new copy JavaType type = tf.constructParametricType(Wrapper1297.class, Map.class); assertNotNull(type); assertEquals(Wrapper1297.class, type.getRawClass()); } }
public void testEqualGeneralPaths() { GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); GeneralPath g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertTrue(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(11.0f, 22.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(33.0f, 44.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(55.0f, 66.0f, 77.0f, 88.0f, 99.0f, 100.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(11.0f, 22.0f, 33.0f, 44.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.lineTo(3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); }
org.jfree.chart.util.junit.ShapeUtilitiesTests::testEqualGeneralPaths
tests/org/jfree/chart/util/junit/ShapeUtilitiesTests.java
245
tests/org/jfree/chart/util/junit/ShapeUtilitiesTests.java
testEqualGeneralPaths
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * ShapeUtilitiesTests.java * ------------------------ * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 02-Jun-2008 : Copied from JCommon (DG); * */ package org.jfree.chart.util.junit; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.util.ShapeUtilities; /** * Tests for the {@link ShapeUtilities} class. */ public class ShapeUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ShapeUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ShapeUtilitiesTests(final String name) { super(name); } /** * Tests the equal() method. */ public void testEqualLine2Ds() { assertTrue(ShapeUtilities.equal((Line2D) null, (Line2D) null)); Line2D l1 = new Line2D.Float(1.0f, 2.0f, 3.0f, 4.0f); Line2D l2 = new Line2D.Float(1.0f, 2.0f, 3.0f, 4.0f); assertTrue(ShapeUtilities.equal(l1, l2)); l1 = new Line2D.Float(4.0f, 3.0f, 2.0f, 1.0f); assertFalse(ShapeUtilities.equal(l1, l2)); l2 = new Line2D.Float(4.0f, 3.0f, 2.0f, 1.0f); assertTrue(ShapeUtilities.equal(l1, l2)); l1 = new Line2D.Double(4.0f, 3.0f, 2.0f, 1.0f); assertTrue(ShapeUtilities.equal(l1, l2)); } /** * Some checks for the equal(Shape, Shape) method. */ public void testEqualShapes() { // NULL Shape s1 = null; Shape s2 = null; assertTrue(ShapeUtilities.equal(s1, s2)); // LINE2D s1 = new Line2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Line2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); assertFalse(s1.equals(s2)); // RECTANGLE2D s1 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); assertTrue(s1.equals(s2)); // Rectangle2D overrides equals() // ELLIPSE2D s1 = new Ellipse2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Ellipse2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); // ARC2D s1 = new Arc2D.Double(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, Arc2D.PIE); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Arc2D.Double(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, Arc2D.PIE); assertTrue(ShapeUtilities.equal(s1, s2)); // POLYGON Polygon p1 = new Polygon(new int[] {0, 1, 0}, new int[] {1, 0, 1}, 3); Polygon p2 = new Polygon(new int[] {1, 1, 0}, new int[] {1, 0, 1}, 3); s1 = p1; s2 = p2; assertFalse(ShapeUtilities.equal(s1, s2)); p2 = new Polygon(new int[] {0, 1, 0}, new int[] {1, 0, 1}, 3); s2 = p2; assertTrue(ShapeUtilities.equal(s1, s2)); // GENERALPATH GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); s1 = g1; assertFalse(ShapeUtilities.equal(s1, s2)); GeneralPath g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); s2 = g2; assertTrue(ShapeUtilities.equal(s1, s2)); assertFalse(s1.equals(s2)); } /** * Some checks for the intersects() method, */ public void testIntersects() { final Rectangle2D r1 = new Rectangle2D.Float(0, 0, 100, 100); final Rectangle2D r2 = new Rectangle2D.Float(0, 0, 100, 100); assertTrue(ShapeUtilities.intersects(r1, r2)); r1.setRect(100, 0, 100, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); r1.setRect(0, 0, 0, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); r1.setRect(50, 50, 10, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); } /** * Some checks for the equal(GeneralPath, GeneralPath) method. */ public void testEqualGeneralPaths() { GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); GeneralPath g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertTrue(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(11.0f, 22.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(33.0f, 44.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(55.0f, 66.0f, 77.0f, 88.0f, 99.0f, 100.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(11.0f, 22.0f, 33.0f, 44.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.lineTo(3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); } }
// You are a professional Java test case writer, please create a test case named `testEqualGeneralPaths` for the issue `Chart-868`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-868 // // ## Issue-Title: // #868 JCommon 1.0.12 ShapeUtilities.equal(path1,path2) // // // // // // ## Issue-Description: // 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. // // // // public void testEqualGeneralPaths() {
245
/** * Some checks for the equal(GeneralPath, GeneralPath) method. */
11
190
tests/org/jfree/chart/util/junit/ShapeUtilitiesTests.java
tests
```markdown ## Issue-ID: Chart-868 ## Issue-Title: #868 JCommon 1.0.12 ShapeUtilities.equal(path1,path2) ## Issue-Description: 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. ``` You are a professional Java test case writer, please create a test case named `testEqualGeneralPaths` for the issue `Chart-868`, utilizing the provided issue report information and the following function signature. ```java public void testEqualGeneralPaths() { ```
190
[ "org.jfree.chart.util.ShapeUtilities" ]
1c62e0459299c55b8a9bf134b41605dd2c630c2e5732c233c6cddd45d35b39b4
public void testEqualGeneralPaths()
// You are a professional Java test case writer, please create a test case named `testEqualGeneralPaths` for the issue `Chart-868`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-868 // // ## Issue-Title: // #868 JCommon 1.0.12 ShapeUtilities.equal(path1,path2) // // // // // // ## Issue-Description: // 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. // // // //
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * ShapeUtilitiesTests.java * ------------------------ * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 02-Jun-2008 : Copied from JCommon (DG); * */ package org.jfree.chart.util.junit; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.util.ShapeUtilities; /** * Tests for the {@link ShapeUtilities} class. */ public class ShapeUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ShapeUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ShapeUtilitiesTests(final String name) { super(name); } /** * Tests the equal() method. */ public void testEqualLine2Ds() { assertTrue(ShapeUtilities.equal((Line2D) null, (Line2D) null)); Line2D l1 = new Line2D.Float(1.0f, 2.0f, 3.0f, 4.0f); Line2D l2 = new Line2D.Float(1.0f, 2.0f, 3.0f, 4.0f); assertTrue(ShapeUtilities.equal(l1, l2)); l1 = new Line2D.Float(4.0f, 3.0f, 2.0f, 1.0f); assertFalse(ShapeUtilities.equal(l1, l2)); l2 = new Line2D.Float(4.0f, 3.0f, 2.0f, 1.0f); assertTrue(ShapeUtilities.equal(l1, l2)); l1 = new Line2D.Double(4.0f, 3.0f, 2.0f, 1.0f); assertTrue(ShapeUtilities.equal(l1, l2)); } /** * Some checks for the equal(Shape, Shape) method. */ public void testEqualShapes() { // NULL Shape s1 = null; Shape s2 = null; assertTrue(ShapeUtilities.equal(s1, s2)); // LINE2D s1 = new Line2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Line2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); assertFalse(s1.equals(s2)); // RECTANGLE2D s1 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); assertTrue(s1.equals(s2)); // Rectangle2D overrides equals() // ELLIPSE2D s1 = new Ellipse2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Ellipse2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); // ARC2D s1 = new Arc2D.Double(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, Arc2D.PIE); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Arc2D.Double(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, Arc2D.PIE); assertTrue(ShapeUtilities.equal(s1, s2)); // POLYGON Polygon p1 = new Polygon(new int[] {0, 1, 0}, new int[] {1, 0, 1}, 3); Polygon p2 = new Polygon(new int[] {1, 1, 0}, new int[] {1, 0, 1}, 3); s1 = p1; s2 = p2; assertFalse(ShapeUtilities.equal(s1, s2)); p2 = new Polygon(new int[] {0, 1, 0}, new int[] {1, 0, 1}, 3); s2 = p2; assertTrue(ShapeUtilities.equal(s1, s2)); // GENERALPATH GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); s1 = g1; assertFalse(ShapeUtilities.equal(s1, s2)); GeneralPath g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); s2 = g2; assertTrue(ShapeUtilities.equal(s1, s2)); assertFalse(s1.equals(s2)); } /** * Some checks for the intersects() method, */ public void testIntersects() { final Rectangle2D r1 = new Rectangle2D.Float(0, 0, 100, 100); final Rectangle2D r2 = new Rectangle2D.Float(0, 0, 100, 100); assertTrue(ShapeUtilities.intersects(r1, r2)); r1.setRect(100, 0, 100, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); r1.setRect(0, 0, 0, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); r1.setRect(50, 50, 10, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); } /** * Some checks for the equal(GeneralPath, GeneralPath) method. */ public void testEqualGeneralPaths() { GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); GeneralPath g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertTrue(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(11.0f, 22.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(33.0f, 44.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(55.0f, 66.0f, 77.0f, 88.0f, 99.0f, 100.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(11.0f, 22.0f, 33.0f, 44.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.lineTo(3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); } }
@Test public void discardsSpuriousByteOrderMark() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, "UTF-8", "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); }
org.jsoup.helper.DataUtilTest::discardsSpuriousByteOrderMark
src/test/java/org/jsoup/helper/DataUtilTest.java
32
src/test/java/org/jsoup/helper/DataUtilTest.java
discardsSpuriousByteOrderMark
package org.jsoup.helper; import static org.junit.Assert.assertEquals; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import org.junit.Test; import java.nio.ByteBuffer; import java.nio.charset.Charset; public class DataUtilTest { @Test public void testCharset() { assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); } @Test public void testQuotedCharset() { assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=\"utf-8\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=\"utf-8\"")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=\"ISO-8859-1\"")); } @Test public void discardsSpuriousByteOrderMark() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, "UTF-8", "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); } }
// You are a professional Java test case writer, please create a test case named `discardsSpuriousByteOrderMark` for the issue `Jsoup-134`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-134 // // ## Issue-Title: // Some html file's head element will be empty // // ## Issue-Description: // Hello, Jonathan // // // I love Jsoup, and handling many html files. // // // But today, I'm under the problem. // // When parse with Jsoup, some html file's head element will be empty. // // // Sample html is here -> <http://dl.dropbox.com/u/972460/test.html> // // // Please help me. // // // // @Test public void discardsSpuriousByteOrderMark() {
32
20
27
src/test/java/org/jsoup/helper/DataUtilTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-134 ## Issue-Title: Some html file's head element will be empty ## Issue-Description: Hello, Jonathan I love Jsoup, and handling many html files. But today, I'm under the problem. When parse with Jsoup, some html file's head element will be empty. Sample html is here -> <http://dl.dropbox.com/u/972460/test.html> Please help me. ``` You are a professional Java test case writer, please create a test case named `discardsSpuriousByteOrderMark` for the issue `Jsoup-134`, utilizing the provided issue report information and the following function signature. ```java @Test public void discardsSpuriousByteOrderMark() { ```
27
[ "org.jsoup.helper.DataUtil" ]
1d09ce78d0f8e64f118ec7e66fb06138803fa5caf1f13185a9f5347a0f8fe771
@Test public void discardsSpuriousByteOrderMark()
// You are a professional Java test case writer, please create a test case named `discardsSpuriousByteOrderMark` for the issue `Jsoup-134`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-134 // // ## Issue-Title: // Some html file's head element will be empty // // ## Issue-Description: // Hello, Jonathan // // // I love Jsoup, and handling many html files. // // // But today, I'm under the problem. // // When parse with Jsoup, some html file's head element will be empty. // // // Sample html is here -> <http://dl.dropbox.com/u/972460/test.html> // // // Please help me. // // // //
Jsoup
package org.jsoup.helper; import static org.junit.Assert.assertEquals; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import org.junit.Test; import java.nio.ByteBuffer; import java.nio.charset.Charset; public class DataUtilTest { @Test public void testCharset() { assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); } @Test public void testQuotedCharset() { assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=\"utf-8\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=\"utf-8\"")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=\"ISO-8859-1\"")); } @Test public void discardsSpuriousByteOrderMark() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, "UTF-8", "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); } }
public void testOneType4() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {'a': 0};\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F['a'] = 0;"; String expected = "{}"; testSets(false, js, js, expected); testSets(true, js, js, expected); }
com.google.javascript.jscomp.DisambiguatePropertiesTest::testOneType4
test/com/google/javascript/jscomp/DisambiguatePropertiesTest.java
129
test/com/google/javascript/jscomp/DisambiguatePropertiesTest.java
testOneType4
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import com.google.javascript.rhino.testing.TestErrorReporter; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * Unit test for the Compiler DisambiguateProperties pass. * */ public class DisambiguatePropertiesTest extends CompilerTestCase { private DisambiguateProperties<?> lastPass; private boolean runTightenTypes; public DisambiguatePropertiesTest() { parseTypeInfo = true; } @Override protected void setUp() throws Exception { super.setUp(); super.enableNormalize(true); super.enableTypeCheck(CheckLevel.WARNING); } @Override public CompilerPass getProcessor(final Compiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { Map<String, CheckLevel> propertiesToErrorFor = Maps.<String, CheckLevel>newHashMap(); propertiesToErrorFor.put("foobar", CheckLevel.ERROR); if (runTightenTypes) { TightenTypes tightener = new TightenTypes(compiler); tightener.process(externs, root); lastPass = DisambiguateProperties.forConcreteTypeSystem(compiler, tightener, propertiesToErrorFor); } else { // This must be created after type checking is run as it depends on // any mismatches found during checking. lastPass = DisambiguateProperties.forJSTypeSystem( compiler, propertiesToErrorFor); } lastPass.process(externs, root); } }; } @Override protected int getNumRepetitions() { return 1; } public void testOneType1() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;"; testSets(false, js, js, "{a=[[Foo.prototype]]}"); testSets(true, js, js, "{a=[[Foo.prototype]]}"); } public void testOneType2() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {a: 0};\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;"; String expected = "{a=[[Foo.prototype]]}"; testSets(false, js, js, expected); testSets(true, js, js, expected); } public void testOneType3() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = { get a() {return 0}," + " set a(b) {} };\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;"; String expected = "{a=[[Foo.prototype]]}"; testSets(false, js, js, expected); testSets(true, js, js, expected); } public void testOneType4() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {'a': 0};\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F['a'] = 0;"; String expected = "{}"; testSets(false, js, js, expected); testSets(true, js, js, expected); } public void testPrototypeAndInstance() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;"; testSets(false, js, js, "{a=[[Foo.prototype]]}"); testSets(true, js, js, "{a=[[Foo.prototype]]}"); } public void testPrototypeAndInstance2() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "new Foo().a = 0;"; testSets(false, js, js, "{a=[[Foo.prototype]]}"); testSets(true, js, js, "{a=[[Foo.prototype]]}"); } public void testTwoTypes1() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B.a = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype.Foo_prototype$a=0;" + "var F=new Foo;" + "F.Foo_prototype$a=0;" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "var B=new Bar;" + "B.Bar_prototype$a=0"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testTwoTypes2() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {a: 0};" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype = {a: 0};" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B.a = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype = {Foo_prototype$a: 0};" + "var F=new Foo;" + "F.Foo_prototype$a=0;" + "function Bar(){}" + "Bar.prototype = {Bar_prototype$a: 0};" + "var B=new Bar;" + "B.Bar_prototype$a=0"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testTwoTypes3() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = { get a() {return 0}," + " set a(b) {} };\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype = { get a() {return 0}," + " set a(b) {} };\n" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B.a = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype = { get Foo_prototype$a() {return 0}," + " set Foo_prototype$a(b) {} };\n" + "var F=new Foo;" + "F.Foo_prototype$a=0;" + "function Bar(){}" + "Bar.prototype = { get Bar_prototype$a() {return 0}," + " set Bar_prototype$a(b) {} };\n" + "var B=new Bar;" + "B.Bar_prototype$a=0"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testTwoTypes4() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {a: 0};" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype = {'a': 0};" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B['a'] = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype = {a: 0};" + "var F=new Foo;" + "F.a=0;" + "function Bar(){}" + "Bar.prototype = {'a': 0};" + "var B=new Bar;" + "B['a']=0"; testSets(false, js, output, "{a=[[Foo.prototype]]}"); testSets(true, js, output, "{a=[[Foo.prototype]]}"); } public void testTwoFields() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "Foo.prototype.b = 0;" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "F.b = 0;"; String output = "function Foo(){}Foo.prototype.a=0;Foo.prototype.b=0;" + "var F=new Foo;F.a=0;F.b=0"; testSets(false, js, output, "{a=[[Foo.prototype]], b=[[Foo.prototype]]}"); testSets(true, js, output, "{a=[[Foo.prototype]], b=[[Foo.prototype]]}"); } public void testTwoSeparateFieldsTwoTypes() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "Foo.prototype.b = 0;" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "F.b = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "Bar.prototype.b = 0;" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B.a = 0;" + "B.b = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype.Foo_prototype$a=0;" + "Foo.prototype.Foo_prototype$b=0;" + "var F=new Foo;" + "F.Foo_prototype$a=0;" + "F.Foo_prototype$b=0;" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "Bar.prototype.Bar_prototype$b=0;" + "var B=new Bar;" + "B.Bar_prototype$a=0;" + "B.Bar_prototype$b=0"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]," + " b=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]," + " b=[[Bar.prototype], [Foo.prototype]]}"); } public void testUnionType() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "/** @type {Bar|Foo} */\n" + "var B = new Bar;\n" + "B.a = 0;\n" + "B = new Foo;\n" + "B.a = 0;\n" + "/** @constructor */ function Baz() {}\n" + "Baz.prototype.a = 0;\n"; testSets(false, js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}"); testSets(true, js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}"); } public void testIgnoreUnknownType() { String js = "" + "/** @constructor */\n" + "function Foo() {}\n" + "Foo.prototype.blah = 3;\n" + "/** @type {Foo} */\n" + "var F = new Foo;\n" + "F.blah = 0;\n" + "var U = function() { return {} };\n" + "U().blah();"; String expected = "" + "function Foo(){}Foo.prototype.blah=3;var F = new Foo;F.blah=0;" + "var U=function(){return{}};U().blah()"; testSets(false, js, expected, "{}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, expected, "{}"); } public void testIgnoreUnknownType1() { String js = "" + "/** @constructor */\n" + "function Foo() {}\n" + "Foo.prototype.blah = 3;\n" + "/** @type {Foo} */\n" + "var F = new Foo;\n" + "F.blah = 0;\n" + "/** @return {Object} */\n" + "var U = function() { return {} };\n" + "U().blah();"; String expected = "" + "function Foo(){}Foo.prototype.blah=3;var F = new Foo;F.blah=0;" + "var U=function(){return{}};U().blah()"; testSets(false, js, expected, "{blah=[[Foo.prototype]]}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, expected, "{}"); } public void testIgnoreUnknownType2() { String js = "" + "/** @constructor */\n" + "function Foo() {}\n" + "Foo.prototype.blah = 3;\n" + "/** @type {Foo} */\n" + "var F = new Foo;\n" + "F.blah = 0;\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype.blah = 3;\n" + "/** @return {Object} */\n" + "var U = function() { return {} };\n" + "U().blah();"; String expected = "" + "function Foo(){}Foo.prototype.blah=3;var F = new Foo;F.blah=0;" + "function Bar(){}Bar.prototype.blah=3;" + "var U=function(){return{}};U().blah()"; testSets(false, js, expected, "{}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, expected, "{}"); } public void testUnionTypeTwoFields() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "Foo.prototype.b = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;\n" + "Bar.prototype.b = 0;\n" + "/** @type {Foo|Bar} */\n" + "var B = new Bar;\n" + "B.a = 0;\n" + "B.b = 0;\n" + "B = new Foo;\n" + "/** @constructor */ function Baz() {}\n" + "Baz.prototype.a = 0;\n" + "Baz.prototype.b = 0;\n"; testSets(false, js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]," + " b=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}"); testSets(true, js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]," + " b=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}"); } public void testCast() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "/** @type {Foo|Bar} */\n" + "var F = new Foo;\n" + "(/** @type {Bar} */(F)).a = 0;"; String output = "" + "function Foo(){}Foo.prototype.Foo_prototype$a=0;" + "function Bar(){}Bar.prototype.Bar_prototype$a=0;" + "var F=new Foo;F.Bar_prototype$a=0;"; String ttOutput = "" + "function Foo(){}Foo.prototype.Foo_prototype$a=0;" + "function Bar(){}Bar.prototype.Bar_prototype$a=0;" + "var F=new Foo;F.Unique$1$a=0;"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, ttOutput, "{a=[[Bar.prototype], [Foo.prototype], [Unique$1]]}"); } public void testConstructorFields() { String js = "" + "/** @constructor */\n" + "var Foo = function() { this.a = 0; };\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "new Foo"; String output = "" + "var Foo=function(){this.Foo$a=0};" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "new Foo"; String ttOutput = "" + "var Foo=function(){this.Foo_prototype$a=0};" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "new Foo"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo]]}"); testSets(true, js, ttOutput, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testStaticProperty() { String js = "" + "/** @constructor */ function Foo() {} \n" + "/** @constructor */ function Bar() {}\n" + "Foo.a = 0;" + "Bar.a = 0;"; String output = "" + "function Foo(){}" + "function Bar(){}" + "Foo.function__new_Foo___undefined$a = 0;" + "Bar.function__new_Bar___undefined$a = 0;"; testSets(false, js, output, "{a=[[function (new:Bar): undefined]," + " [function (new:Foo): undefined]]}"); } public void testSupertypeWithSameField() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @constructor\n* @extends Foo */ function Bar() {}\n" + "/** @override */\n" + "Bar.prototype.a = 0;\n" + "/** @type Bar */ var B = new Bar;\n" + "B.a = 0;" + "/** @constructor */ function Baz() {}\n" + "Baz.prototype.a = function(){};\n"; String output = "" + "function Foo(){}Foo.prototype.Foo_prototype$a=0;" + "function Bar(){}Bar.prototype.Foo_prototype$a=0;" + "var B = new Bar;B.Foo_prototype$a=0;" + "function Baz(){}Baz.prototype.Baz_prototype$a=function(){};"; String ttOutput = "" + "function Foo(){}Foo.prototype.Foo_prototype$a=0;" + "function Bar(){}Bar.prototype.Bar_prototype$a=0;" + "var B = new Bar;B.Bar_prototype$a=0;" + "function Baz(){}Baz.prototype.Baz_prototype$a=function(){};"; testSets(false, js, output, "{a=[[Baz.prototype], [Foo.prototype]]}"); testSets(true, js, ttOutput, "{a=[[Bar.prototype], [Baz.prototype], [Foo.prototype]]}"); } public void testScopedType() { String js = "" + "var g = {};\n" + "/** @constructor */ g.Foo = function() {}\n" + "g.Foo.prototype.a = 0;" + "/** @constructor */ g.Bar = function() {}\n" + "g.Bar.prototype.a = 0;"; String output = "" + "var g={};" + "g.Foo=function(){};" + "g.Foo.prototype.g_Foo_prototype$a=0;" + "g.Bar=function(){};" + "g.Bar.prototype.g_Bar_prototype$a=0;"; testSets(false, js, output, "{a=[[g.Bar.prototype], [g.Foo.prototype]]}"); testSets(true, js, output, "{a=[[g.Bar.prototype], [g.Foo.prototype]]}"); } public void testUnresolvedType() { // NOTE(nicksantos): This behavior seems very wrong to me. String js = "" + "var g = {};" + "/** @constructor \n @extends {?} */ " + "var Foo = function() {};\n" + "Foo.prototype.a = 0;" + "/** @constructor */ var Bar = function() {};\n" + "Bar.prototype.a = 0;"; String output = "" + "var g={};" + "var Foo=function(){};" + "Foo.prototype.Foo_prototype$a=0;" + "var Bar=function(){};" + "Bar.prototype.Bar_prototype$a=0;"; setExpectParseWarningsThisTest(); testSets(false, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testNamedType() { String js = "" + "var g = {};" + "/** @constructor \n @extends g.Late */ var Foo = function() {}\n" + "Foo.prototype.a = 0;" + "/** @constructor */ var Bar = function() {}\n" + "Bar.prototype.a = 0;" + "/** @constructor */ g.Late = function() {}"; String output = "" + "var g={};" + "var Foo=function(){};" + "Foo.prototype.Foo_prototype$a=0;" + "var Bar=function(){};" + "Bar.prototype.Bar_prototype$a=0;" + "g.Late = function(){}"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testUnknownType() { String js = "" + "/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Bar = function() {};\n" + "/** @return {?} */ function fun() {}\n" + "Foo.prototype.a = fun();\n" + "fun().a;\n" + "Bar.prototype.a = 0;"; String ttOutput = "" + "var Foo=function(){};\n" + "var Bar=function(){};\n" + "function fun(){}\n" + "Foo.prototype.Foo_prototype$a=fun();\n" + "fun().Unique$1$a;\n" + "Bar.prototype.Bar_prototype$a=0;"; testSets(false, js, js, "{}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, ttOutput, "{a=[[Bar.prototype], [Foo.prototype], [Unique$1]]}"); } public void testEnum() { String js = "" + "/** @enum {string} */ var En = {\n" + " A: 'first',\n" + " B: 'second'\n" + "};\n" + "var EA = En.A;\n" + "var EB = En.B;\n" + "/** @constructor */ function Foo(){};\n" + "Foo.prototype.A = 0;\n" + "Foo.prototype.B = 0;\n"; String output = "" + "var En={A:'first',B:'second'};" + "var EA=En.A;" + "var EB=En.B;" + "function Foo(){};" + "Foo.prototype.Foo_prototype$A=0;" + "Foo.prototype.Foo_prototype$B=0"; String ttOutput = "" + "var En={A:'first',B:'second'};" + "var EA=En.A;" + "var EB=En.B;" + "function Foo(){};" + "Foo.prototype.Foo_prototype$A=0;" + "Foo.prototype.Foo_prototype$B=0"; testSets(false, js, output, "{A=[[Foo.prototype]], B=[[Foo.prototype]]}"); testSets(true, js, ttOutput, "{A=[[Foo.prototype]], B=[[Foo.prototype]]}"); } public void testEnumOfObjects() { String js = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.format = function() {};" + "/** @enum {!Formatter} */ var Enum = {\n" + " A: new Formatter()\n" + "};\n" + "Enum.A.format();\n"; String output = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.Formatter_prototype$format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.Unrelated_prototype$format = function() {};" + "/** @enum {!Formatter} */ var Enum = {\n" + " A: new Formatter()\n" + "};\n" + "Enum.A.Formatter_prototype$format();\n"; testSets(false, js, output, "{format=[[Formatter.prototype], [Unrelated.prototype]]}"); // TODO(nicksantos): Fix the type tightener to handle this case. // It currently doesn't work, because getSubTypes is broken for enums. } public void testEnumOfObjects2() { String js = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.format = function() {};" + "/** @enum {?Formatter} */ var Enum = {\n" + " A: new Formatter(),\n" + " B: new Formatter()\n" + "};\n" + "function f() {\n" + " var formatter = window.toString() ? Enum.A : Enum.B;\n" + " formatter.format();\n" + "}"; String output = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.format = function() {};" + "/** @enum {?Formatter} */ var Enum = {\n" + " A: new Formatter(),\n" + " B: new Formatter()\n" + "};\n" + "function f() {\n" + " var formatter = window.toString() ? Enum.A : Enum.B;\n" + " formatter.format();\n" + "}"; testSets(false, js, output, "{}"); } public void testEnumOfObjects3() { String js = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.format = function() {};" + "/** @enum {!Formatter} */ var Enum = {\n" + " A: new Formatter(),\n" + " B: new Formatter()\n" + "};\n" + "/** @enum {!Enum} */ var SubEnum = {\n" + " C: Enum.A\n" + "};\n" + "function f() {\n" + " var formatter = SubEnum.C\n" + " formatter.format();\n" + "}"; String output = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.Formatter_prototype$format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.Unrelated_prototype$format = function() {};" + "/** @enum {!Formatter} */ var Enum = {\n" + " A: new Formatter(),\n" + " B: new Formatter()\n" + "};\n" + "/** @enum {!Enum} */ var SubEnum = {\n" + " C: Enum.A\n" + "};\n" + "function f() {\n" + " var formatter = SubEnum.C\n" + " formatter.Formatter_prototype$format();\n" + "}"; testSets(false, js, output, "{format=[[Formatter.prototype], [Unrelated.prototype]]}"); } public void testUntypedExterns() { String externs = BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES + "var window;" + "window.alert = function() {x};"; String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "Foo.prototype.alert = 0;\n" + "Foo.prototype.window = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;\n" + "Bar.prototype.alert = 0;\n" + "Bar.prototype.window = 0;\n" + "window.alert();"; String output = "" + "function Foo(){}" + "Foo.prototype.Foo_prototype$a=0;" + "Foo.prototype.alert=0;" + "Foo.prototype.Foo_prototype$window=0;" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "Bar.prototype.alert=0;" + "Bar.prototype.Bar_prototype$window=0;" + "window.alert();"; testSets(false, externs, js, output, "{a=[[Bar.prototype], [Foo.prototype]]" + ", window=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, externs, js, output, "{a=[[Bar.prototype], [Foo.prototype]]," + " window=[[Bar.prototype], [Foo.prototype]]}"); } public void testUnionTypeInvalidation() { String externs = "" + "/** @constructor */ function Baz() {}" + "Baz.prototype.a"; String js = "" + "/** @constructor */ function Ind() {this.a=0}\n" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;\n" + "/** @type {Foo|Bar} */\n" + "var F = new Foo;\n" + "F.a = 1\n;" + "F = new Bar;\n" + "/** @type {Baz} */\n" + "var Z = new Baz;\n" + "Z.a = 1\n;" + "/** @type {Bar|Baz} */\n" + "var B = new Baz;\n" + "B.a = 1;\n" + "B = new Bar;\n"; // Only the constructor field a of Ind is renamed, as Foo is related to Baz // through Bar in the unions Bar|Baz and Foo|Bar. String output = "" + "function Ind() { this.Ind$a = 0; }" + "function Foo() {}" + "Foo.prototype.a = 0;" + "function Bar() {}" + "Bar.prototype.a = 0;" + "var F = new Foo;" + "F.a = 1;" + "F = new Bar;" + "var Z = new Baz;" + "Z.a = 1;" + "var B = new Baz;" + "B.a = 1;" + "B = new Bar;"; String ttOutput = "" + "function Ind() { this.Unique$1$a = 0; }" + "function Foo() {}" + "Foo.prototype.a = 0;" + "function Bar() {}" + "Bar.prototype.a = 0;" + "var F = new Foo;" + "F.a = 1;" + "F = new Bar;" + "var Z = new Baz;" + "Z.a = 1;" + "var B = new Baz;" + "B.a = 1;" + "B = new Bar;"; testSets(false, externs, js, output, "{a=[[Ind]]}"); testSets(true, externs, js, ttOutput, "{a=[[Unique$1]]}"); } public void testUnionAndExternTypes() { String externs = "" + "/** @constructor */ function Foo() { }" + "Foo.prototype.a = 4;\n"; String js = "" + "/** @constructor */ function Bar() { this.a = 2; }\n" + "/** @constructor */ function Baz() { this.a = 3; }\n" + "/** @constructor */ function Buz() { this.a = 4; }\n" + "/** @constructor */ function T1() { this.a = 3; }\n" + "/** @constructor */ function T2() { this.a = 3; }\n" + "/** @type {Bar|Baz} */ var b;\n" + "/** @type {Baz|Buz} */ var c;\n" + "/** @type {Buz|Foo} */ var d;\n" + "b.a = 5; c.a = 6; d.a = 7;"; String output = "" + "/** @constructor */ function Bar() { this.a = 2; }\n" + "/** @constructor */ function Baz() { this.a = 3; }\n" + "/** @constructor */ function Buz() { this.a = 4; }\n" + "/** @constructor */ function T1() { this.T1$a = 3; }\n" + "/** @constructor */ function T2() { this.T2$a = 3; }\n" + "/** @type {Bar|Baz} */ var b;\n" + "/** @type {Baz|Buz} */ var c;\n" + "/** @type {Buz|Foo} */ var d;\n" + "b.a = 5; c.a = 6; d.a = 7;"; // We are testing the skipping of multiple types caused by unionizing with // extern types. testSets(false, externs, js, output, "{a=[[T1], [T2]]}"); } public void testTypedExterns() { String externs = "" + "/** @constructor */ function Window() {};\n" + "Window.prototype.alert;" + "/** @type {Window} */" + "var window;"; String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.alert = 0;\n" + "window.alert('blarg');"; String output = "" + "function Foo(){}" + "Foo.prototype.Foo_prototype$alert=0;" + "window.alert('blarg');"; testSets(false, externs, js, output, "{alert=[[Foo.prototype]]}"); testSets(true, externs, js, output, "{alert=[[Foo.prototype]]}"); } public void testSubtypesWithSameField() { String js = "" + "/** @constructor */ function Top() {}\n" + "/** @constructor \n@extends Top*/ function Foo() {}\n" + "Foo.prototype.a;\n" + "/** @constructor \n@extends Top*/ function Bar() {}\n" + "Bar.prototype.a;\n" + "/** @param {Top} top */" + "function foo(top) {\n" + " var x = top.a;\n" + "}\n" + "foo(new Foo);\n" + "foo(new Bar);\n"; testSets(false, js, "{}"); testSets(true, js, "{a=[[Bar.prototype, Foo.prototype]]}"); } public void testSupertypeReferenceOfSubtypeProperty() { String externs = "" + "/** @constructor */ function Ext() {}" + "Ext.prototype.a;"; String js = "" + "/** @constructor */ function Foo() {}\n" + "/** @constructor \n@extends Foo*/ function Bar() {}\n" + "Bar.prototype.a;\n" + "/** @param {Foo} foo */" + "function foo(foo) {\n" + " var x = foo.a;\n" + "}\n"; String result = "" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype.Bar_prototype$a;\n" + "function foo(foo$$1) {\n" + " var x = foo$$1.Bar_prototype$a;\n" + "}\n"; testSets(false, externs, js, result, "{a=[[Bar.prototype]]}"); } public void testObjectLiteralNotRenamed() { String js = "" + "var F = {a:'a', b:'b'};" + "F.a = 'z';"; testSets(false, js, js, "{}"); testSets(true, js, js, "{}"); } public void testObjectLiteralReflected() { String js = "" + "var goog = {};" + "goog.reflect = {};" + "goog.reflect.object = function(x, y) { return y; };" + "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.foo = 3;" + "/** @constructor */ function G() {}" + "/** @type {number} */ G.prototype.foo = 3;" + "goog.reflect.object(F, {foo: 5});"; String result = "" + "var goog = {};" + "goog.reflect = {};" + "goog.reflect.object = function(x, y) { return y; };" + "function F() {}" + "F.prototype.F_prototype$foo = 3;" + "function G() {}" + "G.prototype.G_prototype$foo = 3;" + "goog.reflect.object(F, {F_prototype$foo: 5});"; testSets(false, js, result, "{foo=[[F.prototype], [G.prototype]]}"); testSets(true, js, result, "{foo=[[F.prototype], [G.prototype]]}"); } public void testObjectLiteralLends() { String js = "" + "var mixin = function(x) { return x; };" + "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.foo = 3;" + "/** @constructor */ function G() {}" + "/** @type {number} */ G.prototype.foo = 3;" + "mixin(/** @lends {F.prototype} */ ({foo: 5}));"; String result = "" + "var mixin = function(x) { return x; };" + "function F() {}" + "F.prototype.F_prototype$foo = 3;" + "function G() {}" + "G.prototype.G_prototype$foo = 3;" + "mixin(/** @lends {F.prototype} */ ({F_prototype$foo: 5}));"; testSets(false, js, result, "{foo=[[F.prototype], [G.prototype]]}"); testSets(true, js, result, "{foo=[[F.prototype], [G.prototype]]}"); } public void testClosureInherits() { String js = "" + "var goog = {};" + "/** @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class. */\n" + "goog.inherits = function(childCtor, parentCtor) {\n" + " /** @constructor */\n" + " function tempCtor() {};\n" + " tempCtor.prototype = parentCtor.prototype;\n" + " childCtor.superClass_ = parentCtor.prototype;\n" + " childCtor.prototype = new tempCtor();\n" + " childCtor.prototype.constructor = childCtor;\n" + "};" + "/** @constructor */ function Top() {}\n" + "Top.prototype.f = function() {};" + "/** @constructor \n@extends Top*/ function Foo() {}\n" + "goog.inherits(Foo, Top);\n" + "/** @override */\n" + "Foo.prototype.f = function() {" + " Foo.superClass_.f();" + "};\n" + "/** @constructor \n* @extends Foo */ function Bar() {}\n" + "goog.inherits(Bar, Foo);\n" + "/** @override */\n" + "Bar.prototype.f = function() {" + " Bar.superClass_.f();" + "};\n" + "(new Bar).f();\n"; testSets(false, js, "{f=[[Top.prototype]]}"); testSets(true, js, "{constructor=[[Bar.prototype, Foo.prototype]], " + "f=[[Bar.prototype], [Foo.prototype], [Top.prototype]]}"); } public void testSkipNativeFunctionMethod() { String externs = "" + "/** @constructor \n @param {*} var_args */" + "function Function(var_args) {}" + "Function.prototype.call = function() {};"; String js = "" + "/** @constructor */ function Foo(){};" + "/** @constructor\n @extends Foo */" + "function Bar() { Foo.call(this); };"; // call should not be renamed testSame(externs, js, null); } public void testSkipNativeObjectMethod() { String externs = "" + "/** @constructor \n @param {*} opt_v */ function Object(opt_v) {}" + "Object.prototype.hasOwnProperty;"; String js = "" + "/** @constructor */ function Foo(){};" + "(new Foo).hasOwnProperty('x');"; testSets(false, externs, js, js, "{}"); testSets(true, externs, js, js, "{}"); } public void testExtendNativeType() { String externs = "" + "/** @constructor \n @return {string} */" + "function Date(opt_1, opt_2, opt_3, opt_4, opt_5, opt_6, opt_7) {}" + "/** @override */ Date.prototype.toString = function() {}"; String js = "" + "/** @constructor\n @extends {Date} */ function SuperDate() {};\n" + "(new SuperDate).toString();"; testSets(true, externs, js, js, "{}"); testSets(false, externs, js, js, "{}"); } public void testStringFunction() { // Extern functions are not renamed, but user functions on a native // prototype object are. String externs = "/**@constructor\n@param {*} opt_str \n @return {string}*/" + "function String(opt_str) {};\n" + "/** @override \n @return {string} */\n" + "String.prototype.toString = function() { };\n"; String js = "" + "/** @constructor */ function Foo() {};\n" + "Foo.prototype.foo = function() {};\n" + "String.prototype.foo = function() {};\n" + "var a = 'str'.toString().foo();\n"; String output = "" + "function Foo() {};\n" + "Foo.prototype.Foo_prototype$foo = function() {};\n" + "String.prototype.String_prototype$foo = function() {};\n" + "var a = 'str'.toString().String_prototype$foo();\n"; testSets(false, externs, js, output, "{foo=[[Foo.prototype], [String.prototype]]}"); testSets(true, externs, js, output, "{foo=[[Foo.prototype], [String.prototype]]}"); } public void testUnusedTypeInExterns() { String externs = "" + "/** @constructor */ function Foo() {};\n" + "Foo.prototype.a"; String js = "" + "/** @constructor */ function Bar() {};\n" + "Bar.prototype.a;" + "/** @constructor */ function Baz() {};\n" + "Baz.prototype.a;"; String output = "" + "/** @constructor */ function Bar() {};\n" + "Bar.prototype.Bar_prototype$a;" + "/** @constructor */ function Baz() {};\n" + "Baz.prototype.Baz_prototype$a"; testSets(false, externs, js, output, "{a=[[Bar.prototype], [Baz.prototype]]}"); testSets(true, externs, js, output, "{a=[[Bar.prototype], [Baz.prototype]]}"); } public void testInterface() { String js = "" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n" + "/** @constructor \n @implements I */ function Foo() {};\n" + "Foo.prototype.a;\n" + "/** @type I */\n" + "var F = new Foo;" + "var x = F.a;"; testSets(false, js, "{a=[[Foo.prototype, I.prototype]]}"); testSets(true, js, "{a=[[Foo.prototype], [I.prototype]]}"); } public void testInterfaceOfSuperclass() { String js = "" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n" + "/** @constructor \n @implements I */ function Foo() {};\n" + "Foo.prototype.a;\n" + "/** @constructor \n @extends Foo */ function Bar() {};\n" + "Bar.prototype.a;\n" + "/** @type Bar */\n" + "var B = new Bar;" + "B.a = 0"; testSets(false, js, "{a=[[Foo.prototype, I.prototype]]}"); testSets(true, js, "{a=[[Bar.prototype], [Foo.prototype], [I.prototype]]}"); } public void testTwoInterfacesWithSomeInheritance() { String js = "" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n" + "/** @interface */ function I2() {};\n" + "I2.prototype.a;\n" + "/** @constructor \n @implements I */ function Foo() {};\n" + "Foo.prototype.a;\n" + "/** @constructor \n @extends Foo \n @implements I2*/\n" + "function Bar() {};\n" + "Bar.prototype.a;\n" + "/** @type Bar */\n" + "var B = new Bar;" + "B.a = 0"; testSets(false, js, "{a=[[Foo.prototype, I.prototype, I2.prototype]]}"); testSets(true, js, "{a=[[Bar.prototype], [Foo.prototype], " + "[I.prototype], [I2.prototype]]}"); } public void testInvalidatingInterface() { String js = "" + "/** @interface */ function I2() {};\n" + "I2.prototype.a;\n" + "/** @constructor */ function Bar() {}\n" + "/** @type I */\n" + "var i = new Bar;\n" // Make I invalidating + "/** @constructor \n @implements I \n @implements I2 */" + "function Foo() {};\n" + "/** @override */\n" + "Foo.prototype.a = 0;\n" + "(new Foo).a = 0;" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n"; testSets(false, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING); testSets(true, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING); } public void testMultipleInterfaces() { String js = "" + "/** @interface */ function I() {};\n" + "/** @interface */ function I2() {};\n" + "I2.prototype.a;\n" + "/** @constructor \n @implements I \n @implements I2 */" + "function Foo() {};\n" + "/** @override */" + "Foo.prototype.a = 0;\n" + "(new Foo).a = 0"; testSets(false, js, "{a=[[Foo.prototype, I2.prototype]]}"); testSets(true, js, "{a=[[Foo.prototype], [I2.prototype]]}"); } public void testInterfaceWithSupertypeImplementor() { String js = "" + "/** @interface */ function C() {}\n" + "C.prototype.foo = function() {};\n" + "/** @constructor */ function A (){}\n" + "A.prototype.foo = function() {};\n" + "/** @constructor \n @implements {C} \n @extends {A} */\n" + "function B() {}\n" + "/** @type {C} */ var b = new B();\n" + "b.foo();\n"; testSets(false, js, "{foo=[[A.prototype, C.prototype]]}"); testSets(true, js, "{foo=[[A.prototype], [C.prototype]]}"); } public void testSuperInterface() { String js = "" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n" + "/** @interface \n @extends I */ function I2() {};\n" + "/** @constructor \n @implements I2 */" + "function Foo() {};\n" + "/** @override */\n" + "Foo.prototype.a = 0;\n" + "(new Foo).a = 0"; testSets(false, js, "{a=[[Foo.prototype, I.prototype]]}"); testSets(true, js, "{a=[[Foo.prototype], [I.prototype]]}"); } public void testInterfaceUnionWithCtor() { String js = "" + "/** @interface */ function I() {};\n" + "/** @type {!Function} */ I.prototype.addEventListener;\n" + "/** @constructor \n * @implements {I} */ function Impl() {};\n" + "/** @type {!Function} */ Impl.prototype.addEventListener;" + "/** @constructor */ function C() {};\n" + "/** @type {!Function} */ C.prototype.addEventListener;" + "/** @param {C|I} x */" + "function f(x) { x.addEventListener(); };\n" + "f(new C()); f(new Impl());"; testSets(false, js, js, "{addEventListener=[[C.prototype, I.prototype, Impl.prototype]]}"); // In the tightened case, the disambiguator is smart enough to // disambiguate Impl's method from the interface method. String tightenedOutput = "" + "function I() {};\n" + "I.prototype.I_prototype$addEventListener;\n" + "function Impl() {};\n" + "Impl.prototype.C_prototype$addEventListener;" + "function C() {};\n" + "C.prototype.C_prototype$addEventListener;" + "/** @param {C|I} x */" + "function f(x) { x.C_prototype$addEventListener(); };\n" + "f(new C()); f(new Impl());"; testSets(true, js, tightenedOutput, "{addEventListener=[[C.prototype, Impl.prototype], [I.prototype]]}"); } public void testExternInterfaceUnionWithCtor() { String externs = "" + "/** @interface */ function I() {};\n" + "/** @type {!Function} */ I.prototype.addEventListener;\n" + "/** @constructor \n * @implements {I} */ function Impl() {};\n" + "/** @type {!Function} */ Impl.prototype.addEventListener;"; String js = "" + "/** @constructor */ function C() {};\n" + "/** @type {!Function} */ C.prototype.addEventListener;" + "/** @param {C|I} x */" + "function f(x) { x.addEventListener(); };\n" + "f(new C()); f(new Impl());"; testSets(false, externs, js, js, "{}"); testSets(true, externs, js, js, "{}"); } /** * Tests that the type based version skips renaming on types that have a * mismatch, and the type tightened version continues to work as normal. */ public void testMismatchInvalidation() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;\n" + "/** @type Foo */\n" + "var F = new Bar;\n" + "F.a = 0;"; testSets(false, "", js, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING, "initializing variable\n" + "found : Bar\n" + "required: (Foo|null)"); testSets(true, "", js, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING, "initializing variable\n" + "found : Bar\n" + "required: (Foo|null)"); } public void testBadCast() { String js = "/** @constructor */ function Foo() {};\n" + "Foo.prototype.a = 0;\n" + "/** @constructor */ function Bar() {};\n" + "Bar.prototype.a = 0;\n" + "var a = /** @type {!Foo} */ (new Bar);\n" + "a.a = 4;"; testSets(false, "", js, js, "{}", TypeValidator.INVALID_CAST, "invalid cast - must be a subtype or supertype\n" + "from: Bar\n" + "to : Foo"); } public void testDeterministicNaming() { String js = "/** @constructor */function A() {}\n" + "/** @return {string} */A.prototype.f = function() {return 'a';};\n" + "/** @constructor */function B() {}\n" + "/** @return {string} */B.prototype.f = function() {return 'b';};\n" + "/** @constructor */function C() {}\n" + "/** @return {string} */C.prototype.f = function() {return 'c';};\n" + "/** @type {A|B} */var ab = 1 ? new B : new A;\n" + "/** @type {string} */var n = ab.f();\n"; String output = "function A() {}\n" + "A.prototype.A_prototype$f = function() { return'a'; };\n" + "function B() {}\n" + "B.prototype.A_prototype$f = function() { return'b'; };\n" + "function C() {}\n" + "C.prototype.C_prototype$f = function() { return'c'; };\n" + "var ab = 1 ? new B : new A; var n = ab.A_prototype$f();\n"; for (int i = 0; i < 5; i++) { testSets(false, js, output, "{f=[[A.prototype, B.prototype], [C.prototype]]}"); testSets(true, js, output, "{f=[[A.prototype, B.prototype], [C.prototype]]}"); } } public void testObjectLiteral() { String js = "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a;\n" + "var F = /** @type {Foo} */({ a: 'a' });\n"; String output = "function Foo() {}\n" + "Foo.prototype.Foo_prototype$a;\n" + "function Bar() {}\n" + "Bar.prototype.Bar_prototype$a;\n" + "var F = { Foo_prototype$a: 'a' };\n"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testCustomInherits() { String js = "Object.prototype.inheritsFrom = function(shuper) {\n" + " /** @constructor */\n" + " function Inheriter() { }\n" + " Inheriter.prototype = shuper.prototype;\n" + " this.prototype = new Inheriter();\n" + " this.superConstructor = shuper;\n" + "};\n" + "function Foo(var1, var2, strength) {\n" + " Foo.superConstructor.call(this, strength);\n" + "}" + "Foo.inheritsFrom(Object);"; String externs = "" + "function Function(var_args) {}" + "/** @return {*} */Function.prototype.call = function(var_args) {};"; testSets(false, externs, js, js, "{}"); } public void testSkipNativeFunctionStaticProperty() { String js = "" + "/** @param {!Function} ctor */\n" + "function addSingletonGetter(ctor) { ctor.a; }\n" + "/** @constructor */ function Foo() {}\n" + "Foo.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.a = 0;"; String output = "" + "function addSingletonGetter(ctor){ctor.a}" + "function Foo(){}" + "Foo.a=0;" + "function Bar(){}" + "Bar.a=0"; testSets(false, js, output, "{}"); } public void testErrorOnProtectedProperty() { test("function addSingletonGetter(foo) { foo.foobar = 'a'; };", null, DisambiguateProperties.Warnings.INVALIDATION); assertTrue(getLastCompiler().getErrors()[0].toString().contains("foobar")); } public void testMismatchForbiddenInvalidation() { test("/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.foobar = 3;" + "/** @return {number} */ function g() { return new F(); }", null, DisambiguateProperties.Warnings.INVALIDATION); assertTrue(getLastCompiler().getErrors()[0].toString() .contains("Consider fixing errors")); } public void testUnionTypeInvalidationError() { String externs = "" + "/** @constructor */ function Baz() {}" + "Baz.prototype.foobar"; String js = "" + "/** @constructor */ function Ind() {this.foobar=0}\n" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foobar = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.foobar = 0;\n" + "/** @type {Foo|Bar} */\n" + "var F = new Foo;\n" + "F.foobar = 1\n;" + "F = new Bar;\n" + "/** @type {Baz} */\n" + "var Z = new Baz;\n" + "Z.foobar = 1\n;"; test( externs, js, "", DisambiguateProperties.Warnings.INVALIDATION_ON_TYPE, null); assertTrue(getLastCompiler().getErrors()[0].toString() .contains("foobar")); } public void runFindHighestTypeInChain() { // Check that this doesn't go into an infinite loop. DisambiguateProperties.forJSTypeSystem(new Compiler(), Maps.<String, CheckLevel>newHashMap()) .getTypeWithProperty("no", new JSTypeRegistry(new TestErrorReporter(null, null)) .getNativeType(JSTypeNative.OBJECT_PROTOTYPE)); } @SuppressWarnings("unchecked") private void testSets(boolean runTightenTypes, String js, String expected, String fieldTypes) { this.runTightenTypes = runTightenTypes; test(js, expected); assertEquals( fieldTypes, mapToString(lastPass.getRenamedTypesForTesting())); } @SuppressWarnings("unchecked") private void testSets(boolean runTightenTypes, String externs, String js, String expected, String fieldTypes) { testSets(runTightenTypes, externs, js, expected, fieldTypes, null, null); } @SuppressWarnings("unchecked") private void testSets(boolean runTightenTypes, String externs, String js, String expected, String fieldTypes, DiagnosticType warning, String description) { this.runTightenTypes = runTightenTypes; test(externs, js, expected, null, warning, description); assertEquals( fieldTypes, mapToString(lastPass.getRenamedTypesForTesting())); } /** * Compiles the code and checks that the set of types for each field matches * the expected value. * * <p>The format for the set of types for fields is: * {field=[[Type1, Type2]]} */ private void testSets(boolean runTightenTypes, String js, String fieldTypes) { this.runTightenTypes = runTightenTypes; test(js, null, null, null); assertEquals(fieldTypes, mapToString(lastPass.getRenamedTypesForTesting())); } /** * Compiles the code and checks that the set of types for each field matches * the expected value. * * <p>The format for the set of types for fields is: * {field=[[Type1, Type2]]} */ private void testSets(boolean runTightenTypes, String js, String fieldTypes, DiagnosticType warning) { this.runTightenTypes = runTightenTypes; test(js, null, null, warning); assertEquals(fieldTypes, mapToString(lastPass.getRenamedTypesForTesting())); } /** Sorts the map and converts to a string for comparison purposes. */ private <T> String mapToString(Multimap<String, Collection<T>> map) { TreeMap<String, String> retMap = Maps.newTreeMap(); for (String key : map.keySet()) { TreeSet<String> treeSet = Sets.newTreeSet(); for (Collection<T> collection : map.get(key)) { Set<String> subSet = Sets.newTreeSet(); for (T type : collection) { subSet.add(type.toString()); } treeSet.add(subSet.toString()); } retMap.put(key, treeSet.toString()); } return retMap.toString(); } }
// You are a professional Java test case writer, please create a test case named `testOneType4` for the issue `Closure-1024`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1024 // // ## Issue-Title: // Prototype method incorrectly removed // // ## Issue-Description: // // ==ClosureCompiler== // // @compilation\_level ADVANCED\_OPTIMIZATIONS // // @output\_file\_name default.js // // @formatting pretty\_print // // ==/ClosureCompiler== // // /\*\* @const \*/ // var foo = {}; // foo.bar = { // 'bar1': function() { console.log('bar1'); } // } // // /\*\* @constructor \*/ // function foobar() {} // foobar.prototype = foo.bar; // // foo.foobar = new foobar; // // console.log(foo.foobar['bar1']); // // public void testOneType4() {
129
118
119
test/com/google/javascript/jscomp/DisambiguatePropertiesTest.java
test
```markdown ## Issue-ID: Closure-1024 ## Issue-Title: Prototype method incorrectly removed ## Issue-Description: // ==ClosureCompiler== // @compilation\_level ADVANCED\_OPTIMIZATIONS // @output\_file\_name default.js // @formatting pretty\_print // ==/ClosureCompiler== /\*\* @const \*/ var foo = {}; foo.bar = { 'bar1': function() { console.log('bar1'); } } /\*\* @constructor \*/ function foobar() {} foobar.prototype = foo.bar; foo.foobar = new foobar; console.log(foo.foobar['bar1']); ``` You are a professional Java test case writer, please create a test case named `testOneType4` for the issue `Closure-1024`, utilizing the provided issue report information and the following function signature. ```java public void testOneType4() { ```
119
[ "com.google.javascript.jscomp.DisambiguateProperties" ]
1d50ee35cebcf6452f7cdf1d7eafed61f5a114b96f1659e2a13211be5e20ccfb
public void testOneType4()
// You are a professional Java test case writer, please create a test case named `testOneType4` for the issue `Closure-1024`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1024 // // ## Issue-Title: // Prototype method incorrectly removed // // ## Issue-Description: // // ==ClosureCompiler== // // @compilation\_level ADVANCED\_OPTIMIZATIONS // // @output\_file\_name default.js // // @formatting pretty\_print // // ==/ClosureCompiler== // // /\*\* @const \*/ // var foo = {}; // foo.bar = { // 'bar1': function() { console.log('bar1'); } // } // // /\*\* @constructor \*/ // function foobar() {} // foobar.prototype = foo.bar; // // foo.foobar = new foobar; // // console.log(foo.foobar['bar1']); // //
Closure
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import com.google.javascript.rhino.testing.TestErrorReporter; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * Unit test for the Compiler DisambiguateProperties pass. * */ public class DisambiguatePropertiesTest extends CompilerTestCase { private DisambiguateProperties<?> lastPass; private boolean runTightenTypes; public DisambiguatePropertiesTest() { parseTypeInfo = true; } @Override protected void setUp() throws Exception { super.setUp(); super.enableNormalize(true); super.enableTypeCheck(CheckLevel.WARNING); } @Override public CompilerPass getProcessor(final Compiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { Map<String, CheckLevel> propertiesToErrorFor = Maps.<String, CheckLevel>newHashMap(); propertiesToErrorFor.put("foobar", CheckLevel.ERROR); if (runTightenTypes) { TightenTypes tightener = new TightenTypes(compiler); tightener.process(externs, root); lastPass = DisambiguateProperties.forConcreteTypeSystem(compiler, tightener, propertiesToErrorFor); } else { // This must be created after type checking is run as it depends on // any mismatches found during checking. lastPass = DisambiguateProperties.forJSTypeSystem( compiler, propertiesToErrorFor); } lastPass.process(externs, root); } }; } @Override protected int getNumRepetitions() { return 1; } public void testOneType1() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;"; testSets(false, js, js, "{a=[[Foo.prototype]]}"); testSets(true, js, js, "{a=[[Foo.prototype]]}"); } public void testOneType2() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {a: 0};\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;"; String expected = "{a=[[Foo.prototype]]}"; testSets(false, js, js, expected); testSets(true, js, js, expected); } public void testOneType3() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = { get a() {return 0}," + " set a(b) {} };\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;"; String expected = "{a=[[Foo.prototype]]}"; testSets(false, js, js, expected); testSets(true, js, js, expected); } public void testOneType4() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {'a': 0};\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F['a'] = 0;"; String expected = "{}"; testSets(false, js, js, expected); testSets(true, js, js, expected); } public void testPrototypeAndInstance() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;"; testSets(false, js, js, "{a=[[Foo.prototype]]}"); testSets(true, js, js, "{a=[[Foo.prototype]]}"); } public void testPrototypeAndInstance2() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "new Foo().a = 0;"; testSets(false, js, js, "{a=[[Foo.prototype]]}"); testSets(true, js, js, "{a=[[Foo.prototype]]}"); } public void testTwoTypes1() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B.a = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype.Foo_prototype$a=0;" + "var F=new Foo;" + "F.Foo_prototype$a=0;" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "var B=new Bar;" + "B.Bar_prototype$a=0"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testTwoTypes2() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {a: 0};" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype = {a: 0};" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B.a = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype = {Foo_prototype$a: 0};" + "var F=new Foo;" + "F.Foo_prototype$a=0;" + "function Bar(){}" + "Bar.prototype = {Bar_prototype$a: 0};" + "var B=new Bar;" + "B.Bar_prototype$a=0"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testTwoTypes3() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = { get a() {return 0}," + " set a(b) {} };\n" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype = { get a() {return 0}," + " set a(b) {} };\n" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B.a = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype = { get Foo_prototype$a() {return 0}," + " set Foo_prototype$a(b) {} };\n" + "var F=new Foo;" + "F.Foo_prototype$a=0;" + "function Bar(){}" + "Bar.prototype = { get Bar_prototype$a() {return 0}," + " set Bar_prototype$a(b) {} };\n" + "var B=new Bar;" + "B.Bar_prototype$a=0"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testTwoTypes4() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype = {a: 0};" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype = {'a': 0};" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B['a'] = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype = {a: 0};" + "var F=new Foo;" + "F.a=0;" + "function Bar(){}" + "Bar.prototype = {'a': 0};" + "var B=new Bar;" + "B['a']=0"; testSets(false, js, output, "{a=[[Foo.prototype]]}"); testSets(true, js, output, "{a=[[Foo.prototype]]}"); } public void testTwoFields() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "Foo.prototype.b = 0;" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "F.b = 0;"; String output = "function Foo(){}Foo.prototype.a=0;Foo.prototype.b=0;" + "var F=new Foo;F.a=0;F.b=0"; testSets(false, js, output, "{a=[[Foo.prototype]], b=[[Foo.prototype]]}"); testSets(true, js, output, "{a=[[Foo.prototype]], b=[[Foo.prototype]]}"); } public void testTwoSeparateFieldsTwoTypes() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "Foo.prototype.b = 0;" + "/** @type Foo */\n" + "var F = new Foo;\n" + "F.a = 0;" + "F.b = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "Bar.prototype.b = 0;" + "/** @type Bar */\n" + "var B = new Bar;\n" + "B.a = 0;" + "B.b = 0;"; String output = "" + "function Foo(){}" + "Foo.prototype.Foo_prototype$a=0;" + "Foo.prototype.Foo_prototype$b=0;" + "var F=new Foo;" + "F.Foo_prototype$a=0;" + "F.Foo_prototype$b=0;" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "Bar.prototype.Bar_prototype$b=0;" + "var B=new Bar;" + "B.Bar_prototype$a=0;" + "B.Bar_prototype$b=0"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]," + " b=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]," + " b=[[Bar.prototype], [Foo.prototype]]}"); } public void testUnionType() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "/** @type {Bar|Foo} */\n" + "var B = new Bar;\n" + "B.a = 0;\n" + "B = new Foo;\n" + "B.a = 0;\n" + "/** @constructor */ function Baz() {}\n" + "Baz.prototype.a = 0;\n"; testSets(false, js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}"); testSets(true, js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}"); } public void testIgnoreUnknownType() { String js = "" + "/** @constructor */\n" + "function Foo() {}\n" + "Foo.prototype.blah = 3;\n" + "/** @type {Foo} */\n" + "var F = new Foo;\n" + "F.blah = 0;\n" + "var U = function() { return {} };\n" + "U().blah();"; String expected = "" + "function Foo(){}Foo.prototype.blah=3;var F = new Foo;F.blah=0;" + "var U=function(){return{}};U().blah()"; testSets(false, js, expected, "{}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, expected, "{}"); } public void testIgnoreUnknownType1() { String js = "" + "/** @constructor */\n" + "function Foo() {}\n" + "Foo.prototype.blah = 3;\n" + "/** @type {Foo} */\n" + "var F = new Foo;\n" + "F.blah = 0;\n" + "/** @return {Object} */\n" + "var U = function() { return {} };\n" + "U().blah();"; String expected = "" + "function Foo(){}Foo.prototype.blah=3;var F = new Foo;F.blah=0;" + "var U=function(){return{}};U().blah()"; testSets(false, js, expected, "{blah=[[Foo.prototype]]}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, expected, "{}"); } public void testIgnoreUnknownType2() { String js = "" + "/** @constructor */\n" + "function Foo() {}\n" + "Foo.prototype.blah = 3;\n" + "/** @type {Foo} */\n" + "var F = new Foo;\n" + "F.blah = 0;\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype.blah = 3;\n" + "/** @return {Object} */\n" + "var U = function() { return {} };\n" + "U().blah();"; String expected = "" + "function Foo(){}Foo.prototype.blah=3;var F = new Foo;F.blah=0;" + "function Bar(){}Bar.prototype.blah=3;" + "var U=function(){return{}};U().blah()"; testSets(false, js, expected, "{}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, expected, "{}"); } public void testUnionTypeTwoFields() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "Foo.prototype.b = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;\n" + "Bar.prototype.b = 0;\n" + "/** @type {Foo|Bar} */\n" + "var B = new Bar;\n" + "B.a = 0;\n" + "B.b = 0;\n" + "B = new Foo;\n" + "/** @constructor */ function Baz() {}\n" + "Baz.prototype.a = 0;\n" + "Baz.prototype.b = 0;\n"; testSets(false, js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]," + " b=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}"); testSets(true, js, "{a=[[Bar.prototype, Foo.prototype], [Baz.prototype]]," + " b=[[Bar.prototype, Foo.prototype], [Baz.prototype]]}"); } public void testCast() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "/** @type {Foo|Bar} */\n" + "var F = new Foo;\n" + "(/** @type {Bar} */(F)).a = 0;"; String output = "" + "function Foo(){}Foo.prototype.Foo_prototype$a=0;" + "function Bar(){}Bar.prototype.Bar_prototype$a=0;" + "var F=new Foo;F.Bar_prototype$a=0;"; String ttOutput = "" + "function Foo(){}Foo.prototype.Foo_prototype$a=0;" + "function Bar(){}Bar.prototype.Bar_prototype$a=0;" + "var F=new Foo;F.Unique$1$a=0;"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, ttOutput, "{a=[[Bar.prototype], [Foo.prototype], [Unique$1]]}"); } public void testConstructorFields() { String js = "" + "/** @constructor */\n" + "var Foo = function() { this.a = 0; };\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;" + "new Foo"; String output = "" + "var Foo=function(){this.Foo$a=0};" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "new Foo"; String ttOutput = "" + "var Foo=function(){this.Foo_prototype$a=0};" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "new Foo"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo]]}"); testSets(true, js, ttOutput, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testStaticProperty() { String js = "" + "/** @constructor */ function Foo() {} \n" + "/** @constructor */ function Bar() {}\n" + "Foo.a = 0;" + "Bar.a = 0;"; String output = "" + "function Foo(){}" + "function Bar(){}" + "Foo.function__new_Foo___undefined$a = 0;" + "Bar.function__new_Bar___undefined$a = 0;"; testSets(false, js, output, "{a=[[function (new:Bar): undefined]," + " [function (new:Foo): undefined]]}"); } public void testSupertypeWithSameField() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @constructor\n* @extends Foo */ function Bar() {}\n" + "/** @override */\n" + "Bar.prototype.a = 0;\n" + "/** @type Bar */ var B = new Bar;\n" + "B.a = 0;" + "/** @constructor */ function Baz() {}\n" + "Baz.prototype.a = function(){};\n"; String output = "" + "function Foo(){}Foo.prototype.Foo_prototype$a=0;" + "function Bar(){}Bar.prototype.Foo_prototype$a=0;" + "var B = new Bar;B.Foo_prototype$a=0;" + "function Baz(){}Baz.prototype.Baz_prototype$a=function(){};"; String ttOutput = "" + "function Foo(){}Foo.prototype.Foo_prototype$a=0;" + "function Bar(){}Bar.prototype.Bar_prototype$a=0;" + "var B = new Bar;B.Bar_prototype$a=0;" + "function Baz(){}Baz.prototype.Baz_prototype$a=function(){};"; testSets(false, js, output, "{a=[[Baz.prototype], [Foo.prototype]]}"); testSets(true, js, ttOutput, "{a=[[Bar.prototype], [Baz.prototype], [Foo.prototype]]}"); } public void testScopedType() { String js = "" + "var g = {};\n" + "/** @constructor */ g.Foo = function() {}\n" + "g.Foo.prototype.a = 0;" + "/** @constructor */ g.Bar = function() {}\n" + "g.Bar.prototype.a = 0;"; String output = "" + "var g={};" + "g.Foo=function(){};" + "g.Foo.prototype.g_Foo_prototype$a=0;" + "g.Bar=function(){};" + "g.Bar.prototype.g_Bar_prototype$a=0;"; testSets(false, js, output, "{a=[[g.Bar.prototype], [g.Foo.prototype]]}"); testSets(true, js, output, "{a=[[g.Bar.prototype], [g.Foo.prototype]]}"); } public void testUnresolvedType() { // NOTE(nicksantos): This behavior seems very wrong to me. String js = "" + "var g = {};" + "/** @constructor \n @extends {?} */ " + "var Foo = function() {};\n" + "Foo.prototype.a = 0;" + "/** @constructor */ var Bar = function() {};\n" + "Bar.prototype.a = 0;"; String output = "" + "var g={};" + "var Foo=function(){};" + "Foo.prototype.Foo_prototype$a=0;" + "var Bar=function(){};" + "Bar.prototype.Bar_prototype$a=0;"; setExpectParseWarningsThisTest(); testSets(false, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testNamedType() { String js = "" + "var g = {};" + "/** @constructor \n @extends g.Late */ var Foo = function() {}\n" + "Foo.prototype.a = 0;" + "/** @constructor */ var Bar = function() {}\n" + "Bar.prototype.a = 0;" + "/** @constructor */ g.Late = function() {}"; String output = "" + "var g={};" + "var Foo=function(){};" + "Foo.prototype.Foo_prototype$a=0;" + "var Bar=function(){};" + "Bar.prototype.Bar_prototype$a=0;" + "g.Late = function(){}"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testUnknownType() { String js = "" + "/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Bar = function() {};\n" + "/** @return {?} */ function fun() {}\n" + "Foo.prototype.a = fun();\n" + "fun().a;\n" + "Bar.prototype.a = 0;"; String ttOutput = "" + "var Foo=function(){};\n" + "var Bar=function(){};\n" + "function fun(){}\n" + "Foo.prototype.Foo_prototype$a=fun();\n" + "fun().Unique$1$a;\n" + "Bar.prototype.Bar_prototype$a=0;"; testSets(false, js, js, "{}"); testSets(true, BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES, js, ttOutput, "{a=[[Bar.prototype], [Foo.prototype], [Unique$1]]}"); } public void testEnum() { String js = "" + "/** @enum {string} */ var En = {\n" + " A: 'first',\n" + " B: 'second'\n" + "};\n" + "var EA = En.A;\n" + "var EB = En.B;\n" + "/** @constructor */ function Foo(){};\n" + "Foo.prototype.A = 0;\n" + "Foo.prototype.B = 0;\n"; String output = "" + "var En={A:'first',B:'second'};" + "var EA=En.A;" + "var EB=En.B;" + "function Foo(){};" + "Foo.prototype.Foo_prototype$A=0;" + "Foo.prototype.Foo_prototype$B=0"; String ttOutput = "" + "var En={A:'first',B:'second'};" + "var EA=En.A;" + "var EB=En.B;" + "function Foo(){};" + "Foo.prototype.Foo_prototype$A=0;" + "Foo.prototype.Foo_prototype$B=0"; testSets(false, js, output, "{A=[[Foo.prototype]], B=[[Foo.prototype]]}"); testSets(true, js, ttOutput, "{A=[[Foo.prototype]], B=[[Foo.prototype]]}"); } public void testEnumOfObjects() { String js = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.format = function() {};" + "/** @enum {!Formatter} */ var Enum = {\n" + " A: new Formatter()\n" + "};\n" + "Enum.A.format();\n"; String output = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.Formatter_prototype$format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.Unrelated_prototype$format = function() {};" + "/** @enum {!Formatter} */ var Enum = {\n" + " A: new Formatter()\n" + "};\n" + "Enum.A.Formatter_prototype$format();\n"; testSets(false, js, output, "{format=[[Formatter.prototype], [Unrelated.prototype]]}"); // TODO(nicksantos): Fix the type tightener to handle this case. // It currently doesn't work, because getSubTypes is broken for enums. } public void testEnumOfObjects2() { String js = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.format = function() {};" + "/** @enum {?Formatter} */ var Enum = {\n" + " A: new Formatter(),\n" + " B: new Formatter()\n" + "};\n" + "function f() {\n" + " var formatter = window.toString() ? Enum.A : Enum.B;\n" + " formatter.format();\n" + "}"; String output = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.format = function() {};" + "/** @enum {?Formatter} */ var Enum = {\n" + " A: new Formatter(),\n" + " B: new Formatter()\n" + "};\n" + "function f() {\n" + " var formatter = window.toString() ? Enum.A : Enum.B;\n" + " formatter.format();\n" + "}"; testSets(false, js, output, "{}"); } public void testEnumOfObjects3() { String js = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.format = function() {};" + "/** @enum {!Formatter} */ var Enum = {\n" + " A: new Formatter(),\n" + " B: new Formatter()\n" + "};\n" + "/** @enum {!Enum} */ var SubEnum = {\n" + " C: Enum.A\n" + "};\n" + "function f() {\n" + " var formatter = SubEnum.C\n" + " formatter.format();\n" + "}"; String output = "" + "/** @constructor */ function Formatter() {}" + "Formatter.prototype.Formatter_prototype$format = function() {};" + "/** @constructor */ function Unrelated() {}" + "Unrelated.prototype.Unrelated_prototype$format = function() {};" + "/** @enum {!Formatter} */ var Enum = {\n" + " A: new Formatter(),\n" + " B: new Formatter()\n" + "};\n" + "/** @enum {!Enum} */ var SubEnum = {\n" + " C: Enum.A\n" + "};\n" + "function f() {\n" + " var formatter = SubEnum.C\n" + " formatter.Formatter_prototype$format();\n" + "}"; testSets(false, js, output, "{format=[[Formatter.prototype], [Unrelated.prototype]]}"); } public void testUntypedExterns() { String externs = BaseJSTypeTestCase.ALL_NATIVE_EXTERN_TYPES + "var window;" + "window.alert = function() {x};"; String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "Foo.prototype.alert = 0;\n" + "Foo.prototype.window = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;\n" + "Bar.prototype.alert = 0;\n" + "Bar.prototype.window = 0;\n" + "window.alert();"; String output = "" + "function Foo(){}" + "Foo.prototype.Foo_prototype$a=0;" + "Foo.prototype.alert=0;" + "Foo.prototype.Foo_prototype$window=0;" + "function Bar(){}" + "Bar.prototype.Bar_prototype$a=0;" + "Bar.prototype.alert=0;" + "Bar.prototype.Bar_prototype$window=0;" + "window.alert();"; testSets(false, externs, js, output, "{a=[[Bar.prototype], [Foo.prototype]]" + ", window=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, externs, js, output, "{a=[[Bar.prototype], [Foo.prototype]]," + " window=[[Bar.prototype], [Foo.prototype]]}"); } public void testUnionTypeInvalidation() { String externs = "" + "/** @constructor */ function Baz() {}" + "Baz.prototype.a"; String js = "" + "/** @constructor */ function Ind() {this.a=0}\n" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;\n" + "/** @type {Foo|Bar} */\n" + "var F = new Foo;\n" + "F.a = 1\n;" + "F = new Bar;\n" + "/** @type {Baz} */\n" + "var Z = new Baz;\n" + "Z.a = 1\n;" + "/** @type {Bar|Baz} */\n" + "var B = new Baz;\n" + "B.a = 1;\n" + "B = new Bar;\n"; // Only the constructor field a of Ind is renamed, as Foo is related to Baz // through Bar in the unions Bar|Baz and Foo|Bar. String output = "" + "function Ind() { this.Ind$a = 0; }" + "function Foo() {}" + "Foo.prototype.a = 0;" + "function Bar() {}" + "Bar.prototype.a = 0;" + "var F = new Foo;" + "F.a = 1;" + "F = new Bar;" + "var Z = new Baz;" + "Z.a = 1;" + "var B = new Baz;" + "B.a = 1;" + "B = new Bar;"; String ttOutput = "" + "function Ind() { this.Unique$1$a = 0; }" + "function Foo() {}" + "Foo.prototype.a = 0;" + "function Bar() {}" + "Bar.prototype.a = 0;" + "var F = new Foo;" + "F.a = 1;" + "F = new Bar;" + "var Z = new Baz;" + "Z.a = 1;" + "var B = new Baz;" + "B.a = 1;" + "B = new Bar;"; testSets(false, externs, js, output, "{a=[[Ind]]}"); testSets(true, externs, js, ttOutput, "{a=[[Unique$1]]}"); } public void testUnionAndExternTypes() { String externs = "" + "/** @constructor */ function Foo() { }" + "Foo.prototype.a = 4;\n"; String js = "" + "/** @constructor */ function Bar() { this.a = 2; }\n" + "/** @constructor */ function Baz() { this.a = 3; }\n" + "/** @constructor */ function Buz() { this.a = 4; }\n" + "/** @constructor */ function T1() { this.a = 3; }\n" + "/** @constructor */ function T2() { this.a = 3; }\n" + "/** @type {Bar|Baz} */ var b;\n" + "/** @type {Baz|Buz} */ var c;\n" + "/** @type {Buz|Foo} */ var d;\n" + "b.a = 5; c.a = 6; d.a = 7;"; String output = "" + "/** @constructor */ function Bar() { this.a = 2; }\n" + "/** @constructor */ function Baz() { this.a = 3; }\n" + "/** @constructor */ function Buz() { this.a = 4; }\n" + "/** @constructor */ function T1() { this.T1$a = 3; }\n" + "/** @constructor */ function T2() { this.T2$a = 3; }\n" + "/** @type {Bar|Baz} */ var b;\n" + "/** @type {Baz|Buz} */ var c;\n" + "/** @type {Buz|Foo} */ var d;\n" + "b.a = 5; c.a = 6; d.a = 7;"; // We are testing the skipping of multiple types caused by unionizing with // extern types. testSets(false, externs, js, output, "{a=[[T1], [T2]]}"); } public void testTypedExterns() { String externs = "" + "/** @constructor */ function Window() {};\n" + "Window.prototype.alert;" + "/** @type {Window} */" + "var window;"; String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.alert = 0;\n" + "window.alert('blarg');"; String output = "" + "function Foo(){}" + "Foo.prototype.Foo_prototype$alert=0;" + "window.alert('blarg');"; testSets(false, externs, js, output, "{alert=[[Foo.prototype]]}"); testSets(true, externs, js, output, "{alert=[[Foo.prototype]]}"); } public void testSubtypesWithSameField() { String js = "" + "/** @constructor */ function Top() {}\n" + "/** @constructor \n@extends Top*/ function Foo() {}\n" + "Foo.prototype.a;\n" + "/** @constructor \n@extends Top*/ function Bar() {}\n" + "Bar.prototype.a;\n" + "/** @param {Top} top */" + "function foo(top) {\n" + " var x = top.a;\n" + "}\n" + "foo(new Foo);\n" + "foo(new Bar);\n"; testSets(false, js, "{}"); testSets(true, js, "{a=[[Bar.prototype, Foo.prototype]]}"); } public void testSupertypeReferenceOfSubtypeProperty() { String externs = "" + "/** @constructor */ function Ext() {}" + "Ext.prototype.a;"; String js = "" + "/** @constructor */ function Foo() {}\n" + "/** @constructor \n@extends Foo*/ function Bar() {}\n" + "Bar.prototype.a;\n" + "/** @param {Foo} foo */" + "function foo(foo) {\n" + " var x = foo.a;\n" + "}\n"; String result = "" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype.Bar_prototype$a;\n" + "function foo(foo$$1) {\n" + " var x = foo$$1.Bar_prototype$a;\n" + "}\n"; testSets(false, externs, js, result, "{a=[[Bar.prototype]]}"); } public void testObjectLiteralNotRenamed() { String js = "" + "var F = {a:'a', b:'b'};" + "F.a = 'z';"; testSets(false, js, js, "{}"); testSets(true, js, js, "{}"); } public void testObjectLiteralReflected() { String js = "" + "var goog = {};" + "goog.reflect = {};" + "goog.reflect.object = function(x, y) { return y; };" + "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.foo = 3;" + "/** @constructor */ function G() {}" + "/** @type {number} */ G.prototype.foo = 3;" + "goog.reflect.object(F, {foo: 5});"; String result = "" + "var goog = {};" + "goog.reflect = {};" + "goog.reflect.object = function(x, y) { return y; };" + "function F() {}" + "F.prototype.F_prototype$foo = 3;" + "function G() {}" + "G.prototype.G_prototype$foo = 3;" + "goog.reflect.object(F, {F_prototype$foo: 5});"; testSets(false, js, result, "{foo=[[F.prototype], [G.prototype]]}"); testSets(true, js, result, "{foo=[[F.prototype], [G.prototype]]}"); } public void testObjectLiteralLends() { String js = "" + "var mixin = function(x) { return x; };" + "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.foo = 3;" + "/** @constructor */ function G() {}" + "/** @type {number} */ G.prototype.foo = 3;" + "mixin(/** @lends {F.prototype} */ ({foo: 5}));"; String result = "" + "var mixin = function(x) { return x; };" + "function F() {}" + "F.prototype.F_prototype$foo = 3;" + "function G() {}" + "G.prototype.G_prototype$foo = 3;" + "mixin(/** @lends {F.prototype} */ ({F_prototype$foo: 5}));"; testSets(false, js, result, "{foo=[[F.prototype], [G.prototype]]}"); testSets(true, js, result, "{foo=[[F.prototype], [G.prototype]]}"); } public void testClosureInherits() { String js = "" + "var goog = {};" + "/** @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class. */\n" + "goog.inherits = function(childCtor, parentCtor) {\n" + " /** @constructor */\n" + " function tempCtor() {};\n" + " tempCtor.prototype = parentCtor.prototype;\n" + " childCtor.superClass_ = parentCtor.prototype;\n" + " childCtor.prototype = new tempCtor();\n" + " childCtor.prototype.constructor = childCtor;\n" + "};" + "/** @constructor */ function Top() {}\n" + "Top.prototype.f = function() {};" + "/** @constructor \n@extends Top*/ function Foo() {}\n" + "goog.inherits(Foo, Top);\n" + "/** @override */\n" + "Foo.prototype.f = function() {" + " Foo.superClass_.f();" + "};\n" + "/** @constructor \n* @extends Foo */ function Bar() {}\n" + "goog.inherits(Bar, Foo);\n" + "/** @override */\n" + "Bar.prototype.f = function() {" + " Bar.superClass_.f();" + "};\n" + "(new Bar).f();\n"; testSets(false, js, "{f=[[Top.prototype]]}"); testSets(true, js, "{constructor=[[Bar.prototype, Foo.prototype]], " + "f=[[Bar.prototype], [Foo.prototype], [Top.prototype]]}"); } public void testSkipNativeFunctionMethod() { String externs = "" + "/** @constructor \n @param {*} var_args */" + "function Function(var_args) {}" + "Function.prototype.call = function() {};"; String js = "" + "/** @constructor */ function Foo(){};" + "/** @constructor\n @extends Foo */" + "function Bar() { Foo.call(this); };"; // call should not be renamed testSame(externs, js, null); } public void testSkipNativeObjectMethod() { String externs = "" + "/** @constructor \n @param {*} opt_v */ function Object(opt_v) {}" + "Object.prototype.hasOwnProperty;"; String js = "" + "/** @constructor */ function Foo(){};" + "(new Foo).hasOwnProperty('x');"; testSets(false, externs, js, js, "{}"); testSets(true, externs, js, js, "{}"); } public void testExtendNativeType() { String externs = "" + "/** @constructor \n @return {string} */" + "function Date(opt_1, opt_2, opt_3, opt_4, opt_5, opt_6, opt_7) {}" + "/** @override */ Date.prototype.toString = function() {}"; String js = "" + "/** @constructor\n @extends {Date} */ function SuperDate() {};\n" + "(new SuperDate).toString();"; testSets(true, externs, js, js, "{}"); testSets(false, externs, js, js, "{}"); } public void testStringFunction() { // Extern functions are not renamed, but user functions on a native // prototype object are. String externs = "/**@constructor\n@param {*} opt_str \n @return {string}*/" + "function String(opt_str) {};\n" + "/** @override \n @return {string} */\n" + "String.prototype.toString = function() { };\n"; String js = "" + "/** @constructor */ function Foo() {};\n" + "Foo.prototype.foo = function() {};\n" + "String.prototype.foo = function() {};\n" + "var a = 'str'.toString().foo();\n"; String output = "" + "function Foo() {};\n" + "Foo.prototype.Foo_prototype$foo = function() {};\n" + "String.prototype.String_prototype$foo = function() {};\n" + "var a = 'str'.toString().String_prototype$foo();\n"; testSets(false, externs, js, output, "{foo=[[Foo.prototype], [String.prototype]]}"); testSets(true, externs, js, output, "{foo=[[Foo.prototype], [String.prototype]]}"); } public void testUnusedTypeInExterns() { String externs = "" + "/** @constructor */ function Foo() {};\n" + "Foo.prototype.a"; String js = "" + "/** @constructor */ function Bar() {};\n" + "Bar.prototype.a;" + "/** @constructor */ function Baz() {};\n" + "Baz.prototype.a;"; String output = "" + "/** @constructor */ function Bar() {};\n" + "Bar.prototype.Bar_prototype$a;" + "/** @constructor */ function Baz() {};\n" + "Baz.prototype.Baz_prototype$a"; testSets(false, externs, js, output, "{a=[[Bar.prototype], [Baz.prototype]]}"); testSets(true, externs, js, output, "{a=[[Bar.prototype], [Baz.prototype]]}"); } public void testInterface() { String js = "" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n" + "/** @constructor \n @implements I */ function Foo() {};\n" + "Foo.prototype.a;\n" + "/** @type I */\n" + "var F = new Foo;" + "var x = F.a;"; testSets(false, js, "{a=[[Foo.prototype, I.prototype]]}"); testSets(true, js, "{a=[[Foo.prototype], [I.prototype]]}"); } public void testInterfaceOfSuperclass() { String js = "" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n" + "/** @constructor \n @implements I */ function Foo() {};\n" + "Foo.prototype.a;\n" + "/** @constructor \n @extends Foo */ function Bar() {};\n" + "Bar.prototype.a;\n" + "/** @type Bar */\n" + "var B = new Bar;" + "B.a = 0"; testSets(false, js, "{a=[[Foo.prototype, I.prototype]]}"); testSets(true, js, "{a=[[Bar.prototype], [Foo.prototype], [I.prototype]]}"); } public void testTwoInterfacesWithSomeInheritance() { String js = "" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n" + "/** @interface */ function I2() {};\n" + "I2.prototype.a;\n" + "/** @constructor \n @implements I */ function Foo() {};\n" + "Foo.prototype.a;\n" + "/** @constructor \n @extends Foo \n @implements I2*/\n" + "function Bar() {};\n" + "Bar.prototype.a;\n" + "/** @type Bar */\n" + "var B = new Bar;" + "B.a = 0"; testSets(false, js, "{a=[[Foo.prototype, I.prototype, I2.prototype]]}"); testSets(true, js, "{a=[[Bar.prototype], [Foo.prototype], " + "[I.prototype], [I2.prototype]]}"); } public void testInvalidatingInterface() { String js = "" + "/** @interface */ function I2() {};\n" + "I2.prototype.a;\n" + "/** @constructor */ function Bar() {}\n" + "/** @type I */\n" + "var i = new Bar;\n" // Make I invalidating + "/** @constructor \n @implements I \n @implements I2 */" + "function Foo() {};\n" + "/** @override */\n" + "Foo.prototype.a = 0;\n" + "(new Foo).a = 0;" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n"; testSets(false, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING); testSets(true, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING); } public void testMultipleInterfaces() { String js = "" + "/** @interface */ function I() {};\n" + "/** @interface */ function I2() {};\n" + "I2.prototype.a;\n" + "/** @constructor \n @implements I \n @implements I2 */" + "function Foo() {};\n" + "/** @override */" + "Foo.prototype.a = 0;\n" + "(new Foo).a = 0"; testSets(false, js, "{a=[[Foo.prototype, I2.prototype]]}"); testSets(true, js, "{a=[[Foo.prototype], [I2.prototype]]}"); } public void testInterfaceWithSupertypeImplementor() { String js = "" + "/** @interface */ function C() {}\n" + "C.prototype.foo = function() {};\n" + "/** @constructor */ function A (){}\n" + "A.prototype.foo = function() {};\n" + "/** @constructor \n @implements {C} \n @extends {A} */\n" + "function B() {}\n" + "/** @type {C} */ var b = new B();\n" + "b.foo();\n"; testSets(false, js, "{foo=[[A.prototype, C.prototype]]}"); testSets(true, js, "{foo=[[A.prototype], [C.prototype]]}"); } public void testSuperInterface() { String js = "" + "/** @interface */ function I() {};\n" + "I.prototype.a;\n" + "/** @interface \n @extends I */ function I2() {};\n" + "/** @constructor \n @implements I2 */" + "function Foo() {};\n" + "/** @override */\n" + "Foo.prototype.a = 0;\n" + "(new Foo).a = 0"; testSets(false, js, "{a=[[Foo.prototype, I.prototype]]}"); testSets(true, js, "{a=[[Foo.prototype], [I.prototype]]}"); } public void testInterfaceUnionWithCtor() { String js = "" + "/** @interface */ function I() {};\n" + "/** @type {!Function} */ I.prototype.addEventListener;\n" + "/** @constructor \n * @implements {I} */ function Impl() {};\n" + "/** @type {!Function} */ Impl.prototype.addEventListener;" + "/** @constructor */ function C() {};\n" + "/** @type {!Function} */ C.prototype.addEventListener;" + "/** @param {C|I} x */" + "function f(x) { x.addEventListener(); };\n" + "f(new C()); f(new Impl());"; testSets(false, js, js, "{addEventListener=[[C.prototype, I.prototype, Impl.prototype]]}"); // In the tightened case, the disambiguator is smart enough to // disambiguate Impl's method from the interface method. String tightenedOutput = "" + "function I() {};\n" + "I.prototype.I_prototype$addEventListener;\n" + "function Impl() {};\n" + "Impl.prototype.C_prototype$addEventListener;" + "function C() {};\n" + "C.prototype.C_prototype$addEventListener;" + "/** @param {C|I} x */" + "function f(x) { x.C_prototype$addEventListener(); };\n" + "f(new C()); f(new Impl());"; testSets(true, js, tightenedOutput, "{addEventListener=[[C.prototype, Impl.prototype], [I.prototype]]}"); } public void testExternInterfaceUnionWithCtor() { String externs = "" + "/** @interface */ function I() {};\n" + "/** @type {!Function} */ I.prototype.addEventListener;\n" + "/** @constructor \n * @implements {I} */ function Impl() {};\n" + "/** @type {!Function} */ Impl.prototype.addEventListener;"; String js = "" + "/** @constructor */ function C() {};\n" + "/** @type {!Function} */ C.prototype.addEventListener;" + "/** @param {C|I} x */" + "function f(x) { x.addEventListener(); };\n" + "f(new C()); f(new Impl());"; testSets(false, externs, js, js, "{}"); testSets(true, externs, js, js, "{}"); } /** * Tests that the type based version skips renaming on types that have a * mismatch, and the type tightened version continues to work as normal. */ public void testMismatchInvalidation() { String js = "" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a = 0;\n" + "/** @type Foo */\n" + "var F = new Bar;\n" + "F.a = 0;"; testSets(false, "", js, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING, "initializing variable\n" + "found : Bar\n" + "required: (Foo|null)"); testSets(true, "", js, js, "{}", TypeValidator.TYPE_MISMATCH_WARNING, "initializing variable\n" + "found : Bar\n" + "required: (Foo|null)"); } public void testBadCast() { String js = "/** @constructor */ function Foo() {};\n" + "Foo.prototype.a = 0;\n" + "/** @constructor */ function Bar() {};\n" + "Bar.prototype.a = 0;\n" + "var a = /** @type {!Foo} */ (new Bar);\n" + "a.a = 4;"; testSets(false, "", js, js, "{}", TypeValidator.INVALID_CAST, "invalid cast - must be a subtype or supertype\n" + "from: Bar\n" + "to : Foo"); } public void testDeterministicNaming() { String js = "/** @constructor */function A() {}\n" + "/** @return {string} */A.prototype.f = function() {return 'a';};\n" + "/** @constructor */function B() {}\n" + "/** @return {string} */B.prototype.f = function() {return 'b';};\n" + "/** @constructor */function C() {}\n" + "/** @return {string} */C.prototype.f = function() {return 'c';};\n" + "/** @type {A|B} */var ab = 1 ? new B : new A;\n" + "/** @type {string} */var n = ab.f();\n"; String output = "function A() {}\n" + "A.prototype.A_prototype$f = function() { return'a'; };\n" + "function B() {}\n" + "B.prototype.A_prototype$f = function() { return'b'; };\n" + "function C() {}\n" + "C.prototype.C_prototype$f = function() { return'c'; };\n" + "var ab = 1 ? new B : new A; var n = ab.A_prototype$f();\n"; for (int i = 0; i < 5; i++) { testSets(false, js, output, "{f=[[A.prototype, B.prototype], [C.prototype]]}"); testSets(true, js, output, "{f=[[A.prototype, B.prototype], [C.prototype]]}"); } } public void testObjectLiteral() { String js = "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.a;\n" + "var F = /** @type {Foo} */({ a: 'a' });\n"; String output = "function Foo() {}\n" + "Foo.prototype.Foo_prototype$a;\n" + "function Bar() {}\n" + "Bar.prototype.Bar_prototype$a;\n" + "var F = { Foo_prototype$a: 'a' };\n"; testSets(false, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); testSets(true, js, output, "{a=[[Bar.prototype], [Foo.prototype]]}"); } public void testCustomInherits() { String js = "Object.prototype.inheritsFrom = function(shuper) {\n" + " /** @constructor */\n" + " function Inheriter() { }\n" + " Inheriter.prototype = shuper.prototype;\n" + " this.prototype = new Inheriter();\n" + " this.superConstructor = shuper;\n" + "};\n" + "function Foo(var1, var2, strength) {\n" + " Foo.superConstructor.call(this, strength);\n" + "}" + "Foo.inheritsFrom(Object);"; String externs = "" + "function Function(var_args) {}" + "/** @return {*} */Function.prototype.call = function(var_args) {};"; testSets(false, externs, js, js, "{}"); } public void testSkipNativeFunctionStaticProperty() { String js = "" + "/** @param {!Function} ctor */\n" + "function addSingletonGetter(ctor) { ctor.a; }\n" + "/** @constructor */ function Foo() {}\n" + "Foo.a = 0;" + "/** @constructor */ function Bar() {}\n" + "Bar.a = 0;"; String output = "" + "function addSingletonGetter(ctor){ctor.a}" + "function Foo(){}" + "Foo.a=0;" + "function Bar(){}" + "Bar.a=0"; testSets(false, js, output, "{}"); } public void testErrorOnProtectedProperty() { test("function addSingletonGetter(foo) { foo.foobar = 'a'; };", null, DisambiguateProperties.Warnings.INVALIDATION); assertTrue(getLastCompiler().getErrors()[0].toString().contains("foobar")); } public void testMismatchForbiddenInvalidation() { test("/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.foobar = 3;" + "/** @return {number} */ function g() { return new F(); }", null, DisambiguateProperties.Warnings.INVALIDATION); assertTrue(getLastCompiler().getErrors()[0].toString() .contains("Consider fixing errors")); } public void testUnionTypeInvalidationError() { String externs = "" + "/** @constructor */ function Baz() {}" + "Baz.prototype.foobar"; String js = "" + "/** @constructor */ function Ind() {this.foobar=0}\n" + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foobar = 0;\n" + "/** @constructor */ function Bar() {}\n" + "Bar.prototype.foobar = 0;\n" + "/** @type {Foo|Bar} */\n" + "var F = new Foo;\n" + "F.foobar = 1\n;" + "F = new Bar;\n" + "/** @type {Baz} */\n" + "var Z = new Baz;\n" + "Z.foobar = 1\n;"; test( externs, js, "", DisambiguateProperties.Warnings.INVALIDATION_ON_TYPE, null); assertTrue(getLastCompiler().getErrors()[0].toString() .contains("foobar")); } public void runFindHighestTypeInChain() { // Check that this doesn't go into an infinite loop. DisambiguateProperties.forJSTypeSystem(new Compiler(), Maps.<String, CheckLevel>newHashMap()) .getTypeWithProperty("no", new JSTypeRegistry(new TestErrorReporter(null, null)) .getNativeType(JSTypeNative.OBJECT_PROTOTYPE)); } @SuppressWarnings("unchecked") private void testSets(boolean runTightenTypes, String js, String expected, String fieldTypes) { this.runTightenTypes = runTightenTypes; test(js, expected); assertEquals( fieldTypes, mapToString(lastPass.getRenamedTypesForTesting())); } @SuppressWarnings("unchecked") private void testSets(boolean runTightenTypes, String externs, String js, String expected, String fieldTypes) { testSets(runTightenTypes, externs, js, expected, fieldTypes, null, null); } @SuppressWarnings("unchecked") private void testSets(boolean runTightenTypes, String externs, String js, String expected, String fieldTypes, DiagnosticType warning, String description) { this.runTightenTypes = runTightenTypes; test(externs, js, expected, null, warning, description); assertEquals( fieldTypes, mapToString(lastPass.getRenamedTypesForTesting())); } /** * Compiles the code and checks that the set of types for each field matches * the expected value. * * <p>The format for the set of types for fields is: * {field=[[Type1, Type2]]} */ private void testSets(boolean runTightenTypes, String js, String fieldTypes) { this.runTightenTypes = runTightenTypes; test(js, null, null, null); assertEquals(fieldTypes, mapToString(lastPass.getRenamedTypesForTesting())); } /** * Compiles the code and checks that the set of types for each field matches * the expected value. * * <p>The format for the set of types for fields is: * {field=[[Type1, Type2]]} */ private void testSets(boolean runTightenTypes, String js, String fieldTypes, DiagnosticType warning) { this.runTightenTypes = runTightenTypes; test(js, null, null, warning); assertEquals(fieldTypes, mapToString(lastPass.getRenamedTypesForTesting())); } /** Sorts the map and converts to a string for comparison purposes. */ private <T> String mapToString(Multimap<String, Collection<T>> map) { TreeMap<String, String> retMap = Maps.newTreeMap(); for (String key : map.keySet()) { TreeSet<String> treeSet = Sets.newTreeSet(); for (Collection<T> collection : map.get(key)) { Set<String> subSet = Sets.newTreeSet(); for (T type : collection) { subSet.add(type.toString()); } treeSet.add(subSet.toString()); } retMap.put(key, treeSet.toString()); } return retMap.toString(); } }
@Test public void testEscapedMySqlNullValue() throws Exception { // MySQL uses \N to symbolize null values. We have to restore this final Lexer lexer = getLexer("character\\NEscaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character\\NEscaped")); }
org.apache.commons.csv.CSVLexerTest::testEscapedMySqlNullValue
src/test/java/org/apache/commons/csv/CSVLexerTest.java
335
src/test/java/org/apache/commons/csv/CSVLexerTest.java
testEscapedMySqlNullValue
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.apache.commons.csv.Constants.BACKSPACE; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.FF; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import static org.apache.commons.csv.Token.Type.COMMENT; import static org.apache.commons.csv.Token.Type.EOF; import static org.apache.commons.csv.Token.Type.EORECORD; import static org.apache.commons.csv.Token.Type.TOKEN; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertThat; import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.matches; import java.io.IOException; import java.io.StringReader; import org.junit.Before; import org.junit.Test; /** * * * @version $Id$ */ public class CSVLexerTest { private CSVFormat formatWithEscaping; @Before public void setUp() { formatWithEscaping = CSVFormat.newBuilder().withEscape('\\').build(); } private Lexer getLexer(final String input, final CSVFormat format) { return new CSVLexer(format, new ExtendedBufferedReader(new StringReader(input))); } @Test public void testSurroundingSpacesAreDeleted() throws IOException { final String code = "noSpaces, leadingSpaces,trailingSpaces , surroundingSpaces , ,,"; final Lexer parser = getLexer(code, CSVFormat.newBuilder().withIgnoreSurroundingSpaces(true).build()); assertThat(parser.nextToken(new Token()), matches(TOKEN, "noSpaces")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "leadingSpaces")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "trailingSpaces")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "surroundingSpaces")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } @Test public void testSurroundingTabsAreDeleted() throws IOException { final String code = "noTabs,\tleadingTab,trailingTab\t,\tsurroundingTabs\t,\t\t,,"; final Lexer parser = getLexer(code, CSVFormat.newBuilder().withIgnoreSurroundingSpaces(true).build()); assertThat(parser.nextToken(new Token()), matches(TOKEN, "noTabs")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "leadingTab")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "trailingTab")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "surroundingTabs")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } @Test public void testIgnoreEmptyLines() throws IOException { final String code = "first,line,\n"+ "\n"+ "\n"+ "second,line\n"+ "\n"+ "\n"+ "third line \n"+ "\n"+ "\n"+ "last, line \n"+ "\n"+ "\n"+ "\n"; final CSVFormat format = CSVFormat.newBuilder().withIgnoreEmptyLines(true).build(); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "first")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "second")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "third line ")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "last")); assertThat(parser.nextToken(new Token()), matches(EORECORD, " line ")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } @Test public void testComments() throws IOException { final String code = "first,line,\n"+ "second,line,tokenWith#no-comment\n"+ "# comment line \n"+ "third,line,#no-comment\n"+ "# penultimate comment\n"+ "# Final comment\n"; final CSVFormat format = CSVFormat.newBuilder().withCommentStart('#').build(); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "first")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "second")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "tokenWith#no-comment")); assertThat(parser.nextToken(new Token()), matches(COMMENT, "comment line")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "third")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "#no-comment")); assertThat(parser.nextToken(new Token()), matches(COMMENT, "penultimate comment")); assertThat(parser.nextToken(new Token()), matches(COMMENT, "Final comment")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } @Test public void testCommentsAndEmptyLines() throws IOException { final String code = "1,2,3,\n"+ // 1 "\n"+ // 1b "\n"+ // 1c "a,b x,c#no-comment\n"+ // 2 "#foo\n"+ // 3 "\n"+ // 4 "\n"+ // 4b "d,e,#no-comment\n"+ // 5 "\n"+ // 5b "\n"+ // 5c "# penultimate comment\n"+ // 6 "\n"+ // 6b "\n"+ // 6c "# Final comment\n"; // 7 final CSVFormat format = CSVFormat.newBuilder().withCommentStart('#').withIgnoreEmptyLines(false).build(); assertFalse("Should not ignore empty lines", format.getIgnoreEmptyLines()); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "1")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "2")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "3")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1b assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1c assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "b x")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "c#no-comment")); // 2 assertThat(parser.nextToken(new Token()), matches(COMMENT, "foo")); // 3 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 4 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 4b assertThat(parser.nextToken(new Token()), matches(TOKEN, "d")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "e")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "#no-comment")); // 5 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 5b assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 5c assertThat(parser.nextToken(new Token()), matches(COMMENT, "penultimate comment")); // 6 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 6b assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 6c assertThat(parser.nextToken(new Token()), matches(COMMENT, "Final comment")); // 7 assertThat(parser.nextToken(new Token()), matches(EOF, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } // simple token with escaping not enabled @Test public void testBackslashWithoutEscaping() throws IOException { /* file: a,\,,b * \,, */ final String code = "a,\\,,b\\\n\\,,"; final CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isEscaping()); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); // an unquoted single backslash is not an escape char assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); // an unquoted single backslash is not an escape char assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } // simple token with escaping enabled @Test public void testBackslashWithEscaping() throws IOException { /* file: a,\,,b * \,, */ final String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; final CSVFormat format = formatWithEscaping.toBuilder().withIgnoreEmptyLines(false).build(); assertTrue(format.isEscaping()); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, ",")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, ",")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "\nc")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "d\r")); assertThat(parser.nextToken(new Token()), matches(EOF, "e")); } // encapsulator tokenizer (single line) @Test public void testNextToken4() throws IOException { /* file: a,"foo",b * a, " foo",b * a,"foo " ,b // whitespace after closing encapsulator * a, " foo " ,b */ final String code = "a,\"foo\",b\na, \" foo\",b\na,\"foo \" ,b\na, \" foo \" ,b"; final Lexer parser = getLexer(code, CSVFormat.newBuilder().withIgnoreSurroundingSpaces(true).build()); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, " foo")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo ")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, " foo ")); // assertTokenEquals(EORECORD, "b", parser.nextToken(new Token())); assertThat(parser.nextToken(new Token()), matches(EOF, "b")); } // encapsulator tokenizer (multi line, delimiter in string) @Test public void testNextToken5() throws IOException { final String code = "a,\"foo\n\",b\n\"foo\n baar ,,,\"\n\"\n\t \n\""; final Lexer parser = getLexer(code, CSVFormat.DEFAULT); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo\n")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "foo\n baar ,,,")); assertThat(parser.nextToken(new Token()), matches(EOF, "\n\t \n")); } // change delimiters, comment, encapsulater @Test public void testNextToken6() throws IOException { /* file: a;'b and \' more * ' * !comment;;;; * ;; */ final String code = "a;'b and '' more\n'\n!comment;;;;\n;;"; final CSVFormat format = CSVFormat.newBuilder().withDelimiter(';').withQuoteChar('\'').withCommentStart('!').build(); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b and ' more\n")); } // From CSV-1 @Test public void testDelimiterIsWhitespace() throws IOException { final String code = "one\ttwo\t\tfour \t five\t six"; final Lexer parser = getLexer(code, CSVFormat.TDF); assertThat(parser.nextToken(new Token()), matches(TOKEN, "one")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "two")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "four")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "five")); assertThat(parser.nextToken(new Token()), matches(EOF, "six")); } @Test public void testEscapedCR() throws Exception { final Lexer lexer = getLexer("character\\" + CR + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); } @Test public void testEscapedLF() throws Exception { final Lexer lexer = getLexer("character\\" + LF + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + LF + "Escaped")); } @Test // TODO is this correct? Do we expect TAB to be un/escaped? public void testEscapedTab() throws Exception { final Lexer lexer = getLexer("character\\" + TAB + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + TAB + "Escaped")); } @Test // TODO is this correct? Do we expect BACKSPACE to be un/escaped? public void testEscapeBackspace() throws Exception { final Lexer lexer = getLexer("character\\" + BACKSPACE + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + BACKSPACE + "Escaped")); } @Test // TODO is this correct? Do we expect FF to be un/escaped? public void testEscapeFF() throws Exception { final Lexer lexer = getLexer("character\\" + FF + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + FF + "Escaped")); } @Test public void testEscapedMySqlNullValue() throws Exception { // MySQL uses \N to symbolize null values. We have to restore this final Lexer lexer = getLexer("character\\NEscaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character\\NEscaped")); } @Test public void testEscapedCharacter() throws Exception { final Lexer lexer = getLexer("character\\aEscaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character\\aEscaped")); } @Test public void testEscapedControlCharacter() throws Exception { // we are explicitly using an escape different from \ here final Lexer lexer = getLexer("character!rEscaped", CSVFormat.newBuilder().withEscape('!').build()); assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); } @Test public void testEscapedControlCharacter2() throws Exception { final Lexer lexer = getLexer("character\\rEscaped", CSVFormat.newBuilder().withEscape('\\').build()); assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); } @Test(expected = IOException.class) public void testEscapingAtEOF() throws Exception { final String code = "escaping at EOF is evil\\"; final Lexer lexer = getLexer(code, formatWithEscaping); lexer.nextToken(new Token()); } }
// You are a professional Java test case writer, please create a test case named `testEscapedMySqlNullValue` for the issue `Csv-CSV-58`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-58 // // ## Issue-Title: // Unescape handling needs rethinking // // ## Issue-Description: // // The current escape parsing converts <esc><char> to plain <char> if the <char> is not one of the special characters to be escaped. // // // This can affect unicode escapes if the <esc> character is backslash. // // // One way round this is to specifically check for <char> == 'u', but it seems wrong to only do this for 'u'. // // // Another solution would be to leave <esc><char> as is unless the <char> is one of the special characters. // // // There are several possible ways to treat unrecognised escapes: // // // * treat it as if the escape char had not been present (current behaviour) // * leave the escape char as is // * throw an exception // // // // // @Test public void testEscapedMySqlNullValue() throws Exception {
335
3
330
src/test/java/org/apache/commons/csv/CSVLexerTest.java
src/test/java
```markdown ## Issue-ID: Csv-CSV-58 ## Issue-Title: Unescape handling needs rethinking ## Issue-Description: The current escape parsing converts <esc><char> to plain <char> if the <char> is not one of the special characters to be escaped. This can affect unicode escapes if the <esc> character is backslash. One way round this is to specifically check for <char> == 'u', but it seems wrong to only do this for 'u'. Another solution would be to leave <esc><char> as is unless the <char> is one of the special characters. There are several possible ways to treat unrecognised escapes: * treat it as if the escape char had not been present (current behaviour) * leave the escape char as is * throw an exception ``` You are a professional Java test case writer, please create a test case named `testEscapedMySqlNullValue` for the issue `Csv-CSV-58`, utilizing the provided issue report information and the following function signature. ```java @Test public void testEscapedMySqlNullValue() throws Exception { ```
330
[ "org.apache.commons.csv.Lexer" ]
1df3353e84e8d8aedab388963a4bb9de8a3e8563bf8af58a4a8d9cd014425f81
@Test public void testEscapedMySqlNullValue() throws Exception
// You are a professional Java test case writer, please create a test case named `testEscapedMySqlNullValue` for the issue `Csv-CSV-58`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-58 // // ## Issue-Title: // Unescape handling needs rethinking // // ## Issue-Description: // // The current escape parsing converts <esc><char> to plain <char> if the <char> is not one of the special characters to be escaped. // // // This can affect unicode escapes if the <esc> character is backslash. // // // One way round this is to specifically check for <char> == 'u', but it seems wrong to only do this for 'u'. // // // Another solution would be to leave <esc><char> as is unless the <char> is one of the special characters. // // // There are several possible ways to treat unrecognised escapes: // // // * treat it as if the escape char had not been present (current behaviour) // * leave the escape char as is // * throw an exception // // // // //
Csv
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.apache.commons.csv.Constants.BACKSPACE; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.FF; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import static org.apache.commons.csv.Token.Type.COMMENT; import static org.apache.commons.csv.Token.Type.EOF; import static org.apache.commons.csv.Token.Type.EORECORD; import static org.apache.commons.csv.Token.Type.TOKEN; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertThat; import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.matches; import java.io.IOException; import java.io.StringReader; import org.junit.Before; import org.junit.Test; /** * * * @version $Id$ */ public class CSVLexerTest { private CSVFormat formatWithEscaping; @Before public void setUp() { formatWithEscaping = CSVFormat.newBuilder().withEscape('\\').build(); } private Lexer getLexer(final String input, final CSVFormat format) { return new CSVLexer(format, new ExtendedBufferedReader(new StringReader(input))); } @Test public void testSurroundingSpacesAreDeleted() throws IOException { final String code = "noSpaces, leadingSpaces,trailingSpaces , surroundingSpaces , ,,"; final Lexer parser = getLexer(code, CSVFormat.newBuilder().withIgnoreSurroundingSpaces(true).build()); assertThat(parser.nextToken(new Token()), matches(TOKEN, "noSpaces")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "leadingSpaces")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "trailingSpaces")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "surroundingSpaces")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } @Test public void testSurroundingTabsAreDeleted() throws IOException { final String code = "noTabs,\tleadingTab,trailingTab\t,\tsurroundingTabs\t,\t\t,,"; final Lexer parser = getLexer(code, CSVFormat.newBuilder().withIgnoreSurroundingSpaces(true).build()); assertThat(parser.nextToken(new Token()), matches(TOKEN, "noTabs")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "leadingTab")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "trailingTab")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "surroundingTabs")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } @Test public void testIgnoreEmptyLines() throws IOException { final String code = "first,line,\n"+ "\n"+ "\n"+ "second,line\n"+ "\n"+ "\n"+ "third line \n"+ "\n"+ "\n"+ "last, line \n"+ "\n"+ "\n"+ "\n"; final CSVFormat format = CSVFormat.newBuilder().withIgnoreEmptyLines(true).build(); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "first")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "second")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "third line ")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "last")); assertThat(parser.nextToken(new Token()), matches(EORECORD, " line ")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } @Test public void testComments() throws IOException { final String code = "first,line,\n"+ "second,line,tokenWith#no-comment\n"+ "# comment line \n"+ "third,line,#no-comment\n"+ "# penultimate comment\n"+ "# Final comment\n"; final CSVFormat format = CSVFormat.newBuilder().withCommentStart('#').build(); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "first")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "second")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "tokenWith#no-comment")); assertThat(parser.nextToken(new Token()), matches(COMMENT, "comment line")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "third")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "#no-comment")); assertThat(parser.nextToken(new Token()), matches(COMMENT, "penultimate comment")); assertThat(parser.nextToken(new Token()), matches(COMMENT, "Final comment")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } @Test public void testCommentsAndEmptyLines() throws IOException { final String code = "1,2,3,\n"+ // 1 "\n"+ // 1b "\n"+ // 1c "a,b x,c#no-comment\n"+ // 2 "#foo\n"+ // 3 "\n"+ // 4 "\n"+ // 4b "d,e,#no-comment\n"+ // 5 "\n"+ // 5b "\n"+ // 5c "# penultimate comment\n"+ // 6 "\n"+ // 6b "\n"+ // 6c "# Final comment\n"; // 7 final CSVFormat format = CSVFormat.newBuilder().withCommentStart('#').withIgnoreEmptyLines(false).build(); assertFalse("Should not ignore empty lines", format.getIgnoreEmptyLines()); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "1")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "2")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "3")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1b assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1c assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "b x")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "c#no-comment")); // 2 assertThat(parser.nextToken(new Token()), matches(COMMENT, "foo")); // 3 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 4 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 4b assertThat(parser.nextToken(new Token()), matches(TOKEN, "d")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "e")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "#no-comment")); // 5 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 5b assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 5c assertThat(parser.nextToken(new Token()), matches(COMMENT, "penultimate comment")); // 6 assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 6b assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 6c assertThat(parser.nextToken(new Token()), matches(COMMENT, "Final comment")); // 7 assertThat(parser.nextToken(new Token()), matches(EOF, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } // simple token with escaping not enabled @Test public void testBackslashWithoutEscaping() throws IOException { /* file: a,\,,b * \,, */ final String code = "a,\\,,b\\\n\\,,"; final CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isEscaping()); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); // an unquoted single backslash is not an escape char assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); // an unquoted single backslash is not an escape char assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } // simple token with escaping enabled @Test public void testBackslashWithEscaping() throws IOException { /* file: a,\,,b * \,, */ final String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; final CSVFormat format = formatWithEscaping.toBuilder().withIgnoreEmptyLines(false).build(); assertTrue(format.isEscaping()); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, ",")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, ",")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "\nc")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "d\r")); assertThat(parser.nextToken(new Token()), matches(EOF, "e")); } // encapsulator tokenizer (single line) @Test public void testNextToken4() throws IOException { /* file: a,"foo",b * a, " foo",b * a,"foo " ,b // whitespace after closing encapsulator * a, " foo " ,b */ final String code = "a,\"foo\",b\na, \" foo\",b\na,\"foo \" ,b\na, \" foo \" ,b"; final Lexer parser = getLexer(code, CSVFormat.newBuilder().withIgnoreSurroundingSpaces(true).build()); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, " foo")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo ")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, " foo ")); // assertTokenEquals(EORECORD, "b", parser.nextToken(new Token())); assertThat(parser.nextToken(new Token()), matches(EOF, "b")); } // encapsulator tokenizer (multi line, delimiter in string) @Test public void testNextToken5() throws IOException { final String code = "a,\"foo\n\",b\n\"foo\n baar ,,,\"\n\"\n\t \n\""; final Lexer parser = getLexer(code, CSVFormat.DEFAULT); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo\n")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "foo\n baar ,,,")); assertThat(parser.nextToken(new Token()), matches(EOF, "\n\t \n")); } // change delimiters, comment, encapsulater @Test public void testNextToken6() throws IOException { /* file: a;'b and \' more * ' * !comment;;;; * ;; */ final String code = "a;'b and '' more\n'\n!comment;;;;\n;;"; final CSVFormat format = CSVFormat.newBuilder().withDelimiter(';').withQuoteChar('\'').withCommentStart('!').build(); final Lexer parser = getLexer(code, format); assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b and ' more\n")); } // From CSV-1 @Test public void testDelimiterIsWhitespace() throws IOException { final String code = "one\ttwo\t\tfour \t five\t six"; final Lexer parser = getLexer(code, CSVFormat.TDF); assertThat(parser.nextToken(new Token()), matches(TOKEN, "one")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "two")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "four")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "five")); assertThat(parser.nextToken(new Token()), matches(EOF, "six")); } @Test public void testEscapedCR() throws Exception { final Lexer lexer = getLexer("character\\" + CR + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); } @Test public void testEscapedLF() throws Exception { final Lexer lexer = getLexer("character\\" + LF + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + LF + "Escaped")); } @Test // TODO is this correct? Do we expect TAB to be un/escaped? public void testEscapedTab() throws Exception { final Lexer lexer = getLexer("character\\" + TAB + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + TAB + "Escaped")); } @Test // TODO is this correct? Do we expect BACKSPACE to be un/escaped? public void testEscapeBackspace() throws Exception { final Lexer lexer = getLexer("character\\" + BACKSPACE + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + BACKSPACE + "Escaped")); } @Test // TODO is this correct? Do we expect FF to be un/escaped? public void testEscapeFF() throws Exception { final Lexer lexer = getLexer("character\\" + FF + "Escaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character" + FF + "Escaped")); } @Test public void testEscapedMySqlNullValue() throws Exception { // MySQL uses \N to symbolize null values. We have to restore this final Lexer lexer = getLexer("character\\NEscaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character\\NEscaped")); } @Test public void testEscapedCharacter() throws Exception { final Lexer lexer = getLexer("character\\aEscaped", formatWithEscaping); assertThat(lexer.nextToken(new Token()), hasContent("character\\aEscaped")); } @Test public void testEscapedControlCharacter() throws Exception { // we are explicitly using an escape different from \ here final Lexer lexer = getLexer("character!rEscaped", CSVFormat.newBuilder().withEscape('!').build()); assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); } @Test public void testEscapedControlCharacter2() throws Exception { final Lexer lexer = getLexer("character\\rEscaped", CSVFormat.newBuilder().withEscape('\\').build()); assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); } @Test(expected = IOException.class) public void testEscapingAtEOF() throws Exception { final String code = "escaping at EOF is evil\\"; final Lexer lexer = getLexer(code, formatWithEscaping); lexer.nextToken(new Token()); } }
@Test public void hasClassCaseInsensitive() { Elements els = Jsoup.parse("<p Class=One>One <p class=Two>Two <p CLASS=THREE>THREE").select("p"); Element one = els.get(0); Element two = els.get(1); Element thr = els.get(2); assertTrue(one.hasClass("One")); assertTrue(one.hasClass("ONE")); assertTrue(two.hasClass("TWO")); assertTrue(two.hasClass("Two")); assertTrue(thr.hasClass("ThreE")); assertTrue(thr.hasClass("three")); }
org.jsoup.select.ElementsTest::hasClassCaseInsensitive
src/test/java/org/jsoup/select/ElementsTest.java
111
src/test/java/org/jsoup/select/ElementsTest.java
hasClassCaseInsensitive
package org.jsoup.select; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.FormElement; import org.jsoup.nodes.Node; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** Tests for ElementList. @author Jonathan Hedley, jonathan@hedley.net */ public class ElementsTest { @Test public void filter() { String h = "<p>Excl</p><div class=headline><p>Hello</p><p>There</p></div><div class=headline><h1>Headline</h1></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select(".headline").select("p"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("There", els.get(1).text()); } @Test public void attributes() { String h = "<p title=foo><p title=bar><p class=foo><p class=bar>"; Document doc = Jsoup.parse(h); Elements withTitle = doc.select("p[title]"); assertEquals(2, withTitle.size()); assertTrue(withTitle.hasAttr("title")); assertFalse(withTitle.hasAttr("class")); assertEquals("foo", withTitle.attr("title")); withTitle.removeAttr("title"); assertEquals(2, withTitle.size()); // existing Elements are not reevaluated assertEquals(0, doc.select("p[title]").size()); Elements ps = doc.select("p").attr("style", "classy"); assertEquals(4, ps.size()); assertEquals("classy", ps.last().attr("style")); assertEquals("bar", ps.last().attr("class")); } @Test public void hasAttr() { Document doc = Jsoup.parse("<p title=foo><p title=bar><p class=foo><p class=bar>"); Elements ps = doc.select("p"); assertTrue(ps.hasAttr("class")); assertFalse(ps.hasAttr("style")); } @Test public void hasAbsAttr() { Document doc = Jsoup.parse("<a id=1 href='/foo'>One</a> <a id=2 href='https://jsoup.org'>Two</a>"); Elements one = doc.select("#1"); Elements two = doc.select("#2"); Elements both = doc.select("a"); assertFalse(one.hasAttr("abs:href")); assertTrue(two.hasAttr("abs:href")); assertTrue(both.hasAttr("abs:href")); // hits on #2 } @Test public void attr() { Document doc = Jsoup.parse("<p title=foo><p title=bar><p class=foo><p class=bar>"); String classVal = doc.select("p").attr("class"); assertEquals("foo", classVal); } @Test public void absAttr() { Document doc = Jsoup.parse("<a id=1 href='/foo'>One</a> <a id=2 href='https://jsoup.org'>Two</a>"); Elements one = doc.select("#1"); Elements two = doc.select("#2"); Elements both = doc.select("a"); assertEquals("", one.attr("abs:href")); assertEquals("https://jsoup.org", two.attr("abs:href")); assertEquals("https://jsoup.org", both.attr("abs:href")); } @Test public void classes() { Document doc = Jsoup.parse("<div><p class='mellow yellow'></p><p class='red green'></p>"); Elements els = doc.select("p"); assertTrue(els.hasClass("red")); assertFalse(els.hasClass("blue")); els.addClass("blue"); els.removeClass("yellow"); els.toggleClass("mellow"); assertEquals("blue", els.get(0).className()); assertEquals("red green blue mellow", els.get(1).className()); } @Test public void hasClassCaseInsensitive() { Elements els = Jsoup.parse("<p Class=One>One <p class=Two>Two <p CLASS=THREE>THREE").select("p"); Element one = els.get(0); Element two = els.get(1); Element thr = els.get(2); assertTrue(one.hasClass("One")); assertTrue(one.hasClass("ONE")); assertTrue(two.hasClass("TWO")); assertTrue(two.hasClass("Two")); assertTrue(thr.hasClass("ThreE")); assertTrue(thr.hasClass("three")); } @Test public void text() { String h = "<div><p>Hello<p>there<p>world</div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there world", doc.select("div > *").text()); } @Test public void hasText() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p></p></div>"); Elements divs = doc.select("div"); assertTrue(divs.hasText()); assertFalse(doc.select("div + div").hasText()); } @Test public void html() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p>There</p></div>"); Elements divs = doc.select("div"); assertEquals("<p>Hello</p>\n<p>There</p>", divs.html()); } @Test public void outerHtml() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p>There</p></div>"); Elements divs = doc.select("div"); assertEquals("<div><p>Hello</p></div><div><p>There</p></div>", TextUtil.stripNewlines(divs.outerHtml())); } @Test public void setHtml() { Document doc = Jsoup.parse("<p>One</p><p>Two</p><p>Three</p>"); Elements ps = doc.select("p"); ps.prepend("<b>Bold</b>").append("<i>Ital</i>"); assertEquals("<p><b>Bold</b>Two<i>Ital</i></p>", TextUtil.stripNewlines(ps.get(1).outerHtml())); ps.html("<span>Gone</span>"); assertEquals("<p><span>Gone</span></p>", TextUtil.stripNewlines(ps.get(1).outerHtml())); } @Test public void val() { Document doc = Jsoup.parse("<input value='one' /><textarea>two</textarea>"); Elements els = doc.select("input, textarea"); assertEquals(2, els.size()); assertEquals("one", els.val()); assertEquals("two", els.last().val()); els.val("three"); assertEquals("three", els.first().val()); assertEquals("three", els.last().val()); assertEquals("<textarea>three</textarea>", els.last().outerHtml()); } @Test public void before() { Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>"); doc.select("a").before("<span>foo</span>"); assertEquals("<p>This <span>foo</span><a>is</a> <span>foo</span><a>jsoup</a>.</p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>"); doc.select("a").after("<span>foo</span>"); assertEquals("<p>This <a>is</a><span>foo</span> <a>jsoup</a><span>foo</span>.</p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void wrap() { String h = "<p><b>This</b> is <b>jsoup</b></p>"; Document doc = Jsoup.parse(h); doc.select("b").wrap("<i></i>"); assertEquals("<p><i><b>This</b></i> is <i><b>jsoup</b></i></p>", doc.body().html()); } @Test public void wrapDiv() { String h = "<p><b>This</b> is <b>jsoup</b>.</p> <p>How do you like it?</p>"; Document doc = Jsoup.parse(h); doc.select("p").wrap("<div></div>"); assertEquals("<div><p><b>This</b> is <b>jsoup</b>.</p></div> <div><p>How do you like it?</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void unwrap() { String h = "<div><font>One</font> <font><a href=\"/\">Two</a></font></div"; Document doc = Jsoup.parse(h); doc.select("font").unwrap(); assertEquals("<div>One <a href=\"/\">Two</a></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void unwrapP() { String h = "<p><a>One</a> Two</p> Three <i>Four</i> <p>Fix <i>Six</i></p>"; Document doc = Jsoup.parse(h); doc.select("p").unwrap(); assertEquals("<a>One</a> Two Three <i>Four</i> Fix <i>Six</i>", TextUtil.stripNewlines(doc.body().html())); } @Test public void unwrapKeepsSpace() { String h = "<p>One <span>two</span> <span>three</span> four</p>"; Document doc = Jsoup.parse(h); doc.select("span").unwrap(); assertEquals("<p>One two three four</p>", doc.body().html()); } @Test public void empty() { Document doc = Jsoup.parse("<div><p>Hello <b>there</b></p> <p>now!</p></div>"); doc.outputSettings().prettyPrint(false); doc.select("p").empty(); assertEquals("<div><p></p> <p></p></div>", doc.body().html()); } @Test public void remove() { Document doc = Jsoup.parse("<div><p>Hello <b>there</b></p> jsoup <p>now!</p></div>"); doc.outputSettings().prettyPrint(false); doc.select("p").remove(); assertEquals("<div> jsoup </div>", doc.body().html()); } @Test public void eq() { String h = "<p>Hello<p>there<p>world"; Document doc = Jsoup.parse(h); assertEquals("there", doc.select("p").eq(1).text()); assertEquals("there", doc.select("p").get(1).text()); } @Test public void is() { String h = "<p>Hello<p title=foo>there<p>world"; Document doc = Jsoup.parse(h); Elements ps = doc.select("p"); assertTrue(ps.is("[title=foo]")); assertFalse(ps.is("[title=bar]")); } @Test public void parents() { Document doc = Jsoup.parse("<div><p>Hello</p></div><p>There</p>"); Elements parents = doc.select("p").parents(); assertEquals(3, parents.size()); assertEquals("div", parents.get(0).tagName()); assertEquals("body", parents.get(1).tagName()); assertEquals("html", parents.get(2).tagName()); } @Test public void not() { Document doc = Jsoup.parse("<div id=1><p>One</p></div> <div id=2><p><span>Two</span></p></div>"); Elements div1 = doc.select("div").not(":has(p > span)"); assertEquals(1, div1.size()); assertEquals("1", div1.first().id()); Elements div2 = doc.select("div").not("#1"); assertEquals(1, div2.size()); assertEquals("2", div2.first().id()); } @Test public void tagNameSet() { Document doc = Jsoup.parse("<p>Hello <i>there</i> <i>now</i></p>"); doc.select("i").tagName("em"); assertEquals("<p>Hello <em>there</em> <em>now</em></p>", doc.body().html()); } @Test public void traverse() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); doc.select("div").traverse(new NodeVisitor() { public void head(Node node, int depth) { accum.append("<" + node.nodeName() + ">"); } public void tail(Node node, int depth) { accum.append("</" + node.nodeName() + ">"); } }); assertEquals("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.toString()); } @Test public void forms() { Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>"); Elements els = doc.select("*"); assertEquals(9, els.size()); List<FormElement> forms = els.forms(); assertEquals(2, forms.size()); assertTrue(forms.get(0) != null); assertTrue(forms.get(1) != null); assertEquals("1", forms.get(0).id()); assertEquals("2", forms.get(1).id()); } @Test public void classWithHyphen() { Document doc = Jsoup.parse("<p class='tab-nav'>Check</p>"); Elements els = doc.getElementsByClass("tab-nav"); assertEquals(1, els.size()); assertEquals("Check", els.text()); } @Test public void siblings() { Document doc = Jsoup.parse("<div><p>1<p>2<p>3<p>4<p>5<p>6</div><div><p>7<p>8<p>9<p>10<p>11<p>12</div>"); Elements els = doc.select("p:eq(3)"); // gets p4 and p10 assertEquals(2, els.size()); Elements next = els.next(); assertEquals(2, next.size()); assertEquals("5", next.first().text()); assertEquals("11", next.last().text()); assertEquals(0, els.next("p:contains(6)").size()); final Elements nextF = els.next("p:contains(5)"); assertEquals(1, nextF.size()); assertEquals("5", nextF.first().text()); Elements nextA = els.nextAll(); assertEquals(4, nextA.size()); assertEquals("5", nextA.first().text()); assertEquals("12", nextA.last().text()); Elements nextAF = els.nextAll("p:contains(6)"); assertEquals(1, nextAF.size()); assertEquals("6", nextAF.first().text()); Elements prev = els.prev(); assertEquals(2, prev.size()); assertEquals("3", prev.first().text()); assertEquals("9", prev.last().text()); assertEquals(0, els.prev("p:contains(1)").size()); final Elements prevF = els.prev("p:contains(3)"); assertEquals(1, prevF.size()); assertEquals("3", prevF.first().text()); Elements prevA = els.prevAll(); assertEquals(6, prevA.size()); assertEquals("3", prevA.first().text()); assertEquals("7", prevA.last().text()); Elements prevAF = els.prevAll("p:contains(1)"); assertEquals(1, prevAF.size()); assertEquals("1", prevAF.first().text()); } @Test public void eachText() { Document doc = Jsoup.parse("<div><p>1<p>2<p>3<p>4<p>5<p>6</div><div><p>7<p>8<p>9<p>10<p>11<p>12<p></p></div>"); List<String> divText = doc.select("div").eachText(); assertEquals(2, divText.size()); assertEquals("1 2 3 4 5 6", divText.get(0)); assertEquals("7 8 9 10 11 12", divText.get(1)); List<String> pText = doc.select("p").eachText(); Elements ps = doc.select("p"); assertEquals(13, ps.size()); assertEquals(12, pText.size()); // not 13, as last doesn't have text assertEquals("1", pText.get(0)); assertEquals("2", pText.get(1)); assertEquals("5", pText.get(4)); assertEquals("7", pText.get(6)); assertEquals("12", pText.get(11)); } @Test public void eachAttr() { Document doc = Jsoup.parse( "<div><a href='/foo'>1</a><a href='http://example.com/bar'>2</a><a href=''>3</a><a>4</a>", "http://example.com"); List<String> hrefAttrs = doc.select("a").eachAttr("href"); assertEquals(3, hrefAttrs.size()); assertEquals("/foo", hrefAttrs.get(0)); assertEquals("http://example.com/bar", hrefAttrs.get(1)); assertEquals("", hrefAttrs.get(2)); assertEquals(4, doc.select("a").size()); List<String> absAttrs = doc.select("a").eachAttr("abs:href"); assertEquals(3, absAttrs.size()); assertEquals(3, absAttrs.size()); assertEquals("http://example.com/foo", absAttrs.get(0)); assertEquals("http://example.com/bar", absAttrs.get(1)); assertEquals("http://example.com", absAttrs.get(2)); } }
// You are a professional Java test case writer, please create a test case named `hasClassCaseInsensitive` for the issue `Jsoup-814`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-814 // // ## Issue-Title: // Unexpected case sensitivity for CSS class selector // // ## Issue-Description: // Hi, // // i use JSoup version 1.10.2 and noticed an unexpected case sensitivity for a CSS class selector. I tried to parse the following HTML document with capitalized class attributes: // // // // ``` // <!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'> // <HTML> // <HEAD> // <FORM Method='POST' name='Form' Action='Action'> // <TABLE Class='Lst'> // <TR Class='Lst'> // <TH Class='Lst'>Header 1</TH> // <TH Class='Lst'>Header 2</TH> // <TH Class='Lst'>Header 3</TH> // </TR> // <TR Class='Lst1'> // <TD Class='Lst'>Cell 1</TD> // <TD Class='Lst'>Cell 2</TD> // <TD Class='Lst'>Cell 3</TD> // </TR> // </TABLE> // </FORM> // </BODY> // </HTML> // ``` // // I wanted to select the table using the selector *"html > body > form table.Lst"* because I expected it to choose the table with the class attribute "Lst", but that did not work. The selector *"html > body > form table[class=Lst]"* works. Is this a bug? // // // Here is the parser code: // // // // ``` // try { // final String htmlStr = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>\n" // + "<HTML>\n" // + " <HEAD>\n" // + " <FORM Method='POST' name='Form' Action='Action'>\n" // + " <TABLE Class='Lst'>\n" // + " <TR Class='Lst'>\n" // + " <TH Class='Lst'>Header 1</TH>\n" // + " <TH Class='Lst'>Header 2</TH>\n" // + " <TH Class='Lst'>Header 3</TH>\n" // + " </TR>\n" // + " <TR Class='Lst1'>\n" // + " <TD Class='Lst'>Cell 1</TD>\n" // + " <TD Class='Lst'>Cell 2</TD>\n" // + " <TD Class='Lst'>Cell 3</TD>\n" // + " </TR>\n" // + " </TABLE>\n" // + " </FORM>\n" // + " </BODY>\n" // + "</HTML>"; // final Document htmlDoc = Jsoup.parse(htmlStr, // ""); // // final Element tableNotOk = htmlDoc.select("html > body > form table.Lst") // .first(); // final Element tableOk = htmlDoc.select("html > body > form table[class=Lst]") // .first(); // // Logger.getLogger(this.getClass().getName()) // .log(Level.INFO, // "tableNotOk found: ''{0}'', tableOk found: ''{1}''", // new Object[]{( @Test public void hasClassCaseInsensitive() {
111
61
97
src/test/java/org/jsoup/select/ElementsTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-814 ## Issue-Title: Unexpected case sensitivity for CSS class selector ## Issue-Description: Hi, i use JSoup version 1.10.2 and noticed an unexpected case sensitivity for a CSS class selector. I tried to parse the following HTML document with capitalized class attributes: ``` <!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'> <HTML> <HEAD> <FORM Method='POST' name='Form' Action='Action'> <TABLE Class='Lst'> <TR Class='Lst'> <TH Class='Lst'>Header 1</TH> <TH Class='Lst'>Header 2</TH> <TH Class='Lst'>Header 3</TH> </TR> <TR Class='Lst1'> <TD Class='Lst'>Cell 1</TD> <TD Class='Lst'>Cell 2</TD> <TD Class='Lst'>Cell 3</TD> </TR> </TABLE> </FORM> </BODY> </HTML> ``` I wanted to select the table using the selector *"html > body > form table.Lst"* because I expected it to choose the table with the class attribute "Lst", but that did not work. The selector *"html > body > form table[class=Lst]"* works. Is this a bug? Here is the parser code: ``` try { final String htmlStr = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>\n" + "<HTML>\n" + " <HEAD>\n" + " <FORM Method='POST' name='Form' Action='Action'>\n" + " <TABLE Class='Lst'>\n" + " <TR Class='Lst'>\n" + " <TH Class='Lst'>Header 1</TH>\n" + " <TH Class='Lst'>Header 2</TH>\n" + " <TH Class='Lst'>Header 3</TH>\n" + " </TR>\n" + " <TR Class='Lst1'>\n" + " <TD Class='Lst'>Cell 1</TD>\n" + " <TD Class='Lst'>Cell 2</TD>\n" + " <TD Class='Lst'>Cell 3</TD>\n" + " </TR>\n" + " </TABLE>\n" + " </FORM>\n" + " </BODY>\n" + "</HTML>"; final Document htmlDoc = Jsoup.parse(htmlStr, ""); final Element tableNotOk = htmlDoc.select("html > body > form table.Lst") .first(); final Element tableOk = htmlDoc.select("html > body > form table[class=Lst]") .first(); Logger.getLogger(this.getClass().getName()) .log(Level.INFO, "tableNotOk found: ''{0}'', tableOk found: ''{1}''", new Object[]{( ``` You are a professional Java test case writer, please create a test case named `hasClassCaseInsensitive` for the issue `Jsoup-814`, utilizing the provided issue report information and the following function signature. ```java @Test public void hasClassCaseInsensitive() { ```
97
[ "org.jsoup.nodes.Element" ]
1e8c9722e02137baca9999c7be9776c511ddd53193320ec9ea4982dd21bddfad
@Test public void hasClassCaseInsensitive()
// You are a professional Java test case writer, please create a test case named `hasClassCaseInsensitive` for the issue `Jsoup-814`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-814 // // ## Issue-Title: // Unexpected case sensitivity for CSS class selector // // ## Issue-Description: // Hi, // // i use JSoup version 1.10.2 and noticed an unexpected case sensitivity for a CSS class selector. I tried to parse the following HTML document with capitalized class attributes: // // // // ``` // <!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'> // <HTML> // <HEAD> // <FORM Method='POST' name='Form' Action='Action'> // <TABLE Class='Lst'> // <TR Class='Lst'> // <TH Class='Lst'>Header 1</TH> // <TH Class='Lst'>Header 2</TH> // <TH Class='Lst'>Header 3</TH> // </TR> // <TR Class='Lst1'> // <TD Class='Lst'>Cell 1</TD> // <TD Class='Lst'>Cell 2</TD> // <TD Class='Lst'>Cell 3</TD> // </TR> // </TABLE> // </FORM> // </BODY> // </HTML> // ``` // // I wanted to select the table using the selector *"html > body > form table.Lst"* because I expected it to choose the table with the class attribute "Lst", but that did not work. The selector *"html > body > form table[class=Lst]"* works. Is this a bug? // // // Here is the parser code: // // // // ``` // try { // final String htmlStr = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>\n" // + "<HTML>\n" // + " <HEAD>\n" // + " <FORM Method='POST' name='Form' Action='Action'>\n" // + " <TABLE Class='Lst'>\n" // + " <TR Class='Lst'>\n" // + " <TH Class='Lst'>Header 1</TH>\n" // + " <TH Class='Lst'>Header 2</TH>\n" // + " <TH Class='Lst'>Header 3</TH>\n" // + " </TR>\n" // + " <TR Class='Lst1'>\n" // + " <TD Class='Lst'>Cell 1</TD>\n" // + " <TD Class='Lst'>Cell 2</TD>\n" // + " <TD Class='Lst'>Cell 3</TD>\n" // + " </TR>\n" // + " </TABLE>\n" // + " </FORM>\n" // + " </BODY>\n" // + "</HTML>"; // final Document htmlDoc = Jsoup.parse(htmlStr, // ""); // // final Element tableNotOk = htmlDoc.select("html > body > form table.Lst") // .first(); // final Element tableOk = htmlDoc.select("html > body > form table[class=Lst]") // .first(); // // Logger.getLogger(this.getClass().getName()) // .log(Level.INFO, // "tableNotOk found: ''{0}'', tableOk found: ''{1}''", // new Object[]{(
Jsoup
package org.jsoup.select; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.FormElement; import org.jsoup.nodes.Node; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** Tests for ElementList. @author Jonathan Hedley, jonathan@hedley.net */ public class ElementsTest { @Test public void filter() { String h = "<p>Excl</p><div class=headline><p>Hello</p><p>There</p></div><div class=headline><h1>Headline</h1></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select(".headline").select("p"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("There", els.get(1).text()); } @Test public void attributes() { String h = "<p title=foo><p title=bar><p class=foo><p class=bar>"; Document doc = Jsoup.parse(h); Elements withTitle = doc.select("p[title]"); assertEquals(2, withTitle.size()); assertTrue(withTitle.hasAttr("title")); assertFalse(withTitle.hasAttr("class")); assertEquals("foo", withTitle.attr("title")); withTitle.removeAttr("title"); assertEquals(2, withTitle.size()); // existing Elements are not reevaluated assertEquals(0, doc.select("p[title]").size()); Elements ps = doc.select("p").attr("style", "classy"); assertEquals(4, ps.size()); assertEquals("classy", ps.last().attr("style")); assertEquals("bar", ps.last().attr("class")); } @Test public void hasAttr() { Document doc = Jsoup.parse("<p title=foo><p title=bar><p class=foo><p class=bar>"); Elements ps = doc.select("p"); assertTrue(ps.hasAttr("class")); assertFalse(ps.hasAttr("style")); } @Test public void hasAbsAttr() { Document doc = Jsoup.parse("<a id=1 href='/foo'>One</a> <a id=2 href='https://jsoup.org'>Two</a>"); Elements one = doc.select("#1"); Elements two = doc.select("#2"); Elements both = doc.select("a"); assertFalse(one.hasAttr("abs:href")); assertTrue(two.hasAttr("abs:href")); assertTrue(both.hasAttr("abs:href")); // hits on #2 } @Test public void attr() { Document doc = Jsoup.parse("<p title=foo><p title=bar><p class=foo><p class=bar>"); String classVal = doc.select("p").attr("class"); assertEquals("foo", classVal); } @Test public void absAttr() { Document doc = Jsoup.parse("<a id=1 href='/foo'>One</a> <a id=2 href='https://jsoup.org'>Two</a>"); Elements one = doc.select("#1"); Elements two = doc.select("#2"); Elements both = doc.select("a"); assertEquals("", one.attr("abs:href")); assertEquals("https://jsoup.org", two.attr("abs:href")); assertEquals("https://jsoup.org", both.attr("abs:href")); } @Test public void classes() { Document doc = Jsoup.parse("<div><p class='mellow yellow'></p><p class='red green'></p>"); Elements els = doc.select("p"); assertTrue(els.hasClass("red")); assertFalse(els.hasClass("blue")); els.addClass("blue"); els.removeClass("yellow"); els.toggleClass("mellow"); assertEquals("blue", els.get(0).className()); assertEquals("red green blue mellow", els.get(1).className()); } @Test public void hasClassCaseInsensitive() { Elements els = Jsoup.parse("<p Class=One>One <p class=Two>Two <p CLASS=THREE>THREE").select("p"); Element one = els.get(0); Element two = els.get(1); Element thr = els.get(2); assertTrue(one.hasClass("One")); assertTrue(one.hasClass("ONE")); assertTrue(two.hasClass("TWO")); assertTrue(two.hasClass("Two")); assertTrue(thr.hasClass("ThreE")); assertTrue(thr.hasClass("three")); } @Test public void text() { String h = "<div><p>Hello<p>there<p>world</div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there world", doc.select("div > *").text()); } @Test public void hasText() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p></p></div>"); Elements divs = doc.select("div"); assertTrue(divs.hasText()); assertFalse(doc.select("div + div").hasText()); } @Test public void html() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p>There</p></div>"); Elements divs = doc.select("div"); assertEquals("<p>Hello</p>\n<p>There</p>", divs.html()); } @Test public void outerHtml() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p>There</p></div>"); Elements divs = doc.select("div"); assertEquals("<div><p>Hello</p></div><div><p>There</p></div>", TextUtil.stripNewlines(divs.outerHtml())); } @Test public void setHtml() { Document doc = Jsoup.parse("<p>One</p><p>Two</p><p>Three</p>"); Elements ps = doc.select("p"); ps.prepend("<b>Bold</b>").append("<i>Ital</i>"); assertEquals("<p><b>Bold</b>Two<i>Ital</i></p>", TextUtil.stripNewlines(ps.get(1).outerHtml())); ps.html("<span>Gone</span>"); assertEquals("<p><span>Gone</span></p>", TextUtil.stripNewlines(ps.get(1).outerHtml())); } @Test public void val() { Document doc = Jsoup.parse("<input value='one' /><textarea>two</textarea>"); Elements els = doc.select("input, textarea"); assertEquals(2, els.size()); assertEquals("one", els.val()); assertEquals("two", els.last().val()); els.val("three"); assertEquals("three", els.first().val()); assertEquals("three", els.last().val()); assertEquals("<textarea>three</textarea>", els.last().outerHtml()); } @Test public void before() { Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>"); doc.select("a").before("<span>foo</span>"); assertEquals("<p>This <span>foo</span><a>is</a> <span>foo</span><a>jsoup</a>.</p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>"); doc.select("a").after("<span>foo</span>"); assertEquals("<p>This <a>is</a><span>foo</span> <a>jsoup</a><span>foo</span>.</p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void wrap() { String h = "<p><b>This</b> is <b>jsoup</b></p>"; Document doc = Jsoup.parse(h); doc.select("b").wrap("<i></i>"); assertEquals("<p><i><b>This</b></i> is <i><b>jsoup</b></i></p>", doc.body().html()); } @Test public void wrapDiv() { String h = "<p><b>This</b> is <b>jsoup</b>.</p> <p>How do you like it?</p>"; Document doc = Jsoup.parse(h); doc.select("p").wrap("<div></div>"); assertEquals("<div><p><b>This</b> is <b>jsoup</b>.</p></div> <div><p>How do you like it?</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void unwrap() { String h = "<div><font>One</font> <font><a href=\"/\">Two</a></font></div"; Document doc = Jsoup.parse(h); doc.select("font").unwrap(); assertEquals("<div>One <a href=\"/\">Two</a></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void unwrapP() { String h = "<p><a>One</a> Two</p> Three <i>Four</i> <p>Fix <i>Six</i></p>"; Document doc = Jsoup.parse(h); doc.select("p").unwrap(); assertEquals("<a>One</a> Two Three <i>Four</i> Fix <i>Six</i>", TextUtil.stripNewlines(doc.body().html())); } @Test public void unwrapKeepsSpace() { String h = "<p>One <span>two</span> <span>three</span> four</p>"; Document doc = Jsoup.parse(h); doc.select("span").unwrap(); assertEquals("<p>One two three four</p>", doc.body().html()); } @Test public void empty() { Document doc = Jsoup.parse("<div><p>Hello <b>there</b></p> <p>now!</p></div>"); doc.outputSettings().prettyPrint(false); doc.select("p").empty(); assertEquals("<div><p></p> <p></p></div>", doc.body().html()); } @Test public void remove() { Document doc = Jsoup.parse("<div><p>Hello <b>there</b></p> jsoup <p>now!</p></div>"); doc.outputSettings().prettyPrint(false); doc.select("p").remove(); assertEquals("<div> jsoup </div>", doc.body().html()); } @Test public void eq() { String h = "<p>Hello<p>there<p>world"; Document doc = Jsoup.parse(h); assertEquals("there", doc.select("p").eq(1).text()); assertEquals("there", doc.select("p").get(1).text()); } @Test public void is() { String h = "<p>Hello<p title=foo>there<p>world"; Document doc = Jsoup.parse(h); Elements ps = doc.select("p"); assertTrue(ps.is("[title=foo]")); assertFalse(ps.is("[title=bar]")); } @Test public void parents() { Document doc = Jsoup.parse("<div><p>Hello</p></div><p>There</p>"); Elements parents = doc.select("p").parents(); assertEquals(3, parents.size()); assertEquals("div", parents.get(0).tagName()); assertEquals("body", parents.get(1).tagName()); assertEquals("html", parents.get(2).tagName()); } @Test public void not() { Document doc = Jsoup.parse("<div id=1><p>One</p></div> <div id=2><p><span>Two</span></p></div>"); Elements div1 = doc.select("div").not(":has(p > span)"); assertEquals(1, div1.size()); assertEquals("1", div1.first().id()); Elements div2 = doc.select("div").not("#1"); assertEquals(1, div2.size()); assertEquals("2", div2.first().id()); } @Test public void tagNameSet() { Document doc = Jsoup.parse("<p>Hello <i>there</i> <i>now</i></p>"); doc.select("i").tagName("em"); assertEquals("<p>Hello <em>there</em> <em>now</em></p>", doc.body().html()); } @Test public void traverse() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); doc.select("div").traverse(new NodeVisitor() { public void head(Node node, int depth) { accum.append("<" + node.nodeName() + ">"); } public void tail(Node node, int depth) { accum.append("</" + node.nodeName() + ">"); } }); assertEquals("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.toString()); } @Test public void forms() { Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>"); Elements els = doc.select("*"); assertEquals(9, els.size()); List<FormElement> forms = els.forms(); assertEquals(2, forms.size()); assertTrue(forms.get(0) != null); assertTrue(forms.get(1) != null); assertEquals("1", forms.get(0).id()); assertEquals("2", forms.get(1).id()); } @Test public void classWithHyphen() { Document doc = Jsoup.parse("<p class='tab-nav'>Check</p>"); Elements els = doc.getElementsByClass("tab-nav"); assertEquals(1, els.size()); assertEquals("Check", els.text()); } @Test public void siblings() { Document doc = Jsoup.parse("<div><p>1<p>2<p>3<p>4<p>5<p>6</div><div><p>7<p>8<p>9<p>10<p>11<p>12</div>"); Elements els = doc.select("p:eq(3)"); // gets p4 and p10 assertEquals(2, els.size()); Elements next = els.next(); assertEquals(2, next.size()); assertEquals("5", next.first().text()); assertEquals("11", next.last().text()); assertEquals(0, els.next("p:contains(6)").size()); final Elements nextF = els.next("p:contains(5)"); assertEquals(1, nextF.size()); assertEquals("5", nextF.first().text()); Elements nextA = els.nextAll(); assertEquals(4, nextA.size()); assertEquals("5", nextA.first().text()); assertEquals("12", nextA.last().text()); Elements nextAF = els.nextAll("p:contains(6)"); assertEquals(1, nextAF.size()); assertEquals("6", nextAF.first().text()); Elements prev = els.prev(); assertEquals(2, prev.size()); assertEquals("3", prev.first().text()); assertEquals("9", prev.last().text()); assertEquals(0, els.prev("p:contains(1)").size()); final Elements prevF = els.prev("p:contains(3)"); assertEquals(1, prevF.size()); assertEquals("3", prevF.first().text()); Elements prevA = els.prevAll(); assertEquals(6, prevA.size()); assertEquals("3", prevA.first().text()); assertEquals("7", prevA.last().text()); Elements prevAF = els.prevAll("p:contains(1)"); assertEquals(1, prevAF.size()); assertEquals("1", prevAF.first().text()); } @Test public void eachText() { Document doc = Jsoup.parse("<div><p>1<p>2<p>3<p>4<p>5<p>6</div><div><p>7<p>8<p>9<p>10<p>11<p>12<p></p></div>"); List<String> divText = doc.select("div").eachText(); assertEquals(2, divText.size()); assertEquals("1 2 3 4 5 6", divText.get(0)); assertEquals("7 8 9 10 11 12", divText.get(1)); List<String> pText = doc.select("p").eachText(); Elements ps = doc.select("p"); assertEquals(13, ps.size()); assertEquals(12, pText.size()); // not 13, as last doesn't have text assertEquals("1", pText.get(0)); assertEquals("2", pText.get(1)); assertEquals("5", pText.get(4)); assertEquals("7", pText.get(6)); assertEquals("12", pText.get(11)); } @Test public void eachAttr() { Document doc = Jsoup.parse( "<div><a href='/foo'>1</a><a href='http://example.com/bar'>2</a><a href=''>3</a><a>4</a>", "http://example.com"); List<String> hrefAttrs = doc.select("a").eachAttr("href"); assertEquals(3, hrefAttrs.size()); assertEquals("/foo", hrefAttrs.get(0)); assertEquals("http://example.com/bar", hrefAttrs.get(1)); assertEquals("", hrefAttrs.get(2)); assertEquals(4, doc.select("a").size()); List<String> absAttrs = doc.select("a").eachAttr("abs:href"); assertEquals(3, absAttrs.size()); assertEquals(3, absAttrs.size()); assertEquals("http://example.com/foo", absAttrs.get(0)); assertEquals("http://example.com/bar", absAttrs.get(1)); assertEquals("http://example.com", absAttrs.get(2)); } }
public void testCall1() { test("Math.sin(0);", ""); }
com.google.javascript.jscomp.PeepholeRemoveDeadCodeTest::testCall1
test/com/google/javascript/jscomp/PeepholeRemoveDeadCodeTest.java
544
test/com/google/javascript/jscomp/PeepholeRemoveDeadCodeTest.java
testCall1
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Tests for PeepholeRemoveDeadCodeTest in isolation. Tests for the interaction * of multiple peephole passes are in PeepholeIntegrationTest. */ public class PeepholeRemoveDeadCodeTest extends CompilerTestCase { public PeepholeRemoveDeadCodeTest() { super(""); } @Override public void setUp() throws Exception { super.setUp(); enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { PeepholeOptimizationsPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeRemoveDeadCode()); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } public void testFoldBlock() { fold("{{foo()}}", "foo()"); fold("{foo();{}}", "foo()"); fold("{{foo()}{}}", "foo()"); fold("{{foo()}{bar()}}", "foo();bar()"); fold("{if(false)foo(); {bar()}}", "bar()"); fold("{if(false)if(false)if(false)foo(); {bar()}}", "bar()"); fold("{'hi'}", ""); fold("{x==3}", ""); fold("{ (function(){x++}) }", ""); fold("function f(){return;}", "function f(){return;}"); fold("function f(){return 3;}", "function f(){return 3}"); fold("function f(){if(x)return; x=3; return; }", "function f(){if(x)return; x=3; return; }"); fold("{x=3;;;y=2;;;}", "x=3;y=2"); // Cases to test for empty block. fold("while(x()){x}", "while(x());"); fold("while(x()){x()}", "while(x())x()"); fold("for(x=0;x<100;x++){x}", "for(x=0;x<100;x++);"); fold("for(x in y){x}", "for(x in y);"); } /** Try to remove spurious blocks with multiple children */ public void testFoldBlocksWithManyChildren() { fold("function f() { if (false) {} }", "function f(){}"); fold("function f() { { if (false) {} if (true) {} {} } }", "function f(){}"); fold("{var x; var y; var z; function f() { { var a; { var b; } } } }", "var x;var y;var z;function f(){var a;var b}"); } public void testIf() { fold("if (1){ x=1; } else { x = 2;}", "x=1"); fold("if (false){ x = 1; } else { x = 2; }", "x=2"); fold("if (undefined){ x = 1; } else { x = 2; }", "x=2"); fold("if (null){ x = 1; } else { x = 2; }", "x=2"); fold("if (void 0){ x = 1; } else { x = 2; }", "x=2"); fold("if (void foo()){ x = 1; } else { x = 2; }", "foo();x=2"); fold("if (false){ x = 1; } else if (true) { x = 3; } else { x = 2; }", "x=3"); fold("if (x){ x = 1; } else if (false) { x = 3; }", "if(x)x=1"); } public void testHook() { fold("true ? a() : b()", "a()"); fold("false ? a() : b()", "b()"); fold("a() ? b() : true", "a() && b()"); fold("a() ? true : b()", "a() || b()"); fold("(a = true) ? b() : c()", "a = true, b()"); fold("(a = false) ? b() : c()", "a = false, c()"); fold("do {f()} while((a = true) ? b() : c())", "do {f()} while((a = true) , b())"); fold("do {f()} while((a = false) ? b() : c())", "do {f()} while((a = false) , c())"); fold("var x = (true) ? 1 : 0", "var x=1"); fold("var y = (true) ? ((false) ? 12 : (cond ? 1 : 2)) : 13", "var y=cond?1:2"); foldSame("var z=x?void 0:y()"); foldSame("z=x?void 0:y()"); foldSame("z*=x?void 0:y()"); foldSame("var z=x?y():void 0"); foldSame("(w?x:void 0).y=z"); foldSame("(w?x:void 0).y+=z"); } public void testConstantConditionWithSideEffect1() { fold("if (b=true) x=1;", "b=true;x=1"); fold("if (b=/ab/) x=1;", "b=/ab/;x=1"); fold("if (b=/ab/){ x=1; } else { x=2; }", "b=/ab/;x=1"); fold("var b;b=/ab/;if(b)x=1;", "var b;b=/ab/;x=1"); foldSame("var b;b=f();if(b)x=1;"); fold("var b=/ab/;if(b)x=1;", "var b=/ab/;x=1"); foldSame("var b=f();if(b)x=1;"); foldSame("b=b++;if(b)x=b;"); fold("(b=0,b=1);if(b)x=b;", "b=0,b=1;if(b)x=b;"); fold("b=1;if(foo,b)x=b;","b=1;x=b;"); foldSame("b=1;if(foo=1,b)x=b;"); } public void testConstantConditionWithSideEffect2() { fold("(b=true)?x=1:x=2;", "b=true,x=1"); fold("(b=false)?x=1:x=2;", "b=false,x=2"); fold("if (b=/ab/) x=1;", "b=/ab/;x=1"); fold("var b;b=/ab/;(b)?x=1:x=2;", "var b;b=/ab/;x=1"); foldSame("var b;b=f();(b)?x=1:x=2;"); fold("var b=/ab/;(b)?x=1:x=2;", "var b=/ab/;x=1"); foldSame("var b=f();(b)?x=1:x=2;"); } public void testVarLifting() { fold("if(true)var a", "var a"); fold("if(false)var a", "var a"); // More var lifting tests in PeepholeIntegrationTests } public void testFoldUselessWhile() { fold("while(false) { foo() }", ""); fold("while(void 0) { foo() }", ""); fold("while(undefined) { foo() }", ""); foldSame("while(true) foo()"); fold("while(false) { var a = 0; }", "var a"); // Make sure it plays nice with minimizing fold("while(false) { foo(); continue }", ""); fold("while(0) { foo() }", ""); } public void testFoldUselessFor() { fold("for(;false;) { foo() }", ""); fold("for(;void 0;) { foo() }", ""); fold("for(;undefined;) { foo() }", ""); fold("for(;true;) foo() ", "for(;;) foo() "); foldSame("for(;;) foo()"); fold("for(;false;) { var a = 0; }", "var a"); // Make sure it plays nice with minimizing fold("for(;false;) { foo(); continue }", ""); } public void testFoldUselessDo() { fold("do { foo() } while(false);", "foo()"); fold("do { foo() } while(void 0);", "foo()"); fold("do { foo() } while(undefined);", "foo()"); fold("do { foo() } while(true);", "do { foo() } while(true);"); fold("do { var a = 0; } while(false);", "var a=0"); fold("do { var a = 0; } while(!{a:foo()});", "var a=0;foo()"); // Can't fold with break or continues. foldSame("do { foo(); continue; } while(0)"); foldSame("do { foo(); break; } while(0)"); } public void testMinimizeWhileConstantCondition() { fold("while(true) foo()", "while(true) foo()"); fold("while(0) foo()", ""); fold("while(0.0) foo()", ""); fold("while(NaN) foo()", ""); fold("while(null) foo()", ""); fold("while(undefined) foo()", ""); fold("while('') foo()", ""); } public void testFoldConstantCommaExpressions() { fold("if (true, false) {foo()}", ""); fold("if (false, true) {foo()}", "foo()"); fold("true, foo()", "foo()"); fold("(1 + 2 + ''), foo()", "foo()"); } public void testRemoveUselessOps() { // There are four place where expression results are discarded: // - a top level expression EXPR_RESULT // - the LHS of a COMMA // - the FOR init expression // - the FOR increment expression // Known side-effect free functions calls are removed. fold("Math.random()", ""); fold("Math.random(f() + g())", "f(),g();"); fold("Math.random(f(),g(),h())", "f(),g(),h();"); // Calls to functions with unknown side-effects are are left. foldSame("f();"); foldSame("(function () {})();"); // Uncalled function expressions are removed fold("(function () {});", ""); fold("(function f() {});", ""); // ... including any code they contain. fold("(function () {foo();});", ""); // Useless operators are removed. fold("+f()", "f()"); fold("a=(+f(),g())", "a=(f(),g())"); fold("a=(true,g())", "a=g()"); fold("f(),true", "f()"); fold("f() + g()", "f(),g()"); fold("for(;;+f()){}", "for(;;f()){}"); fold("for(+f();;g()){}", "for(f();;g()){}"); fold("for(;;Math.random(f(),g(),h())){}", "for(;;f(),g(),h()){}"); // The optimization cascades into conditional expressions: fold("g() && +f()", "g() && f()"); fold("g() || +f()", "g() || f()"); fold("x ? g() : +f()", "x ? g() : f()"); fold("+x()", "x()"); fold("+x() * 2", "x()"); fold("-(+x() * 2)", "x()"); fold("2 -(+x() * 2)", "x()"); fold("x().foo", "x()"); foldSame("x().foo()"); foldSame("x++"); foldSame("++x"); foldSame("x--"); foldSame("--x"); foldSame("x = 2"); foldSame("x *= 2"); // Sanity check, other expression are left alone. foldSame("function f() {}"); foldSame("var x;"); } public void testOptimizeSwitch() { fold("switch(a){}", ""); fold("switch(foo()){}", "foo()"); fold("switch(a){default:}", ""); fold("switch(a){default:break;}", ""); fold("switch(a){default:var b;break;}", "var b"); fold("switch(a){case 1: default:}", ""); fold("switch(a){default: case 1:}", ""); fold("switch(a){default: break; case 1:break;}", ""); fold("switch(a){default: var b; break; case 1: var c; break;}", "var c; var b;"); // Can't remove cases if a default exists. foldSame("function f() {switch(a){default: return; case 1: break;}}"); foldSame("function f() {switch(a){case 1: foo();}}"); foldSame("function f() {switch(a){case 3: case 2: case 1: foo();}}"); fold("function f() {switch(a){case 2: case 1: default: foo();}}", "function f() {switch(a){default: foo();}}"); fold("switch(a){case 1: default:break; case 2: foo()}", "switch(a){case 2: foo()}"); foldSame("switch(a){case 1: goo(); default:break; case 2: foo()}"); // TODO(johnlenz): merge the useless "case 2" foldSame("switch(a){case 1: goo(); case 2:break; case 3: foo()}"); // Can't remove cases if something useful is done. foldSame("switch(a){case 1: var c =2; break;}"); foldSame("function f() {switch(a){case 1: return;}}"); foldSame("x:switch(a){case 1: break x;}"); } public void testRemoveNumber() { test("3", ""); } public void testRemoveVarGet1() { test("a", ""); } public void testRemoveVarGet2() { test("var a = 1;a", "var a = 1"); } public void testRemoveNamespaceGet1() { test("var a = {};a.b", "var a = {}"); } public void testRemoveNamespaceGet2() { test("var a = {};a.b=1;a.b", "var a = {};a.b=1"); } public void testRemovePrototypeGet1() { test("var a = {};a.prototype.b", "var a = {}"); } public void testRemovePrototypeGet2() { test("var a = {};a.prototype.b = 1;a.prototype.b", "var a = {};a.prototype.b = 1"); } public void testRemoveAdd1() { test("1 + 2", ""); } public void testNoRemoveVar1() { testSame("var a = 1"); } public void testNoRemoveVar2() { testSame("var a = 1, b = 2"); } public void testNoRemoveAssign1() { testSame("a = 1"); } public void testNoRemoveAssign2() { testSame("a = b = 1"); } public void testNoRemoveAssign3() { test("1 + (a = 2)", "a = 2"); } public void testNoRemoveAssign4() { testSame("x.a = 1"); } public void testNoRemoveAssign5() { testSame("x.a = x.b = 1"); } public void testNoRemoveAssign6() { test("1 + (x.a = 2)", "x.a = 2"); } public void testNoRemoveCall1() { testSame("a()"); } public void testNoRemoveCall2() { test("a()+b()", "a(),b()"); } public void testNoRemoveCall3() { testSame("a() && b()"); } public void testNoRemoveCall4() { testSame("a() || b()"); } public void testNoRemoveCall5() { test("a() || 1", "a()"); } public void testNoRemoveCall6() { testSame("1 || a()"); } public void testNoRemoveThrow1() { testSame("function f(){throw a()}"); } public void testNoRemoveThrow2() { testSame("function f(){throw a}"); } public void testNoRemoveThrow3() { testSame("function f(){throw 10}"); } public void testRemoveInControlStructure1() { test("if(x()) 1", "x()"); } public void testRemoveInControlStructure2() { test("while(2) 1", "while(2);"); } public void testRemoveInControlStructure3() { test("for(1;2;3) 4", "for(;;);"); } public void testHook1() { test("1 ? 2 : 3", ""); } public void testHook2() { test("x ? a() : 3", "x && a()"); } public void testHook3() { test("x ? 2 : a()", "x || a()"); } public void testHook4() { testSame("x ? a() : b()"); } public void testHook5() { test("a() ? 1 : 2", "a()"); } public void testHook6() { test("a() ? b() : 2", "a() && b()"); } // TODO(johnlenz): Consider adding a post optimization pass to // convert OR into HOOK to save parentheses when the operator // precedents would require them. public void testHook7() { test("a() ? 1 : b()", "a() || b()"); } public void testHook8() { testSame("a() ? b() : c()"); } public void testShortCircuit1() { testSame("1 && a()"); } public void testShortCircuit2() { test("1 && a() && 2", "1 && a()"); } public void testShortCircuit3() { test("a() && 1 && 2", "a()"); } public void testShortCircuit4() { testSame("a() && 1 && b()"); } public void testComplex1() { test("1 && a() + b() + c()", "1 && (a(), b(), c())"); } public void testComplex2() { test("1 && (a() ? b() : 1)", "1 && a() && b()"); } public void testComplex3() { test("1 && (a() ? b() : 1 + c())", "1 && (a() ? b() : c())"); } public void testComplex4() { test("1 && (a() ? 1 : 1 + c())", "1 && (a() || c())"); } public void testComplex5() { // can't simplify lhs of short circuit statements with side effects testSame("(a() ? 1 : 1 + c()) && foo()"); } public void testNoRemoveFunctionDeclaration1() { testSame("function foo(){}"); } public void testNoRemoveFunctionDeclaration2() { testSame("var foo = function (){}"); } public void testNoSimplifyFunctionArgs1() { testSame("f(1 + 2, 3 + g())"); } public void testNoSimplifyFunctionArgs2() { testSame("1 && f(1 + 2, 3 + g())"); } public void testNoSimplifyFunctionArgs3() { testSame("1 && foo(a() ? b() : 1 + c())"); } public void testNoRemoveInherits1() { testSame("var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a)"); } public void testNoRemoveInherits2() { test("var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a) + 1", "var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a)"); } public void testNoRemoveInherits3() { testSame("this.a = {}; var b = {}; b.inherits(a);"); } public void testNoRemoveInherits4() { test("this.a = {}; var b = {}; b.inherits(a) + 1;", "this.a = {}; var b = {}; b.inherits(a)"); } public void testRemoveFromLabel1() { test("LBL: void 0", "LBL: {}"); } public void testRemoveFromLabel2() { test("LBL: foo() + 1 + bar()", "LBL: foo(),bar()"); } public void testCall1() { test("Math.sin(0);", ""); } public void testCall2() { test("1 + Math.sin(0);", ""); } public void testNew1() { test("new Date;", ""); } public void testNew2() { test("1 + new Date;", ""); } public void testFoldAssign() { test("x=x", ""); testSame("x=xy"); testSame("x=x + 1"); testSame("x.a=x.a"); test("var y=(x=x)", "var y=x"); test("y=1 + (x=x)", "y=1 + x"); } public void testTryCatchFinally() { testSame("try {foo()} catch (e) {bar()}"); testSame("try { try {foo()} catch (e) {bar()}} catch (x) {bar()}"); test("try {var x = 1} finally {}", "var x = 1;"); testSame("try {var x = 1} finally {x()}"); test("function f() { return; try{var x = 1}finally{} }", "function f() { return; var x = 1; }"); } public void testObjectLiteral() { test("({})", ""); test("({a:1})", ""); test("({a:foo()})", "foo()"); test("({'a':foo()})", "foo()"); } public void testArrayLiteral() { test("([])", ""); test("([1])", ""); test("([a])", ""); test("([foo()])", "foo()"); } }
// You are a professional Java test case writer, please create a test case named `testCall1` for the issue `Closure-501`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-501 // // ## Issue-Title: // Closure removes needed code. // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Try the following code, in Simple mode // Math.blah = function(test) { test.a = 5; }; // var test = new Object(); // Math.blah(test); // 2. The output is // Math.blah=function(a){a.a=5};var test={}; // // // **What is the expected output? What do you see instead?** // Note that Math.blah(test) was removed. It should not be. It issues a warning: JSC\_USELESS\_CODE: Suspicious code. This code lacks side-effects. Is there a bug? at line 4 character 9 // // **What version of the product are you using? On what operating system?** // Tested on Google hosted Closure service. // // **Please provide any additional information below.** // Closure seems to be protective about Math in particular, and doesn't like people messing around with her? So, when I try the following code:- // var n = {}; // n.blah = function(test) { test.a = 5; }; // var test = new Object(); // n.blah(test); // // It works. When I replace n by Math, then again, Closure kicks out blah. I need that poor fellow. Please talk some sense into it. // // public void testCall1() {
544
61
542
test/com/google/javascript/jscomp/PeepholeRemoveDeadCodeTest.java
test
```markdown ## Issue-ID: Closure-501 ## Issue-Title: Closure removes needed code. ## Issue-Description: **What steps will reproduce the problem?** 1. Try the following code, in Simple mode Math.blah = function(test) { test.a = 5; }; var test = new Object(); Math.blah(test); 2. The output is Math.blah=function(a){a.a=5};var test={}; **What is the expected output? What do you see instead?** Note that Math.blah(test) was removed. It should not be. It issues a warning: JSC\_USELESS\_CODE: Suspicious code. This code lacks side-effects. Is there a bug? at line 4 character 9 **What version of the product are you using? On what operating system?** Tested on Google hosted Closure service. **Please provide any additional information below.** Closure seems to be protective about Math in particular, and doesn't like people messing around with her? So, when I try the following code:- var n = {}; n.blah = function(test) { test.a = 5; }; var test = new Object(); n.blah(test); It works. When I replace n by Math, then again, Closure kicks out blah. I need that poor fellow. Please talk some sense into it. ``` You are a professional Java test case writer, please create a test case named `testCall1` for the issue `Closure-501`, utilizing the provided issue report information and the following function signature. ```java public void testCall1() { ```
542
[ "com.google.javascript.jscomp.NodeUtil" ]
1ecbec3d59855936727a8b41e297fe5a5876dce4c601934e1c15746fb289ad53
public void testCall1()
// You are a professional Java test case writer, please create a test case named `testCall1` for the issue `Closure-501`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-501 // // ## Issue-Title: // Closure removes needed code. // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Try the following code, in Simple mode // Math.blah = function(test) { test.a = 5; }; // var test = new Object(); // Math.blah(test); // 2. The output is // Math.blah=function(a){a.a=5};var test={}; // // // **What is the expected output? What do you see instead?** // Note that Math.blah(test) was removed. It should not be. It issues a warning: JSC\_USELESS\_CODE: Suspicious code. This code lacks side-effects. Is there a bug? at line 4 character 9 // // **What version of the product are you using? On what operating system?** // Tested on Google hosted Closure service. // // **Please provide any additional information below.** // Closure seems to be protective about Math in particular, and doesn't like people messing around with her? So, when I try the following code:- // var n = {}; // n.blah = function(test) { test.a = 5; }; // var test = new Object(); // n.blah(test); // // It works. When I replace n by Math, then again, Closure kicks out blah. I need that poor fellow. Please talk some sense into it. // //
Closure
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Tests for PeepholeRemoveDeadCodeTest in isolation. Tests for the interaction * of multiple peephole passes are in PeepholeIntegrationTest. */ public class PeepholeRemoveDeadCodeTest extends CompilerTestCase { public PeepholeRemoveDeadCodeTest() { super(""); } @Override public void setUp() throws Exception { super.setUp(); enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { PeepholeOptimizationsPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeRemoveDeadCode()); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } public void testFoldBlock() { fold("{{foo()}}", "foo()"); fold("{foo();{}}", "foo()"); fold("{{foo()}{}}", "foo()"); fold("{{foo()}{bar()}}", "foo();bar()"); fold("{if(false)foo(); {bar()}}", "bar()"); fold("{if(false)if(false)if(false)foo(); {bar()}}", "bar()"); fold("{'hi'}", ""); fold("{x==3}", ""); fold("{ (function(){x++}) }", ""); fold("function f(){return;}", "function f(){return;}"); fold("function f(){return 3;}", "function f(){return 3}"); fold("function f(){if(x)return; x=3; return; }", "function f(){if(x)return; x=3; return; }"); fold("{x=3;;;y=2;;;}", "x=3;y=2"); // Cases to test for empty block. fold("while(x()){x}", "while(x());"); fold("while(x()){x()}", "while(x())x()"); fold("for(x=0;x<100;x++){x}", "for(x=0;x<100;x++);"); fold("for(x in y){x}", "for(x in y);"); } /** Try to remove spurious blocks with multiple children */ public void testFoldBlocksWithManyChildren() { fold("function f() { if (false) {} }", "function f(){}"); fold("function f() { { if (false) {} if (true) {} {} } }", "function f(){}"); fold("{var x; var y; var z; function f() { { var a; { var b; } } } }", "var x;var y;var z;function f(){var a;var b}"); } public void testIf() { fold("if (1){ x=1; } else { x = 2;}", "x=1"); fold("if (false){ x = 1; } else { x = 2; }", "x=2"); fold("if (undefined){ x = 1; } else { x = 2; }", "x=2"); fold("if (null){ x = 1; } else { x = 2; }", "x=2"); fold("if (void 0){ x = 1; } else { x = 2; }", "x=2"); fold("if (void foo()){ x = 1; } else { x = 2; }", "foo();x=2"); fold("if (false){ x = 1; } else if (true) { x = 3; } else { x = 2; }", "x=3"); fold("if (x){ x = 1; } else if (false) { x = 3; }", "if(x)x=1"); } public void testHook() { fold("true ? a() : b()", "a()"); fold("false ? a() : b()", "b()"); fold("a() ? b() : true", "a() && b()"); fold("a() ? true : b()", "a() || b()"); fold("(a = true) ? b() : c()", "a = true, b()"); fold("(a = false) ? b() : c()", "a = false, c()"); fold("do {f()} while((a = true) ? b() : c())", "do {f()} while((a = true) , b())"); fold("do {f()} while((a = false) ? b() : c())", "do {f()} while((a = false) , c())"); fold("var x = (true) ? 1 : 0", "var x=1"); fold("var y = (true) ? ((false) ? 12 : (cond ? 1 : 2)) : 13", "var y=cond?1:2"); foldSame("var z=x?void 0:y()"); foldSame("z=x?void 0:y()"); foldSame("z*=x?void 0:y()"); foldSame("var z=x?y():void 0"); foldSame("(w?x:void 0).y=z"); foldSame("(w?x:void 0).y+=z"); } public void testConstantConditionWithSideEffect1() { fold("if (b=true) x=1;", "b=true;x=1"); fold("if (b=/ab/) x=1;", "b=/ab/;x=1"); fold("if (b=/ab/){ x=1; } else { x=2; }", "b=/ab/;x=1"); fold("var b;b=/ab/;if(b)x=1;", "var b;b=/ab/;x=1"); foldSame("var b;b=f();if(b)x=1;"); fold("var b=/ab/;if(b)x=1;", "var b=/ab/;x=1"); foldSame("var b=f();if(b)x=1;"); foldSame("b=b++;if(b)x=b;"); fold("(b=0,b=1);if(b)x=b;", "b=0,b=1;if(b)x=b;"); fold("b=1;if(foo,b)x=b;","b=1;x=b;"); foldSame("b=1;if(foo=1,b)x=b;"); } public void testConstantConditionWithSideEffect2() { fold("(b=true)?x=1:x=2;", "b=true,x=1"); fold("(b=false)?x=1:x=2;", "b=false,x=2"); fold("if (b=/ab/) x=1;", "b=/ab/;x=1"); fold("var b;b=/ab/;(b)?x=1:x=2;", "var b;b=/ab/;x=1"); foldSame("var b;b=f();(b)?x=1:x=2;"); fold("var b=/ab/;(b)?x=1:x=2;", "var b=/ab/;x=1"); foldSame("var b=f();(b)?x=1:x=2;"); } public void testVarLifting() { fold("if(true)var a", "var a"); fold("if(false)var a", "var a"); // More var lifting tests in PeepholeIntegrationTests } public void testFoldUselessWhile() { fold("while(false) { foo() }", ""); fold("while(void 0) { foo() }", ""); fold("while(undefined) { foo() }", ""); foldSame("while(true) foo()"); fold("while(false) { var a = 0; }", "var a"); // Make sure it plays nice with minimizing fold("while(false) { foo(); continue }", ""); fold("while(0) { foo() }", ""); } public void testFoldUselessFor() { fold("for(;false;) { foo() }", ""); fold("for(;void 0;) { foo() }", ""); fold("for(;undefined;) { foo() }", ""); fold("for(;true;) foo() ", "for(;;) foo() "); foldSame("for(;;) foo()"); fold("for(;false;) { var a = 0; }", "var a"); // Make sure it plays nice with minimizing fold("for(;false;) { foo(); continue }", ""); } public void testFoldUselessDo() { fold("do { foo() } while(false);", "foo()"); fold("do { foo() } while(void 0);", "foo()"); fold("do { foo() } while(undefined);", "foo()"); fold("do { foo() } while(true);", "do { foo() } while(true);"); fold("do { var a = 0; } while(false);", "var a=0"); fold("do { var a = 0; } while(!{a:foo()});", "var a=0;foo()"); // Can't fold with break or continues. foldSame("do { foo(); continue; } while(0)"); foldSame("do { foo(); break; } while(0)"); } public void testMinimizeWhileConstantCondition() { fold("while(true) foo()", "while(true) foo()"); fold("while(0) foo()", ""); fold("while(0.0) foo()", ""); fold("while(NaN) foo()", ""); fold("while(null) foo()", ""); fold("while(undefined) foo()", ""); fold("while('') foo()", ""); } public void testFoldConstantCommaExpressions() { fold("if (true, false) {foo()}", ""); fold("if (false, true) {foo()}", "foo()"); fold("true, foo()", "foo()"); fold("(1 + 2 + ''), foo()", "foo()"); } public void testRemoveUselessOps() { // There are four place where expression results are discarded: // - a top level expression EXPR_RESULT // - the LHS of a COMMA // - the FOR init expression // - the FOR increment expression // Known side-effect free functions calls are removed. fold("Math.random()", ""); fold("Math.random(f() + g())", "f(),g();"); fold("Math.random(f(),g(),h())", "f(),g(),h();"); // Calls to functions with unknown side-effects are are left. foldSame("f();"); foldSame("(function () {})();"); // Uncalled function expressions are removed fold("(function () {});", ""); fold("(function f() {});", ""); // ... including any code they contain. fold("(function () {foo();});", ""); // Useless operators are removed. fold("+f()", "f()"); fold("a=(+f(),g())", "a=(f(),g())"); fold("a=(true,g())", "a=g()"); fold("f(),true", "f()"); fold("f() + g()", "f(),g()"); fold("for(;;+f()){}", "for(;;f()){}"); fold("for(+f();;g()){}", "for(f();;g()){}"); fold("for(;;Math.random(f(),g(),h())){}", "for(;;f(),g(),h()){}"); // The optimization cascades into conditional expressions: fold("g() && +f()", "g() && f()"); fold("g() || +f()", "g() || f()"); fold("x ? g() : +f()", "x ? g() : f()"); fold("+x()", "x()"); fold("+x() * 2", "x()"); fold("-(+x() * 2)", "x()"); fold("2 -(+x() * 2)", "x()"); fold("x().foo", "x()"); foldSame("x().foo()"); foldSame("x++"); foldSame("++x"); foldSame("x--"); foldSame("--x"); foldSame("x = 2"); foldSame("x *= 2"); // Sanity check, other expression are left alone. foldSame("function f() {}"); foldSame("var x;"); } public void testOptimizeSwitch() { fold("switch(a){}", ""); fold("switch(foo()){}", "foo()"); fold("switch(a){default:}", ""); fold("switch(a){default:break;}", ""); fold("switch(a){default:var b;break;}", "var b"); fold("switch(a){case 1: default:}", ""); fold("switch(a){default: case 1:}", ""); fold("switch(a){default: break; case 1:break;}", ""); fold("switch(a){default: var b; break; case 1: var c; break;}", "var c; var b;"); // Can't remove cases if a default exists. foldSame("function f() {switch(a){default: return; case 1: break;}}"); foldSame("function f() {switch(a){case 1: foo();}}"); foldSame("function f() {switch(a){case 3: case 2: case 1: foo();}}"); fold("function f() {switch(a){case 2: case 1: default: foo();}}", "function f() {switch(a){default: foo();}}"); fold("switch(a){case 1: default:break; case 2: foo()}", "switch(a){case 2: foo()}"); foldSame("switch(a){case 1: goo(); default:break; case 2: foo()}"); // TODO(johnlenz): merge the useless "case 2" foldSame("switch(a){case 1: goo(); case 2:break; case 3: foo()}"); // Can't remove cases if something useful is done. foldSame("switch(a){case 1: var c =2; break;}"); foldSame("function f() {switch(a){case 1: return;}}"); foldSame("x:switch(a){case 1: break x;}"); } public void testRemoveNumber() { test("3", ""); } public void testRemoveVarGet1() { test("a", ""); } public void testRemoveVarGet2() { test("var a = 1;a", "var a = 1"); } public void testRemoveNamespaceGet1() { test("var a = {};a.b", "var a = {}"); } public void testRemoveNamespaceGet2() { test("var a = {};a.b=1;a.b", "var a = {};a.b=1"); } public void testRemovePrototypeGet1() { test("var a = {};a.prototype.b", "var a = {}"); } public void testRemovePrototypeGet2() { test("var a = {};a.prototype.b = 1;a.prototype.b", "var a = {};a.prototype.b = 1"); } public void testRemoveAdd1() { test("1 + 2", ""); } public void testNoRemoveVar1() { testSame("var a = 1"); } public void testNoRemoveVar2() { testSame("var a = 1, b = 2"); } public void testNoRemoveAssign1() { testSame("a = 1"); } public void testNoRemoveAssign2() { testSame("a = b = 1"); } public void testNoRemoveAssign3() { test("1 + (a = 2)", "a = 2"); } public void testNoRemoveAssign4() { testSame("x.a = 1"); } public void testNoRemoveAssign5() { testSame("x.a = x.b = 1"); } public void testNoRemoveAssign6() { test("1 + (x.a = 2)", "x.a = 2"); } public void testNoRemoveCall1() { testSame("a()"); } public void testNoRemoveCall2() { test("a()+b()", "a(),b()"); } public void testNoRemoveCall3() { testSame("a() && b()"); } public void testNoRemoveCall4() { testSame("a() || b()"); } public void testNoRemoveCall5() { test("a() || 1", "a()"); } public void testNoRemoveCall6() { testSame("1 || a()"); } public void testNoRemoveThrow1() { testSame("function f(){throw a()}"); } public void testNoRemoveThrow2() { testSame("function f(){throw a}"); } public void testNoRemoveThrow3() { testSame("function f(){throw 10}"); } public void testRemoveInControlStructure1() { test("if(x()) 1", "x()"); } public void testRemoveInControlStructure2() { test("while(2) 1", "while(2);"); } public void testRemoveInControlStructure3() { test("for(1;2;3) 4", "for(;;);"); } public void testHook1() { test("1 ? 2 : 3", ""); } public void testHook2() { test("x ? a() : 3", "x && a()"); } public void testHook3() { test("x ? 2 : a()", "x || a()"); } public void testHook4() { testSame("x ? a() : b()"); } public void testHook5() { test("a() ? 1 : 2", "a()"); } public void testHook6() { test("a() ? b() : 2", "a() && b()"); } // TODO(johnlenz): Consider adding a post optimization pass to // convert OR into HOOK to save parentheses when the operator // precedents would require them. public void testHook7() { test("a() ? 1 : b()", "a() || b()"); } public void testHook8() { testSame("a() ? b() : c()"); } public void testShortCircuit1() { testSame("1 && a()"); } public void testShortCircuit2() { test("1 && a() && 2", "1 && a()"); } public void testShortCircuit3() { test("a() && 1 && 2", "a()"); } public void testShortCircuit4() { testSame("a() && 1 && b()"); } public void testComplex1() { test("1 && a() + b() + c()", "1 && (a(), b(), c())"); } public void testComplex2() { test("1 && (a() ? b() : 1)", "1 && a() && b()"); } public void testComplex3() { test("1 && (a() ? b() : 1 + c())", "1 && (a() ? b() : c())"); } public void testComplex4() { test("1 && (a() ? 1 : 1 + c())", "1 && (a() || c())"); } public void testComplex5() { // can't simplify lhs of short circuit statements with side effects testSame("(a() ? 1 : 1 + c()) && foo()"); } public void testNoRemoveFunctionDeclaration1() { testSame("function foo(){}"); } public void testNoRemoveFunctionDeclaration2() { testSame("var foo = function (){}"); } public void testNoSimplifyFunctionArgs1() { testSame("f(1 + 2, 3 + g())"); } public void testNoSimplifyFunctionArgs2() { testSame("1 && f(1 + 2, 3 + g())"); } public void testNoSimplifyFunctionArgs3() { testSame("1 && foo(a() ? b() : 1 + c())"); } public void testNoRemoveInherits1() { testSame("var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a)"); } public void testNoRemoveInherits2() { test("var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a) + 1", "var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a)"); } public void testNoRemoveInherits3() { testSame("this.a = {}; var b = {}; b.inherits(a);"); } public void testNoRemoveInherits4() { test("this.a = {}; var b = {}; b.inherits(a) + 1;", "this.a = {}; var b = {}; b.inherits(a)"); } public void testRemoveFromLabel1() { test("LBL: void 0", "LBL: {}"); } public void testRemoveFromLabel2() { test("LBL: foo() + 1 + bar()", "LBL: foo(),bar()"); } public void testCall1() { test("Math.sin(0);", ""); } public void testCall2() { test("1 + Math.sin(0);", ""); } public void testNew1() { test("new Date;", ""); } public void testNew2() { test("1 + new Date;", ""); } public void testFoldAssign() { test("x=x", ""); testSame("x=xy"); testSame("x=x + 1"); testSame("x.a=x.a"); test("var y=(x=x)", "var y=x"); test("y=1 + (x=x)", "y=1 + x"); } public void testTryCatchFinally() { testSame("try {foo()} catch (e) {bar()}"); testSame("try { try {foo()} catch (e) {bar()}} catch (x) {bar()}"); test("try {var x = 1} finally {}", "var x = 1;"); testSame("try {var x = 1} finally {x()}"); test("function f() { return; try{var x = 1}finally{} }", "function f() { return; var x = 1; }"); } public void testObjectLiteral() { test("({})", ""); test("({a:1})", ""); test("({a:foo()})", "foo()"); test("({'a':foo()})", "foo()"); } public void testArrayLiteral() { test("([])", ""); test("([1])", ""); test("([a])", ""); test("([foo()])", "foo()"); } }
public void testIterateVariable() throws Exception { assertXPathValueIterator(context, "$d", list("a", "b")); assertXPathValue(context, "$d = 'a'", Boolean.TRUE); assertXPathValue(context, "$d = 'b'", Boolean.TRUE); }
org.apache.commons.jxpath.ri.compiler.VariableTest::testIterateVariable
src/test/org/apache/commons/jxpath/ri/compiler/VariableTest.java
279
src/test/org/apache/commons/jxpath/ri/compiler/VariableTest.java
testIterateVariable
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jxpath.ri.compiler; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathTestCase; import org.apache.commons.jxpath.TestMixedModelBean; import org.apache.commons.jxpath.Variables; /** * Test basic functionality of JXPath - infoset types, * operations. * * @author Dmitri Plotnikov * @version $Revision$ $Date$ */ public class VariableTest extends JXPathTestCase { private JXPathContext context; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public VariableTest(String name) { super(name); } public void setUp() { if (context == null) { context = JXPathContext.newContext(new TestMixedModelBean()); context.setFactory(new VariableFactory()); Variables vars = context.getVariables(); vars.declareVariable("a", new Double(1)); vars.declareVariable("b", new Double(1)); vars.declareVariable("c", null); vars.declareVariable("d", new String[] { "a", "b" }); vars.declareVariable("integer", new Integer(1)); vars.declareVariable("nan", new Double(Double.NaN)); vars.declareVariable("x", null); } } public void testVariables() { // Variables assertXPathValueAndPointer(context, "$a", new Double(1), "$a"); } public void testVariablesInExpressions() { assertXPathValue(context, "$a = $b", Boolean.TRUE); assertXPathValue(context, "$a = $nan", Boolean.FALSE); assertXPathValue(context, "$a + 1", new Double(2)); assertXPathValue(context, "$c", null); assertXPathValue(context, "$d[2]", "b"); } public void testInvalidVariableName() { boolean exception = false; try { context.getValue("$none"); } catch (Exception ex) { exception = true; } assertTrue( "Evaluating '$none', expected exception - did not get it", exception); exception = false; try { context.setValue("$none", new Integer(1)); } catch (Exception ex) { exception = true; } assertTrue( "Setting '$none = 1', expected exception - did not get it", exception); } public void testNestedContext() { JXPathContext nestedContext = JXPathContext.newContext(context, null); assertXPathValue(nestedContext, "$a", new Double(1)); } public void testSetValue() { assertXPathSetValue(context, "$x", new Integer(1)); } public void testCreatePathDeclareVariable() { // Calls factory.declareVariable("string") assertXPathCreatePath(context, "$string", null, "$string"); } public void testCreatePathAndSetValueDeclareVariable() { // Calls factory.declareVariable("string") assertXPathCreatePathAndSetValue( context, "$string", "Value", "$string"); } public void testCreatePathDeclareVariableSetCollectionElement() { // Calls factory.declareVariable("stringArray"). // The factory needs to create a collection assertXPathCreatePath( context, "$stringArray[2]", "", "$stringArray[2]"); // See if the factory populated the first element as well assertEquals( "Created <" + "$stringArray[1]" + ">", "Value1", context.getValue("$stringArray[1]")); } public void testCreateAndSetValuePathDeclareVariableSetCollectionElement() { // Calls factory.declareVariable("stringArray"). // The factory needs to create a collection assertXPathCreatePathAndSetValue( context, "$stringArray[2]", "Value2", "$stringArray[2]"); // See if the factory populated the first element as well assertEquals( "Created <" + "$stringArray[1]" + ">", "Value1", context.getValue("$stringArray[1]")); } public void testCreatePathExpandCollection() { context.getVariables().declareVariable( "array", new String[] { "Value1" }); // Does not involve factory at all - just expands the collection assertXPathCreatePath(context, "$array[2]", "", "$array[2]"); // Make sure it is still the same array assertEquals( "Created <" + "$array[1]" + ">", "Value1", context.getValue("$array[1]")); } public void testCreatePathAndSetValueExpandCollection() { context.getVariables().declareVariable( "array", new String[] { "Value1" }); // Does not involve factory at all - just expands the collection assertXPathCreatePathAndSetValue( context, "$array[2]", "Value2", "$array[2]"); // Make sure it is still the same array assertEquals( "Created <" + "$array[1]" + ">", "Value1", context.getValue("$array[1]")); } public void testCreatePathDeclareVariableSetProperty() { // Calls factory.declareVariable("test"). // The factory should create a TestBean assertXPathCreatePath( context, "$test/boolean", Boolean.FALSE, "$test/boolean"); } public void testCreatePathAndSetValueDeclareVariableSetProperty() { // Calls factory.declareVariable("test"). // The factory should create a TestBean assertXPathCreatePathAndSetValue( context, "$test/boolean", Boolean.TRUE, "$test/boolean"); } public void testCreatePathDeclareVariableSetCollectionElementProperty() { // Calls factory.declareVariable("testArray"). // The factory should create a collection of TestBeans. // Then calls factory.createObject(..., collection, "testArray", 1). // That one should produce an instance of TestBean and // put it in the collection at index 1. assertXPathCreatePath( context, "$testArray[2]/boolean", Boolean.FALSE, "$testArray[2]/boolean"); } public void testCreatePathAndSetValueDeclVarSetCollectionElementProperty() { // Calls factory.declareVariable("testArray"). // The factory should create a collection of TestBeans. // Then calls factory.createObject(..., collection, "testArray", 1). // That one should produce an instance of TestBean and // put it in the collection at index 1. assertXPathCreatePathAndSetValue( context, "$testArray[2]/boolean", Boolean.TRUE, "$testArray[2]/boolean"); } public void testRemovePathUndeclareVariable() { // Undeclare variable context.getVariables().declareVariable("temp", "temp"); context.removePath("$temp"); assertTrue( "Undeclare variable", !context.getVariables().isDeclaredVariable("temp")); } public void testRemovePathArrayElement() { // Remove array element - reassigns the new array to the var context.getVariables().declareVariable( "temp", new String[] { "temp1", "temp2" }); context.removePath("$temp[1]"); assertEquals( "Remove array element", "temp2", context.getValue("$temp[1]")); } public void testRemovePathCollectionElement() { // Remove list element - does not create a new list context.getVariables().declareVariable("temp", list("temp1", "temp2")); context.removePath("$temp[1]"); assertEquals( "Remove collection element", "temp2", context.getValue("$temp[1]")); } public void testUnionOfVariableAndNode() throws Exception { assertXPathValue(context, "count($a | /document/vendor/location)", new Double(3)); assertXPathValue(context, "count($a | /list)", new Double(7)); //$o + list which contains six discrete values (one is duped, wrapped in a Container) } public void testIterateVariable() throws Exception { assertXPathValueIterator(context, "$d", list("a", "b")); assertXPathValue(context, "$d = 'a'", Boolean.TRUE); assertXPathValue(context, "$d = 'b'", Boolean.TRUE); } }
// You are a professional Java test case writer, please create a test case named `testIterateVariable` for the issue `JxPath-JXPATH-94`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JxPath-JXPATH-94 // // ## Issue-Title: // equality test for multi-valued variables does not conform to spec // // ## Issue-Description: // // given e.g. variable d= // // // {"a", "b"} // , the spec implies that "$d = 'a'" and that "$d = 'b'". Instead of iterating the variable's components its immediate content (here, the String[]) is compared, causing the aforementioned assertions to fail. // // // // // public void testIterateVariable() throws Exception {
279
6
275
src/test/org/apache/commons/jxpath/ri/compiler/VariableTest.java
src/test
```markdown ## Issue-ID: JxPath-JXPATH-94 ## Issue-Title: equality test for multi-valued variables does not conform to spec ## Issue-Description: given e.g. variable d= {"a", "b"} , the spec implies that "$d = 'a'" and that "$d = 'b'". Instead of iterating the variable's components its immediate content (here, the String[]) is compared, causing the aforementioned assertions to fail. ``` You are a professional Java test case writer, please create a test case named `testIterateVariable` for the issue `JxPath-JXPATH-94`, utilizing the provided issue report information and the following function signature. ```java public void testIterateVariable() throws Exception { ```
275
[ "org.apache.commons.jxpath.ri.compiler.CoreOperationCompare" ]
1fdd450f7357ec0fdac76033fcb27d7cc77e21f223a1d474ffc048165667f08d
public void testIterateVariable() throws Exception
// You are a professional Java test case writer, please create a test case named `testIterateVariable` for the issue `JxPath-JXPATH-94`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JxPath-JXPATH-94 // // ## Issue-Title: // equality test for multi-valued variables does not conform to spec // // ## Issue-Description: // // given e.g. variable d= // // // {"a", "b"} // , the spec implies that "$d = 'a'" and that "$d = 'b'". Instead of iterating the variable's components its immediate content (here, the String[]) is compared, causing the aforementioned assertions to fail. // // // // //
JxPath
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jxpath.ri.compiler; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathTestCase; import org.apache.commons.jxpath.TestMixedModelBean; import org.apache.commons.jxpath.Variables; /** * Test basic functionality of JXPath - infoset types, * operations. * * @author Dmitri Plotnikov * @version $Revision$ $Date$ */ public class VariableTest extends JXPathTestCase { private JXPathContext context; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public VariableTest(String name) { super(name); } public void setUp() { if (context == null) { context = JXPathContext.newContext(new TestMixedModelBean()); context.setFactory(new VariableFactory()); Variables vars = context.getVariables(); vars.declareVariable("a", new Double(1)); vars.declareVariable("b", new Double(1)); vars.declareVariable("c", null); vars.declareVariable("d", new String[] { "a", "b" }); vars.declareVariable("integer", new Integer(1)); vars.declareVariable("nan", new Double(Double.NaN)); vars.declareVariable("x", null); } } public void testVariables() { // Variables assertXPathValueAndPointer(context, "$a", new Double(1), "$a"); } public void testVariablesInExpressions() { assertXPathValue(context, "$a = $b", Boolean.TRUE); assertXPathValue(context, "$a = $nan", Boolean.FALSE); assertXPathValue(context, "$a + 1", new Double(2)); assertXPathValue(context, "$c", null); assertXPathValue(context, "$d[2]", "b"); } public void testInvalidVariableName() { boolean exception = false; try { context.getValue("$none"); } catch (Exception ex) { exception = true; } assertTrue( "Evaluating '$none', expected exception - did not get it", exception); exception = false; try { context.setValue("$none", new Integer(1)); } catch (Exception ex) { exception = true; } assertTrue( "Setting '$none = 1', expected exception - did not get it", exception); } public void testNestedContext() { JXPathContext nestedContext = JXPathContext.newContext(context, null); assertXPathValue(nestedContext, "$a", new Double(1)); } public void testSetValue() { assertXPathSetValue(context, "$x", new Integer(1)); } public void testCreatePathDeclareVariable() { // Calls factory.declareVariable("string") assertXPathCreatePath(context, "$string", null, "$string"); } public void testCreatePathAndSetValueDeclareVariable() { // Calls factory.declareVariable("string") assertXPathCreatePathAndSetValue( context, "$string", "Value", "$string"); } public void testCreatePathDeclareVariableSetCollectionElement() { // Calls factory.declareVariable("stringArray"). // The factory needs to create a collection assertXPathCreatePath( context, "$stringArray[2]", "", "$stringArray[2]"); // See if the factory populated the first element as well assertEquals( "Created <" + "$stringArray[1]" + ">", "Value1", context.getValue("$stringArray[1]")); } public void testCreateAndSetValuePathDeclareVariableSetCollectionElement() { // Calls factory.declareVariable("stringArray"). // The factory needs to create a collection assertXPathCreatePathAndSetValue( context, "$stringArray[2]", "Value2", "$stringArray[2]"); // See if the factory populated the first element as well assertEquals( "Created <" + "$stringArray[1]" + ">", "Value1", context.getValue("$stringArray[1]")); } public void testCreatePathExpandCollection() { context.getVariables().declareVariable( "array", new String[] { "Value1" }); // Does not involve factory at all - just expands the collection assertXPathCreatePath(context, "$array[2]", "", "$array[2]"); // Make sure it is still the same array assertEquals( "Created <" + "$array[1]" + ">", "Value1", context.getValue("$array[1]")); } public void testCreatePathAndSetValueExpandCollection() { context.getVariables().declareVariable( "array", new String[] { "Value1" }); // Does not involve factory at all - just expands the collection assertXPathCreatePathAndSetValue( context, "$array[2]", "Value2", "$array[2]"); // Make sure it is still the same array assertEquals( "Created <" + "$array[1]" + ">", "Value1", context.getValue("$array[1]")); } public void testCreatePathDeclareVariableSetProperty() { // Calls factory.declareVariable("test"). // The factory should create a TestBean assertXPathCreatePath( context, "$test/boolean", Boolean.FALSE, "$test/boolean"); } public void testCreatePathAndSetValueDeclareVariableSetProperty() { // Calls factory.declareVariable("test"). // The factory should create a TestBean assertXPathCreatePathAndSetValue( context, "$test/boolean", Boolean.TRUE, "$test/boolean"); } public void testCreatePathDeclareVariableSetCollectionElementProperty() { // Calls factory.declareVariable("testArray"). // The factory should create a collection of TestBeans. // Then calls factory.createObject(..., collection, "testArray", 1). // That one should produce an instance of TestBean and // put it in the collection at index 1. assertXPathCreatePath( context, "$testArray[2]/boolean", Boolean.FALSE, "$testArray[2]/boolean"); } public void testCreatePathAndSetValueDeclVarSetCollectionElementProperty() { // Calls factory.declareVariable("testArray"). // The factory should create a collection of TestBeans. // Then calls factory.createObject(..., collection, "testArray", 1). // That one should produce an instance of TestBean and // put it in the collection at index 1. assertXPathCreatePathAndSetValue( context, "$testArray[2]/boolean", Boolean.TRUE, "$testArray[2]/boolean"); } public void testRemovePathUndeclareVariable() { // Undeclare variable context.getVariables().declareVariable("temp", "temp"); context.removePath("$temp"); assertTrue( "Undeclare variable", !context.getVariables().isDeclaredVariable("temp")); } public void testRemovePathArrayElement() { // Remove array element - reassigns the new array to the var context.getVariables().declareVariable( "temp", new String[] { "temp1", "temp2" }); context.removePath("$temp[1]"); assertEquals( "Remove array element", "temp2", context.getValue("$temp[1]")); } public void testRemovePathCollectionElement() { // Remove list element - does not create a new list context.getVariables().declareVariable("temp", list("temp1", "temp2")); context.removePath("$temp[1]"); assertEquals( "Remove collection element", "temp2", context.getValue("$temp[1]")); } public void testUnionOfVariableAndNode() throws Exception { assertXPathValue(context, "count($a | /document/vendor/location)", new Double(3)); assertXPathValue(context, "count($a | /list)", new Double(7)); //$o + list which contains six discrete values (one is duped, wrapped in a Container) } public void testIterateVariable() throws Exception { assertXPathValueIterator(context, "$d", list("a", "b")); assertXPathValue(context, "$d = 'a'", Boolean.TRUE); assertXPathValue(context, "$d = 'b'", Boolean.TRUE); } }
@Test public void should_return_zero_if_mock_is_compared_to_itself() { //given Date d = mock(Date.class); d.compareTo(d); Invocation compareTo = this.getLastInvocation(); //when Object result = values.answer(compareTo); //then assertEquals(0, result); }
org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValuesTest::should_return_zero_if_mock_is_compared_to_itself
test/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
77
test/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
should_return_zero_if_mock_is_compared_to_itself
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.stubbing.defaultanswers; import org.junit.Test; import org.mockito.invocation.Invocation; import org.mockitoutil.TestBase; import java.util.*; import static org.mockito.Mockito.mock; @SuppressWarnings("unchecked") public class ReturnsEmptyValuesTest extends TestBase { ReturnsEmptyValues values = new ReturnsEmptyValues(); @Test public void should_return_empty_collections_or_null_for_non_collections() { assertTrue(((Collection) values.returnValueFor(Collection.class)).isEmpty()); assertTrue(((Set) values.returnValueFor(Set.class)).isEmpty()); assertTrue(((SortedSet) values.returnValueFor(SortedSet.class)).isEmpty()); assertTrue(((HashSet) values.returnValueFor(HashSet.class)).isEmpty()); assertTrue(((TreeSet) values.returnValueFor(TreeSet.class)).isEmpty()); assertTrue(((LinkedHashSet) values.returnValueFor(LinkedHashSet.class)).isEmpty()); assertTrue(((List) values.returnValueFor(List.class)).isEmpty()); assertTrue(((ArrayList) values.returnValueFor(ArrayList.class)).isEmpty()); assertTrue(((LinkedList) values.returnValueFor(LinkedList.class)).isEmpty()); assertTrue(((Map) values.returnValueFor(Map.class)).isEmpty()); assertTrue(((SortedMap) values.returnValueFor(SortedMap.class)).isEmpty()); assertTrue(((HashMap) values.returnValueFor(HashMap.class)).isEmpty()); assertTrue(((TreeMap) values.returnValueFor(TreeMap.class)).isEmpty()); assertTrue(((LinkedHashMap) values.returnValueFor(LinkedHashMap.class)).isEmpty()); assertNull(values.returnValueFor(String.class)); } @Test public void should_return_primitive() { assertEquals(false, values.returnValueFor(Boolean.TYPE)); assertEquals((char) 0, values.returnValueFor(Character.TYPE)); assertEquals((byte) 0, values.returnValueFor(Byte.TYPE)); assertEquals((short) 0, values.returnValueFor(Short.TYPE)); assertEquals(0, values.returnValueFor(Integer.TYPE)); assertEquals(0L, values.returnValueFor(Long.TYPE)); assertEquals(0F, values.returnValueFor(Float.TYPE)); assertEquals(0D, values.returnValueFor(Double.TYPE)); } @Test public void should_return_non_zero_for_compareTo_method() { //given Date d = mock(Date.class); d.compareTo(new Date()); Invocation compareTo = this.getLastInvocation(); //when Object result = values.answer(compareTo); //then assertTrue(result != (Object) 0); } @Test public void should_return_zero_if_mock_is_compared_to_itself() { //given Date d = mock(Date.class); d.compareTo(d); Invocation compareTo = this.getLastInvocation(); //when Object result = values.answer(compareTo); //then assertEquals(0, result); } }
// You are a professional Java test case writer, please create a test case named `should_return_zero_if_mock_is_compared_to_itself` for the issue `Mockito-467`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-467 // // ## Issue-Title: // fix some rawtype warnings in tests // // ## Issue-Description: // [Current coverage](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) is **87.76%** // --------------------------------------------------------------------------------------- // // // // > // > Merging [#467](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) into [master](https://codecov.io/gh/mockito/mockito/branch/master?src=pr) will not change coverage // > // > // > // // // // ``` // @@ master #467 diff @@ // ========================================== // Files 263 263 // Lines 4747 4747 // Methods 0 0 // Messages 0 0 // Branches 767 767 // ========================================== // Hits 4166 4166 // Misses 416 416 // Partials 165 165 // ``` // // [![Sunburst](https://camo.githubusercontent.com/977b5c47a26b9014e17af67cdf72511e5c4327e08169dd2f5ed0df612c2b202b/68747470733a2f2f636f6465636f762e696f2f67682f6d6f636b69746f2f6d6f636b69746f2f70756c6c2f3436372f6772617068732f73756e62757273742e7376673f7372633d70722673697a653d313530)](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) // // // // > // > Powered by [Codecov](https://codecov.io?src=pr). Last updated by [3fe0fd7...03d9a48](https://codecov.io/gh/mockito/mockito/compare/3fe0fd7b6c5d8ce41dc4040d3ab3039f8369385c...03d9a480674107305c8101384e2fb2daffc87b4e) // > // > // > // // // // @Test public void should_return_zero_if_mock_is_compared_to_itself() {
77
24
66
test/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
test
```markdown ## Issue-ID: Mockito-467 ## Issue-Title: fix some rawtype warnings in tests ## Issue-Description: [Current coverage](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) is **87.76%** --------------------------------------------------------------------------------------- > > Merging [#467](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) into [master](https://codecov.io/gh/mockito/mockito/branch/master?src=pr) will not change coverage > > > ``` @@ master #467 diff @@ ========================================== Files 263 263 Lines 4747 4747 Methods 0 0 Messages 0 0 Branches 767 767 ========================================== Hits 4166 4166 Misses 416 416 Partials 165 165 ``` [![Sunburst](https://camo.githubusercontent.com/977b5c47a26b9014e17af67cdf72511e5c4327e08169dd2f5ed0df612c2b202b/68747470733a2f2f636f6465636f762e696f2f67682f6d6f636b69746f2f6d6f636b69746f2f70756c6c2f3436372f6772617068732f73756e62757273742e7376673f7372633d70722673697a653d313530)](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) > > Powered by [Codecov](https://codecov.io?src=pr). Last updated by [3fe0fd7...03d9a48](https://codecov.io/gh/mockito/mockito/compare/3fe0fd7b6c5d8ce41dc4040d3ab3039f8369385c...03d9a480674107305c8101384e2fb2daffc87b4e) > > > ``` You are a professional Java test case writer, please create a test case named `should_return_zero_if_mock_is_compared_to_itself` for the issue `Mockito-467`, utilizing the provided issue report information and the following function signature. ```java @Test public void should_return_zero_if_mock_is_compared_to_itself() { ```
66
[ "org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues" ]
1feb4722e3bc81035ba45f5710a63f530ef2f276664e1e59e4ffa960677f5fb6
@Test public void should_return_zero_if_mock_is_compared_to_itself()
// You are a professional Java test case writer, please create a test case named `should_return_zero_if_mock_is_compared_to_itself` for the issue `Mockito-467`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-467 // // ## Issue-Title: // fix some rawtype warnings in tests // // ## Issue-Description: // [Current coverage](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) is **87.76%** // --------------------------------------------------------------------------------------- // // // // > // > Merging [#467](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) into [master](https://codecov.io/gh/mockito/mockito/branch/master?src=pr) will not change coverage // > // > // > // // // // ``` // @@ master #467 diff @@ // ========================================== // Files 263 263 // Lines 4747 4747 // Methods 0 0 // Messages 0 0 // Branches 767 767 // ========================================== // Hits 4166 4166 // Misses 416 416 // Partials 165 165 // ``` // // [![Sunburst](https://camo.githubusercontent.com/977b5c47a26b9014e17af67cdf72511e5c4327e08169dd2f5ed0df612c2b202b/68747470733a2f2f636f6465636f762e696f2f67682f6d6f636b69746f2f6d6f636b69746f2f70756c6c2f3436372f6772617068732f73756e62757273742e7376673f7372633d70722673697a653d313530)](https://codecov.io/gh/mockito/mockito/pull/467?src=pr) // // // // > // > Powered by [Codecov](https://codecov.io?src=pr). Last updated by [3fe0fd7...03d9a48](https://codecov.io/gh/mockito/mockito/compare/3fe0fd7b6c5d8ce41dc4040d3ab3039f8369385c...03d9a480674107305c8101384e2fb2daffc87b4e) // > // > // > // // // //
Mockito
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.stubbing.defaultanswers; import org.junit.Test; import org.mockito.invocation.Invocation; import org.mockitoutil.TestBase; import java.util.*; import static org.mockito.Mockito.mock; @SuppressWarnings("unchecked") public class ReturnsEmptyValuesTest extends TestBase { ReturnsEmptyValues values = new ReturnsEmptyValues(); @Test public void should_return_empty_collections_or_null_for_non_collections() { assertTrue(((Collection) values.returnValueFor(Collection.class)).isEmpty()); assertTrue(((Set) values.returnValueFor(Set.class)).isEmpty()); assertTrue(((SortedSet) values.returnValueFor(SortedSet.class)).isEmpty()); assertTrue(((HashSet) values.returnValueFor(HashSet.class)).isEmpty()); assertTrue(((TreeSet) values.returnValueFor(TreeSet.class)).isEmpty()); assertTrue(((LinkedHashSet) values.returnValueFor(LinkedHashSet.class)).isEmpty()); assertTrue(((List) values.returnValueFor(List.class)).isEmpty()); assertTrue(((ArrayList) values.returnValueFor(ArrayList.class)).isEmpty()); assertTrue(((LinkedList) values.returnValueFor(LinkedList.class)).isEmpty()); assertTrue(((Map) values.returnValueFor(Map.class)).isEmpty()); assertTrue(((SortedMap) values.returnValueFor(SortedMap.class)).isEmpty()); assertTrue(((HashMap) values.returnValueFor(HashMap.class)).isEmpty()); assertTrue(((TreeMap) values.returnValueFor(TreeMap.class)).isEmpty()); assertTrue(((LinkedHashMap) values.returnValueFor(LinkedHashMap.class)).isEmpty()); assertNull(values.returnValueFor(String.class)); } @Test public void should_return_primitive() { assertEquals(false, values.returnValueFor(Boolean.TYPE)); assertEquals((char) 0, values.returnValueFor(Character.TYPE)); assertEquals((byte) 0, values.returnValueFor(Byte.TYPE)); assertEquals((short) 0, values.returnValueFor(Short.TYPE)); assertEquals(0, values.returnValueFor(Integer.TYPE)); assertEquals(0L, values.returnValueFor(Long.TYPE)); assertEquals(0F, values.returnValueFor(Float.TYPE)); assertEquals(0D, values.returnValueFor(Double.TYPE)); } @Test public void should_return_non_zero_for_compareTo_method() { //given Date d = mock(Date.class); d.compareTo(new Date()); Invocation compareTo = this.getLastInvocation(); //when Object result = values.answer(compareTo); //then assertTrue(result != (Object) 0); } @Test public void should_return_zero_if_mock_is_compared_to_itself() { //given Date d = mock(Date.class); d.compareTo(d); Invocation compareTo = this.getLastInvocation(); //when Object result = values.answer(compareTo); //then assertEquals(0, result); } }
@Test public void testStringCreateNumberEnsureNoPrecisionLoss(){ String shouldBeFloat = "1.23"; String shouldBeDouble = "3.40282354e+38"; String shouldBeBigDecimal = "1.797693134862315759e+308"; assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float); assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double); assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal); }
org.apache.commons.lang3.math.NumberUtilsTest::testStringCreateNumberEnsureNoPrecisionLoss
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
130
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
testStringCreateNumberEnsureNoPrecisionLoss
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.math; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import org.junit.Test; /** * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}. * * @version $Id$ */ public class NumberUtilsTest { //----------------------------------------------------------------------- @Test public void testConstructor() { assertNotNull(new NumberUtils()); final Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(NumberUtils.class.getModifiers())); assertFalse(Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#toInt(String)}. */ @Test public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ @Test public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ @Test public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ @Test public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ @Test public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ @Test public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {(@link NumberUtils#createNumber(String)} */ @Test public void testStringCreateNumberEnsureNoPrecisionLoss(){ String shouldBeFloat = "1.23"; String shouldBeDouble = "3.40282354e+38"; String shouldBeBigDecimal = "1.797693134862315759e+308"; assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float); assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double); assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal); } /** * Test for {@link NumberUtils#toDouble(String)}. */ @Test public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ @Test public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ @Test public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ @Test public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ @Test public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ @Test public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } @Test public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", Integer.valueOf("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", Long.valueOf(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", Long.valueOf(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", Long.valueOf(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", Float.valueOf("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", Integer.valueOf("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9a failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 9b failed", 0xFADE == NumberUtils.createNumber("0Xfade").intValue()); assertTrue("createNumber(String) 10a failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertTrue("createNumber(String) 10b failed", -0xFADE == NumberUtils.createNumber("-0Xfade").intValue()); assertEquals("createNumber(String) 11 failed", Double.valueOf("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", Float.valueOf("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", Double.valueOf("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", Double.valueOf("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); assertEquals("createNumber(String) 16 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", Float.valueOf("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); // LANG-693 assertEquals("createNumber(String) LANG-693 failed", Double.valueOf(Double.MAX_VALUE), NumberUtils .createNumber("" + Double.MAX_VALUE)); // LANG-822 // ensure that the underlying negative number would create a BigDecimal final Number bigNum = NumberUtils.createNumber("-1.1E-700F"); assertNotNull(bigNum); assertEquals(BigDecimal.class, bigNum.getClass()); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when preceeded by -- rather than - public void testCreateNumberFailure_1() { NumberUtils.createNumber("--1.1E-700F"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (with decimal) public void testCreateNumberFailure_2() { NumberUtils.createNumber("-1.1E+0-7e00"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (no decimal) public void testCreateNumberFailure_3() { NumberUtils.createNumber("-11E+0-7e00"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (no decimal) public void testCreateNumberFailure_4() { NumberUtils.createNumber("1eE+00001"); } // Tests to show when magnitude causes switch to next Number type // Will probably need to be adjusted if code is changed to check precision (LANG-693) @Test public void testCreateNumberMagnitude() { // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38")); assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38")); // Test Double.MAX_VALUE assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308")); // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal) assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308")); assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678")); assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789")); assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff")); // Does not appear to be a way to create a literal BigInteger of this magnitude assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("0x7fffffffffffffff0")); assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff")); assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("#7fffffffffffffff0")); assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777")); // 63 bits assertEquals(new BigInteger("1777777777777777777777",8), NumberUtils.createNumber("01777777777777777777777"));// 64 bits } @Test public void testCreateFloat() { assertEquals("createFloat(String) failed", Float.valueOf("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(final String str) { try { final Float value = NumberUtils.createFloat(str); fail("createFloat(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateDouble() { assertEquals("createDouble(String) failed", Double.valueOf("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(final String str) { try { final Double value = NumberUtils.createDouble(str); fail("createDouble(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateInteger() { assertEquals("createInteger(String) failed", Integer.valueOf("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(final String str) { try { final Integer value = NumberUtils.createInteger(str); fail("createInteger(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateLong() { assertEquals("createLong(String) failed", Long.valueOf("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(final String str) { try { final Long value = NumberUtils.createLong(str); fail("createLong(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0xff")); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("#ff")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0xff")); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-0"), NumberUtils.createBigInteger("-0")); assertEquals("createBigInteger(String) failed", new BigInteger("0"), NumberUtils.createBigInteger("0")); testCreateBigIntegerFailure("#"); testCreateBigIntegerFailure("-#"); testCreateBigIntegerFailure("0x"); testCreateBigIntegerFailure("-0x"); } protected void testCreateBigIntegerFailure(final String str) { try { final BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); this.testCreateBigDecimalFailure("-"); // sign alone not valid this.testCreateBigDecimalFailure("--"); // comment in NumberUtils suggests some implementations may incorrectly allow this this.testCreateBigDecimalFailure("--0"); this.testCreateBigDecimalFailure("+"); // sign alone not valid this.testCreateBigDecimalFailure("++"); // in case this was also allowed by some JVMs this.testCreateBigDecimalFailure("++0"); } protected void testCreateBigDecimalFailure(final String str) { try { final BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- @Test(expected = IllegalArgumentException.class) public void testMinLong_nullArray() { NumberUtils.min((long[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinLong_emptyArray() { NumberUtils.min(new long[0]); } @Test public void testMinLong() { assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinInt_nullArray() { NumberUtils.min((int[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinInt_emptyArray() { NumberUtils.min(new int[0]); } @Test public void testMinInt() { assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinShort_nullArray() { NumberUtils.min((short[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinShort_emptyArray() { NumberUtils.min(new short[0]); } @Test public void testMinShort() { assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinByte_nullArray() { NumberUtils.min((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinByte_emptyArray() { NumberUtils.min(new byte[0]); } @Test public void testMinByte() { assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinDouble_nullArray() { NumberUtils.min((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinDouble_emptyArray() { NumberUtils.min(new double[0]); } @Test public void testMinDouble() { assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testMinFloat_nullArray() { NumberUtils.min((float[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinFloat_emptyArray() { NumberUtils.min(new float[0]); } @Test public void testMinFloat() { assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } @Test(expected = IllegalArgumentException.class) public void testMaxLong_nullArray() { NumberUtils.max((long[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxLong_emptyArray() { NumberUtils.max(new long[0]); } @Test public void testMaxLong() { assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxInt_nullArray() { NumberUtils.max((int[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxInt_emptyArray() { NumberUtils.max(new int[0]); } @Test public void testMaxInt() { assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxShort_nullArray() { NumberUtils.max((short[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxShort_emptyArray() { NumberUtils.max(new short[0]); } @Test public void testMaxShort() { assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxByte_nullArray() { NumberUtils.max((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxByte_emptyArray() { NumberUtils.max(new byte[0]); } @Test public void testMaxByte() { assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxDouble_nullArray() { NumberUtils.max((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxDouble_emptyArray() { NumberUtils.max(new double[0]); } @Test public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (final IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (final IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testMaxFloat_nullArray() { NumberUtils.max((float[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxFloat_emptyArray() { NumberUtils.max(new float[0]); } @Test public void testMaxFloat() { assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } @Test public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } @Test public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } @Test public void testMinimumShort() { final short low = 1234; final short mid = 1234 + 1; final short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } @Test public void testMinimumByte() { final byte low = 123; final byte mid = 123 + 1; final byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } @Test public void testMinimumDouble() { final double low = 12.3; final double mid = 12.3 + 1; final double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } @Test public void testMinimumFloat() { final float low = 12.3f; final float mid = 12.3f + 1; final float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } @Test public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } @Test public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } @Test public void testMaximumShort() { final short low = 1234; final short mid = 1234 + 1; final short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } @Test public void testMaximumByte() { final byte low = 123; final byte mid = 123 + 1; final byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } @Test public void testMaximumDouble() { final double low = 12.3; final double mid = 12.3 + 1; final double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } @Test public void testMaximumFloat() { final float low = 12.3f; final float mid = 12.3f + 1; final float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } // Testing JDK against old Lang functionality @Test public void testCompareDouble() { assertTrue(Double.compare(Double.NaN, Double.NaN) == 0); assertTrue(Double.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, 1.2d) == +1); assertTrue(Double.compare(Double.NaN, 0.0d) == +1); assertTrue(Double.compare(Double.NaN, -0.0d) == +1); assertTrue(Double.compare(Double.NaN, -1.2d) == +1); assertTrue(Double.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(Double.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(1.2d, Double.NaN) == -1); assertTrue(Double.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(1.2d, 1.2d) == 0); assertTrue(Double.compare(1.2d, 0.0d) == +1); assertTrue(Double.compare(1.2d, -0.0d) == +1); assertTrue(Double.compare(1.2d, -1.2d) == +1); assertTrue(Double.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(0.0d, Double.NaN) == -1); assertTrue(Double.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(0.0d, 1.2d) == -1); assertTrue(Double.compare(0.0d, 0.0d) == 0); assertTrue(Double.compare(0.0d, -0.0d) == +1); assertTrue(Double.compare(0.0d, -1.2d) == +1); assertTrue(Double.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-0.0d, Double.NaN) == -1); assertTrue(Double.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-0.0d, 1.2d) == -1); assertTrue(Double.compare(-0.0d, 0.0d) == -1); assertTrue(Double.compare(-0.0d, -0.0d) == 0); assertTrue(Double.compare(-0.0d, -1.2d) == +1); assertTrue(Double.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-1.2d, Double.NaN) == -1); assertTrue(Double.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-1.2d, 1.2d) == -1); assertTrue(Double.compare(-1.2d, 0.0d) == -1); assertTrue(Double.compare(-1.2d, -0.0d) == -1); assertTrue(Double.compare(-1.2d, -1.2d) == 0); assertTrue(Double.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } @Test public void testCompareFloat() { assertTrue(Float.compare(Float.NaN, Float.NaN) == 0); assertTrue(Float.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, 1.2f) == +1); assertTrue(Float.compare(Float.NaN, 0.0f) == +1); assertTrue(Float.compare(Float.NaN, -0.0f) == +1); assertTrue(Float.compare(Float.NaN, -1.2f) == +1); assertTrue(Float.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(Float.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(1.2f, Float.NaN) == -1); assertTrue(Float.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(1.2f, 1.2f) == 0); assertTrue(Float.compare(1.2f, 0.0f) == +1); assertTrue(Float.compare(1.2f, -0.0f) == +1); assertTrue(Float.compare(1.2f, -1.2f) == +1); assertTrue(Float.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(0.0f, Float.NaN) == -1); assertTrue(Float.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(0.0f, 1.2f) == -1); assertTrue(Float.compare(0.0f, 0.0f) == 0); assertTrue(Float.compare(0.0f, -0.0f) == +1); assertTrue(Float.compare(0.0f, -1.2f) == +1); assertTrue(Float.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-0.0f, Float.NaN) == -1); assertTrue(Float.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-0.0f, 1.2f) == -1); assertTrue(Float.compare(-0.0f, 0.0f) == -1); assertTrue(Float.compare(-0.0f, -0.0f) == 0); assertTrue(Float.compare(-0.0f, -1.2f) == +1); assertTrue(Float.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-1.2f, Float.NaN) == -1); assertTrue(Float.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-1.2f, 1.2f) == -1); assertTrue(Float.compare(-1.2f, 0.0f) == -1); assertTrue(Float.compare(-1.2f, -0.0f) == -1); assertTrue(Float.compare(-1.2f, -1.2f) == 0); assertTrue(Float.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } @Test public void testIsDigits() { assertFalse("isDigits(null) failed", NumberUtils.isDigits(null)); assertFalse("isDigits('') failed", NumberUtils.isDigits("")); assertTrue("isDigits(String) failed", NumberUtils.isDigits("12345")); assertFalse("isDigits(String) neg 1 failed", NumberUtils.isDigits("1234.5")); assertFalse("isDigits(String) neg 3 failed", NumberUtils.isDigits("1ab")); assertFalse("isDigits(String) neg 4 failed", NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ @Test public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); // LANG-664 val = "1.1L"; assertFalse("isNumber(String) LANG-664 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(final String val) { try { final Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (final NumberFormatException e) { return false; } } @SuppressWarnings("cast") // suppress instanceof warning check @Test public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } @Test public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } @Test public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } }
// You are a professional Java test case writer, please create a test case named `testStringCreateNumberEnsureNoPrecisionLoss` for the issue `Lang-LANG-693`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-693 // // ## Issue-Title: // Method createNumber from NumberUtils doesn't work for floating point numbers other than Float // // ## Issue-Description: // // Method createNumber from NumberUtils is trying to parse a string with a floating point number always first as a Float, that will cause that if we send a string with a number that will need a Double or even a BigDecimal the number will be truncate to accommodate into the Float without an exception to be thrown, so in fact we will no be returning ever neither a Double nor a BigDecimal. // // // // // @Test public void testStringCreateNumberEnsureNoPrecisionLoss() {
130
/** * Test for {(@link NumberUtils#createNumber(String)} */
3
121
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-693 ## Issue-Title: Method createNumber from NumberUtils doesn't work for floating point numbers other than Float ## Issue-Description: Method createNumber from NumberUtils is trying to parse a string with a floating point number always first as a Float, that will cause that if we send a string with a number that will need a Double or even a BigDecimal the number will be truncate to accommodate into the Float without an exception to be thrown, so in fact we will no be returning ever neither a Double nor a BigDecimal. ``` You are a professional Java test case writer, please create a test case named `testStringCreateNumberEnsureNoPrecisionLoss` for the issue `Lang-LANG-693`, utilizing the provided issue report information and the following function signature. ```java @Test public void testStringCreateNumberEnsureNoPrecisionLoss() { ```
121
[ "org.apache.commons.lang3.math.NumberUtils" ]
1ff7808e53586a507ce0cab68037e6efc233130fc93540a12de151573fe53ce9
@Test public void testStringCreateNumberEnsureNoPrecisionLoss()
// You are a professional Java test case writer, please create a test case named `testStringCreateNumberEnsureNoPrecisionLoss` for the issue `Lang-LANG-693`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-693 // // ## Issue-Title: // Method createNumber from NumberUtils doesn't work for floating point numbers other than Float // // ## Issue-Description: // // Method createNumber from NumberUtils is trying to parse a string with a floating point number always first as a Float, that will cause that if we send a string with a number that will need a Double or even a BigDecimal the number will be truncate to accommodate into the Float without an exception to be thrown, so in fact we will no be returning ever neither a Double nor a BigDecimal. // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.math; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import org.junit.Test; /** * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}. * * @version $Id$ */ public class NumberUtilsTest { //----------------------------------------------------------------------- @Test public void testConstructor() { assertNotNull(new NumberUtils()); final Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(NumberUtils.class.getModifiers())); assertFalse(Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#toInt(String)}. */ @Test public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ @Test public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ @Test public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ @Test public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ @Test public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ @Test public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {(@link NumberUtils#createNumber(String)} */ @Test public void testStringCreateNumberEnsureNoPrecisionLoss(){ String shouldBeFloat = "1.23"; String shouldBeDouble = "3.40282354e+38"; String shouldBeBigDecimal = "1.797693134862315759e+308"; assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float); assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double); assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal); } /** * Test for {@link NumberUtils#toDouble(String)}. */ @Test public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ @Test public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ @Test public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ @Test public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ @Test public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ @Test public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } @Test public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", Integer.valueOf("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", Long.valueOf(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", Long.valueOf(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", Long.valueOf(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", Float.valueOf("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", Integer.valueOf("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9a failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 9b failed", 0xFADE == NumberUtils.createNumber("0Xfade").intValue()); assertTrue("createNumber(String) 10a failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertTrue("createNumber(String) 10b failed", -0xFADE == NumberUtils.createNumber("-0Xfade").intValue()); assertEquals("createNumber(String) 11 failed", Double.valueOf("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", Float.valueOf("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", Double.valueOf("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", Double.valueOf("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); assertEquals("createNumber(String) 16 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", Float.valueOf("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); // LANG-693 assertEquals("createNumber(String) LANG-693 failed", Double.valueOf(Double.MAX_VALUE), NumberUtils .createNumber("" + Double.MAX_VALUE)); // LANG-822 // ensure that the underlying negative number would create a BigDecimal final Number bigNum = NumberUtils.createNumber("-1.1E-700F"); assertNotNull(bigNum); assertEquals(BigDecimal.class, bigNum.getClass()); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when preceeded by -- rather than - public void testCreateNumberFailure_1() { NumberUtils.createNumber("--1.1E-700F"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (with decimal) public void testCreateNumberFailure_2() { NumberUtils.createNumber("-1.1E+0-7e00"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (no decimal) public void testCreateNumberFailure_3() { NumberUtils.createNumber("-11E+0-7e00"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (no decimal) public void testCreateNumberFailure_4() { NumberUtils.createNumber("1eE+00001"); } // Tests to show when magnitude causes switch to next Number type // Will probably need to be adjusted if code is changed to check precision (LANG-693) @Test public void testCreateNumberMagnitude() { // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38")); assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38")); // Test Double.MAX_VALUE assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308")); // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal) assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308")); assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678")); assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789")); assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff")); // Does not appear to be a way to create a literal BigInteger of this magnitude assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("0x7fffffffffffffff0")); assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff")); assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("#7fffffffffffffff0")); assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777")); // 63 bits assertEquals(new BigInteger("1777777777777777777777",8), NumberUtils.createNumber("01777777777777777777777"));// 64 bits } @Test public void testCreateFloat() { assertEquals("createFloat(String) failed", Float.valueOf("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(final String str) { try { final Float value = NumberUtils.createFloat(str); fail("createFloat(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateDouble() { assertEquals("createDouble(String) failed", Double.valueOf("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(final String str) { try { final Double value = NumberUtils.createDouble(str); fail("createDouble(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateInteger() { assertEquals("createInteger(String) failed", Integer.valueOf("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(final String str) { try { final Integer value = NumberUtils.createInteger(str); fail("createInteger(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateLong() { assertEquals("createLong(String) failed", Long.valueOf("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(final String str) { try { final Long value = NumberUtils.createLong(str); fail("createLong(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0xff")); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("#ff")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0xff")); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-0"), NumberUtils.createBigInteger("-0")); assertEquals("createBigInteger(String) failed", new BigInteger("0"), NumberUtils.createBigInteger("0")); testCreateBigIntegerFailure("#"); testCreateBigIntegerFailure("-#"); testCreateBigIntegerFailure("0x"); testCreateBigIntegerFailure("-0x"); } protected void testCreateBigIntegerFailure(final String str) { try { final BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); this.testCreateBigDecimalFailure("-"); // sign alone not valid this.testCreateBigDecimalFailure("--"); // comment in NumberUtils suggests some implementations may incorrectly allow this this.testCreateBigDecimalFailure("--0"); this.testCreateBigDecimalFailure("+"); // sign alone not valid this.testCreateBigDecimalFailure("++"); // in case this was also allowed by some JVMs this.testCreateBigDecimalFailure("++0"); } protected void testCreateBigDecimalFailure(final String str) { try { final BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- @Test(expected = IllegalArgumentException.class) public void testMinLong_nullArray() { NumberUtils.min((long[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinLong_emptyArray() { NumberUtils.min(new long[0]); } @Test public void testMinLong() { assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinInt_nullArray() { NumberUtils.min((int[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinInt_emptyArray() { NumberUtils.min(new int[0]); } @Test public void testMinInt() { assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinShort_nullArray() { NumberUtils.min((short[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinShort_emptyArray() { NumberUtils.min(new short[0]); } @Test public void testMinShort() { assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinByte_nullArray() { NumberUtils.min((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinByte_emptyArray() { NumberUtils.min(new byte[0]); } @Test public void testMinByte() { assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinDouble_nullArray() { NumberUtils.min((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinDouble_emptyArray() { NumberUtils.min(new double[0]); } @Test public void testMinDouble() { assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testMinFloat_nullArray() { NumberUtils.min((float[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinFloat_emptyArray() { NumberUtils.min(new float[0]); } @Test public void testMinFloat() { assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } @Test(expected = IllegalArgumentException.class) public void testMaxLong_nullArray() { NumberUtils.max((long[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxLong_emptyArray() { NumberUtils.max(new long[0]); } @Test public void testMaxLong() { assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxInt_nullArray() { NumberUtils.max((int[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxInt_emptyArray() { NumberUtils.max(new int[0]); } @Test public void testMaxInt() { assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxShort_nullArray() { NumberUtils.max((short[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxShort_emptyArray() { NumberUtils.max(new short[0]); } @Test public void testMaxShort() { assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxByte_nullArray() { NumberUtils.max((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxByte_emptyArray() { NumberUtils.max(new byte[0]); } @Test public void testMaxByte() { assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxDouble_nullArray() { NumberUtils.max((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxDouble_emptyArray() { NumberUtils.max(new double[0]); } @Test public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (final IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (final IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testMaxFloat_nullArray() { NumberUtils.max((float[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxFloat_emptyArray() { NumberUtils.max(new float[0]); } @Test public void testMaxFloat() { assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } @Test public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } @Test public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } @Test public void testMinimumShort() { final short low = 1234; final short mid = 1234 + 1; final short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } @Test public void testMinimumByte() { final byte low = 123; final byte mid = 123 + 1; final byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } @Test public void testMinimumDouble() { final double low = 12.3; final double mid = 12.3 + 1; final double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } @Test public void testMinimumFloat() { final float low = 12.3f; final float mid = 12.3f + 1; final float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } @Test public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } @Test public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } @Test public void testMaximumShort() { final short low = 1234; final short mid = 1234 + 1; final short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } @Test public void testMaximumByte() { final byte low = 123; final byte mid = 123 + 1; final byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } @Test public void testMaximumDouble() { final double low = 12.3; final double mid = 12.3 + 1; final double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } @Test public void testMaximumFloat() { final float low = 12.3f; final float mid = 12.3f + 1; final float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } // Testing JDK against old Lang functionality @Test public void testCompareDouble() { assertTrue(Double.compare(Double.NaN, Double.NaN) == 0); assertTrue(Double.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, 1.2d) == +1); assertTrue(Double.compare(Double.NaN, 0.0d) == +1); assertTrue(Double.compare(Double.NaN, -0.0d) == +1); assertTrue(Double.compare(Double.NaN, -1.2d) == +1); assertTrue(Double.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(Double.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(1.2d, Double.NaN) == -1); assertTrue(Double.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(1.2d, 1.2d) == 0); assertTrue(Double.compare(1.2d, 0.0d) == +1); assertTrue(Double.compare(1.2d, -0.0d) == +1); assertTrue(Double.compare(1.2d, -1.2d) == +1); assertTrue(Double.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(0.0d, Double.NaN) == -1); assertTrue(Double.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(0.0d, 1.2d) == -1); assertTrue(Double.compare(0.0d, 0.0d) == 0); assertTrue(Double.compare(0.0d, -0.0d) == +1); assertTrue(Double.compare(0.0d, -1.2d) == +1); assertTrue(Double.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-0.0d, Double.NaN) == -1); assertTrue(Double.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-0.0d, 1.2d) == -1); assertTrue(Double.compare(-0.0d, 0.0d) == -1); assertTrue(Double.compare(-0.0d, -0.0d) == 0); assertTrue(Double.compare(-0.0d, -1.2d) == +1); assertTrue(Double.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-1.2d, Double.NaN) == -1); assertTrue(Double.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-1.2d, 1.2d) == -1); assertTrue(Double.compare(-1.2d, 0.0d) == -1); assertTrue(Double.compare(-1.2d, -0.0d) == -1); assertTrue(Double.compare(-1.2d, -1.2d) == 0); assertTrue(Double.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } @Test public void testCompareFloat() { assertTrue(Float.compare(Float.NaN, Float.NaN) == 0); assertTrue(Float.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, 1.2f) == +1); assertTrue(Float.compare(Float.NaN, 0.0f) == +1); assertTrue(Float.compare(Float.NaN, -0.0f) == +1); assertTrue(Float.compare(Float.NaN, -1.2f) == +1); assertTrue(Float.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(Float.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(1.2f, Float.NaN) == -1); assertTrue(Float.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(1.2f, 1.2f) == 0); assertTrue(Float.compare(1.2f, 0.0f) == +1); assertTrue(Float.compare(1.2f, -0.0f) == +1); assertTrue(Float.compare(1.2f, -1.2f) == +1); assertTrue(Float.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(0.0f, Float.NaN) == -1); assertTrue(Float.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(0.0f, 1.2f) == -1); assertTrue(Float.compare(0.0f, 0.0f) == 0); assertTrue(Float.compare(0.0f, -0.0f) == +1); assertTrue(Float.compare(0.0f, -1.2f) == +1); assertTrue(Float.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-0.0f, Float.NaN) == -1); assertTrue(Float.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-0.0f, 1.2f) == -1); assertTrue(Float.compare(-0.0f, 0.0f) == -1); assertTrue(Float.compare(-0.0f, -0.0f) == 0); assertTrue(Float.compare(-0.0f, -1.2f) == +1); assertTrue(Float.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-1.2f, Float.NaN) == -1); assertTrue(Float.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-1.2f, 1.2f) == -1); assertTrue(Float.compare(-1.2f, 0.0f) == -1); assertTrue(Float.compare(-1.2f, -0.0f) == -1); assertTrue(Float.compare(-1.2f, -1.2f) == 0); assertTrue(Float.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } @Test public void testIsDigits() { assertFalse("isDigits(null) failed", NumberUtils.isDigits(null)); assertFalse("isDigits('') failed", NumberUtils.isDigits("")); assertTrue("isDigits(String) failed", NumberUtils.isDigits("12345")); assertFalse("isDigits(String) neg 1 failed", NumberUtils.isDigits("1234.5")); assertFalse("isDigits(String) neg 3 failed", NumberUtils.isDigits("1ab")); assertFalse("isDigits(String) neg 4 failed", NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ @Test public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); // LANG-664 val = "1.1L"; assertFalse("isNumber(String) LANG-664 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(final String val) { try { final Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (final NumberFormatException e) { return false; } } @SuppressWarnings("cast") // suppress instanceof warning check @Test public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } @Test public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } @Test public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } }
public void testUnmodifiable() throws Exception { ObjectMapper mapper = new ObjectMapper(); Class<?> unmodSetType = Collections.unmodifiableSet(Collections.<String>emptySet()).getClass(); mapper.addMixIn(unmodSetType, UnmodifiableSetMixin.class); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); final String EXPECTED_JSON = "[\""+unmodSetType.getName()+"\",[]]"; Set<?> foo = mapper.readValue(EXPECTED_JSON, Set.class); assertTrue(foo.isEmpty()); }
com.fasterxml.jackson.databind.creators.ArrayDelegatorCreatorForCollectionTest::testUnmodifiable
src/test/java/com/fasterxml/jackson/databind/creators/ArrayDelegatorCreatorForCollectionTest.java
29
src/test/java/com/fasterxml/jackson/databind/creators/ArrayDelegatorCreatorForCollectionTest.java
testUnmodifiable
package com.fasterxml.jackson.databind.creators; import java.util.Collections; import java.util.Set; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; public class ArrayDelegatorCreatorForCollectionTest extends BaseMapTest { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) abstract static class UnmodifiableSetMixin { @JsonCreator public UnmodifiableSetMixin(Set<?> s) {} } public void testUnmodifiable() throws Exception { ObjectMapper mapper = new ObjectMapper(); Class<?> unmodSetType = Collections.unmodifiableSet(Collections.<String>emptySet()).getClass(); mapper.addMixIn(unmodSetType, UnmodifiableSetMixin.class); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); final String EXPECTED_JSON = "[\""+unmodSetType.getName()+"\",[]]"; Set<?> foo = mapper.readValue(EXPECTED_JSON, Set.class); assertTrue(foo.isEmpty()); } }
// You are a professional Java test case writer, please create a test case named `testUnmodifiable` for the issue `JacksonDatabind-1392`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1392 // // ## Issue-Title: // Custom UnmodifiableSetMixin Fails in Jackson 2.7+ but works in Jackson 2.6 // // ## Issue-Description: // I'd like to be able to deserialize an `UnmodifiableSet` with default typing enabled. To do this I have created an `UnmodifiableSetMixin` as shown below: // // // **NOTE**: You can find a minimal project with all the source code to reproduce this issue at <https://github.com/rwinch/jackson-unmodifiableset-mixin> // // // // ``` // import com.fasterxml.jackson.annotation.JsonCreator; // import com.fasterxml.jackson.annotation.JsonTypeInfo; // // import java.util.Set; // // @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) // public abstract class UnmodifiableSetMixin { // // @JsonCreator // public UnmodifiableSetMixin(Set<?> s) {} // } // ``` // // I then try to use this to deserialize an empty set. // // // // ``` // public class UnmodifiableSetMixinTest { // static final String EXPECTED\_JSON = "[\"java.util.Collections$UnmodifiableSet\",[]]"; // // ObjectMapper mapper; // // @Before // public void setup() { // mapper = new ObjectMapper(); // mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON\_FINAL, JsonTypeInfo.As.PROPERTY); // mapper.addMixIn(Collections.unmodifiableSet(Collections.<String>emptySet()).getClass(), UnmodifiableSetMixin.class); // } // @Test // @SuppressWarnings("unchecked") // public void read() throws Exception { // Set<String> foo = mapper.readValue(EXPECTED\_JSON, Set.class); // assertThat(foo).isEmpty(); // } // } // ``` // // The test passes with Jackson 2.6, but fails using Jackson 2.7+ (including Jackson 2.8.3) with the following stack trace: // // // // ``` // java.lang.IllegalStateException: No default constructor for [collection type; class java.util.Collections$UnmodifiableSet, contains [simple type, class java.lang.Object]] // at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createUsingDefault(StdValueInstantiator.java:240) // at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:249) // at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) // at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:110) // at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromArray(AsArrayTypeDeserializer.java:50) // at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserializeWithType(CollectionDeserializer.java:310) // at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:42) // at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3788) // at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2779) // at sample.Unmod public void testUnmodifiable() throws Exception {
29
62
18
src/test/java/com/fasterxml/jackson/databind/creators/ArrayDelegatorCreatorForCollectionTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1392 ## Issue-Title: Custom UnmodifiableSetMixin Fails in Jackson 2.7+ but works in Jackson 2.6 ## Issue-Description: I'd like to be able to deserialize an `UnmodifiableSet` with default typing enabled. To do this I have created an `UnmodifiableSetMixin` as shown below: **NOTE**: You can find a minimal project with all the source code to reproduce this issue at <https://github.com/rwinch/jackson-unmodifiableset-mixin> ``` import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeInfo; import java.util.Set; @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) public abstract class UnmodifiableSetMixin { @JsonCreator public UnmodifiableSetMixin(Set<?> s) {} } ``` I then try to use this to deserialize an empty set. ``` public class UnmodifiableSetMixinTest { static final String EXPECTED\_JSON = "[\"java.util.Collections$UnmodifiableSet\",[]]"; ObjectMapper mapper; @Before public void setup() { mapper = new ObjectMapper(); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON\_FINAL, JsonTypeInfo.As.PROPERTY); mapper.addMixIn(Collections.unmodifiableSet(Collections.<String>emptySet()).getClass(), UnmodifiableSetMixin.class); } @Test @SuppressWarnings("unchecked") public void read() throws Exception { Set<String> foo = mapper.readValue(EXPECTED\_JSON, Set.class); assertThat(foo).isEmpty(); } } ``` The test passes with Jackson 2.6, but fails using Jackson 2.7+ (including Jackson 2.8.3) with the following stack trace: ``` java.lang.IllegalStateException: No default constructor for [collection type; class java.util.Collections$UnmodifiableSet, contains [simple type, class java.lang.Object]] at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createUsingDefault(StdValueInstantiator.java:240) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:249) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:110) at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromArray(AsArrayTypeDeserializer.java:50) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserializeWithType(CollectionDeserializer.java:310) at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:42) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3788) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2779) at sample.Unmod ``` You are a professional Java test case writer, please create a test case named `testUnmodifiable` for the issue `JacksonDatabind-1392`, utilizing the provided issue report information and the following function signature. ```java public void testUnmodifiable() throws Exception { ```
18
[ "com.fasterxml.jackson.databind.deser.std.CollectionDeserializer" ]
2124dddf6cf64e8a0bc0555354851bf3746407e41d911f2ae60cd70f0a2d17e0
public void testUnmodifiable() throws Exception
// You are a professional Java test case writer, please create a test case named `testUnmodifiable` for the issue `JacksonDatabind-1392`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1392 // // ## Issue-Title: // Custom UnmodifiableSetMixin Fails in Jackson 2.7+ but works in Jackson 2.6 // // ## Issue-Description: // I'd like to be able to deserialize an `UnmodifiableSet` with default typing enabled. To do this I have created an `UnmodifiableSetMixin` as shown below: // // // **NOTE**: You can find a minimal project with all the source code to reproduce this issue at <https://github.com/rwinch/jackson-unmodifiableset-mixin> // // // // ``` // import com.fasterxml.jackson.annotation.JsonCreator; // import com.fasterxml.jackson.annotation.JsonTypeInfo; // // import java.util.Set; // // @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) // public abstract class UnmodifiableSetMixin { // // @JsonCreator // public UnmodifiableSetMixin(Set<?> s) {} // } // ``` // // I then try to use this to deserialize an empty set. // // // // ``` // public class UnmodifiableSetMixinTest { // static final String EXPECTED\_JSON = "[\"java.util.Collections$UnmodifiableSet\",[]]"; // // ObjectMapper mapper; // // @Before // public void setup() { // mapper = new ObjectMapper(); // mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON\_FINAL, JsonTypeInfo.As.PROPERTY); // mapper.addMixIn(Collections.unmodifiableSet(Collections.<String>emptySet()).getClass(), UnmodifiableSetMixin.class); // } // @Test // @SuppressWarnings("unchecked") // public void read() throws Exception { // Set<String> foo = mapper.readValue(EXPECTED\_JSON, Set.class); // assertThat(foo).isEmpty(); // } // } // ``` // // The test passes with Jackson 2.6, but fails using Jackson 2.7+ (including Jackson 2.8.3) with the following stack trace: // // // // ``` // java.lang.IllegalStateException: No default constructor for [collection type; class java.util.Collections$UnmodifiableSet, contains [simple type, class java.lang.Object]] // at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createUsingDefault(StdValueInstantiator.java:240) // at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:249) // at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) // at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:110) // at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromArray(AsArrayTypeDeserializer.java:50) // at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserializeWithType(CollectionDeserializer.java:310) // at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:42) // at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3788) // at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2779) // at sample.Unmod
JacksonDatabind
package com.fasterxml.jackson.databind.creators; import java.util.Collections; import java.util.Set; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; public class ArrayDelegatorCreatorForCollectionTest extends BaseMapTest { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) abstract static class UnmodifiableSetMixin { @JsonCreator public UnmodifiableSetMixin(Set<?> s) {} } public void testUnmodifiable() throws Exception { ObjectMapper mapper = new ObjectMapper(); Class<?> unmodSetType = Collections.unmodifiableSet(Collections.<String>emptySet()).getClass(); mapper.addMixIn(unmodSetType, UnmodifiableSetMixin.class); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); final String EXPECTED_JSON = "[\""+unmodSetType.getName()+"\",[]]"; Set<?> foo = mapper.readValue(EXPECTED_JSON, Set.class); assertTrue(foo.isEmpty()); } }
public void testCOMPRESS178() throws Exception { final File input = getFile("COMPRESS-178.tar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is); try { in.getNextEntry(); fail("Expected IOException"); } catch (IOException e) { Throwable t = e.getCause(); assertTrue("Expected cause = IllegalArgumentException", t instanceof IllegalArgumentException); } in.close(); }
org.apache.commons.compress.archivers.TarTestCase::testCOMPRESS178
src/test/java/org/apache/commons/compress/archivers/TarTestCase.java
315
src/test/java/org/apache/commons/compress/archivers/TarTestCase.java
testCOMPRESS178
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.compress.archivers; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.compress.AbstractTestCase; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.utils.IOUtils; public final class TarTestCase extends AbstractTestCase { public void testTarArchiveCreation() throws Exception { final File output = new File(dir, "bla.tar"); final File file1 = getFile("test1.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out); final TarArchiveEntry entry = new TarArchiveEntry("testdata/test1.xml"); entry.setModTime(0); entry.setSize(file1.length()); entry.setUserId(0); entry.setGroupId(0); entry.setUserName("avalon"); entry.setGroupName("excalibur"); entry.setMode(0100000); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.close(); } public void testTarArchiveLongNameCreation() throws Exception { String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml"; byte[] bytes = name.getBytes("UTF-8"); assertEquals(bytes.length, 99); final File output = new File(dir, "bla.tar"); final File file1 = getFile("test1.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out); final TarArchiveEntry entry = new TarArchiveEntry(name); entry.setModTime(0); entry.setSize(file1.length()); entry.setUserId(0); entry.setGroupId(0); entry.setUserName("avalon"); entry.setGroupName("excalibur"); entry.setMode(0100000); os.putArchiveEntry(entry); FileInputStream in = new FileInputStream(file1); IOUtils.copy(in, os); os.closeArchiveEntry(); os.close(); out.close(); in.close(); ArchiveOutputStream os2 = null; try { String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml"; final File output2 = new File(dir, "bla.tar"); final OutputStream out2 = new FileOutputStream(output2); os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2); final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName); entry2.setModTime(0); entry2.setSize(file1.length()); entry2.setUserId(0); entry2.setGroupId(0); entry2.setUserName("avalon"); entry2.setGroupName("excalibur"); entry2.setMode(0100000); os2.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), os2); os2.closeArchiveEntry(); } catch(IOException e) { assertTrue(true); } finally { if (os2 != null){ os2.close(); } } } public void testTarUnarchive() throws Exception { final File input = getFile("bla.tar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is); final TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry(); final OutputStream out = new FileOutputStream(new File(dir, entry.getName())); IOUtils.copy(in, out); in.close(); out.close(); } public void testCOMPRESS114() throws Exception { final File input = getFile("COMPRESS-114.tar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is); TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry(); assertEquals("3\u00b1\u00b1\u00b1F06\u00b1W2345\u00b1ZB\u00b1la\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1BLA", entry.getName()); entry = (TarArchiveEntry)in.getNextEntry(); assertEquals("0302-0601-3\u00b1\u00b1\u00b1F06\u00b1W2345\u00b1ZB\u00b1la\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1BLA",entry.getName()); in.close(); } public void testDirectoryEntryFromFile() throws Exception { File[] tmp = createTempDirAndFile(); File archive = null; TarArchiveOutputStream tos = null; TarArchiveInputStream tis = null; try { archive = File.createTempFile("test.", ".tar", tmp[0]); archive.deleteOnExit(); tos = new TarArchiveOutputStream(new FileOutputStream(archive)); long beforeArchiveWrite = tmp[0].lastModified(); TarArchiveEntry in = new TarArchiveEntry(tmp[0], "foo"); tos.putArchiveEntry(in); tos.closeArchiveEntry(); tos.close(); tos = null; tis = new TarArchiveInputStream(new FileInputStream(archive)); TarArchiveEntry out = tis.getNextTarEntry(); tis.close(); tis = null; assertNotNull(out); assertEquals("foo/", out.getName()); assertEquals(0, out.getSize()); // TAR stores time with a granularity of 1 second assertEquals(beforeArchiveWrite / 1000, out.getLastModifiedDate().getTime() / 1000); assertTrue(out.isDirectory()); } finally { if (tis != null) { tis.close(); } if (tos != null) { tos.close(); } tryHardToDelete(archive); tryHardToDelete(tmp[1]); rmdir(tmp[0]); } } public void testExplicitDirectoryEntry() throws Exception { File[] tmp = createTempDirAndFile(); File archive = null; TarArchiveOutputStream tos = null; TarArchiveInputStream tis = null; try { archive = File.createTempFile("test.", ".tar", tmp[0]); archive.deleteOnExit(); tos = new TarArchiveOutputStream(new FileOutputStream(archive)); long beforeArchiveWrite = tmp[0].lastModified(); TarArchiveEntry in = new TarArchiveEntry("foo/"); in.setModTime(beforeArchiveWrite); tos.putArchiveEntry(in); tos.closeArchiveEntry(); tos.close(); tos = null; tis = new TarArchiveInputStream(new FileInputStream(archive)); TarArchiveEntry out = tis.getNextTarEntry(); tis.close(); tis = null; assertNotNull(out); assertEquals("foo/", out.getName()); assertEquals(0, out.getSize()); assertEquals(beforeArchiveWrite / 1000, out.getLastModifiedDate().getTime() / 1000); assertTrue(out.isDirectory()); } finally { if (tis != null) { tis.close(); } if (tos != null) { tos.close(); } tryHardToDelete(archive); tryHardToDelete(tmp[1]); rmdir(tmp[0]); } } public void testFileEntryFromFile() throws Exception { File[] tmp = createTempDirAndFile(); File archive = null; TarArchiveOutputStream tos = null; TarArchiveInputStream tis = null; FileInputStream fis = null; try { archive = File.createTempFile("test.", ".tar", tmp[0]); archive.deleteOnExit(); tos = new TarArchiveOutputStream(new FileOutputStream(archive)); TarArchiveEntry in = new TarArchiveEntry(tmp[1], "foo"); tos.putArchiveEntry(in); byte[] b = new byte[(int) tmp[1].length()]; fis = new FileInputStream(tmp[1]); while (fis.read(b) > 0) { tos.write(b); } fis.close(); fis = null; tos.closeArchiveEntry(); tos.close(); tos = null; tis = new TarArchiveInputStream(new FileInputStream(archive)); TarArchiveEntry out = tis.getNextTarEntry(); tis.close(); tis = null; assertNotNull(out); assertEquals("foo", out.getName()); assertEquals(tmp[1].length(), out.getSize()); assertEquals(tmp[1].lastModified() / 1000, out.getLastModifiedDate().getTime() / 1000); assertFalse(out.isDirectory()); } finally { if (tis != null) { tis.close(); } if (tos != null) { tos.close(); } tryHardToDelete(archive); if (fis != null) { fis.close(); } tryHardToDelete(tmp[1]); rmdir(tmp[0]); } } public void testExplicitFileEntry() throws Exception { File[] tmp = createTempDirAndFile(); File archive = null; TarArchiveOutputStream tos = null; TarArchiveInputStream tis = null; FileInputStream fis = null; try { archive = File.createTempFile("test.", ".tar", tmp[0]); archive.deleteOnExit(); tos = new TarArchiveOutputStream(new FileOutputStream(archive)); TarArchiveEntry in = new TarArchiveEntry("foo"); in.setModTime(tmp[1].lastModified()); in.setSize(tmp[1].length()); tos.putArchiveEntry(in); byte[] b = new byte[(int) tmp[1].length()]; fis = new FileInputStream(tmp[1]); while (fis.read(b) > 0) { tos.write(b); } fis.close(); fis = null; tos.closeArchiveEntry(); tos.close(); tos = null; tis = new TarArchiveInputStream(new FileInputStream(archive)); TarArchiveEntry out = tis.getNextTarEntry(); tis.close(); tis = null; assertNotNull(out); assertEquals("foo", out.getName()); assertEquals(tmp[1].length(), out.getSize()); assertEquals(tmp[1].lastModified() / 1000, out.getLastModifiedDate().getTime() / 1000); assertFalse(out.isDirectory()); } finally { if (tis != null) { tis.close(); } if (tos != null) { tos.close(); } tryHardToDelete(archive); if (fis != null) { fis.close(); } tryHardToDelete(tmp[1]); rmdir(tmp[0]); } } public void testCOMPRESS178() throws Exception { final File input = getFile("COMPRESS-178.tar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is); try { in.getNextEntry(); fail("Expected IOException"); } catch (IOException e) { Throwable t = e.getCause(); assertTrue("Expected cause = IllegalArgumentException", t instanceof IllegalArgumentException); } in.close(); } }
// You are a professional Java test case writer, please create a test case named `testCOMPRESS178` for the issue `Compress-COMPRESS-178`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-178 // // ## Issue-Title: // TarArchiveInputStream throws IllegalArgumentException instead of IOException // // ## Issue-Description: // // TarArchiveInputStream is throwing IllegalArgumentException instead of IOException on corrupt files, in direct contradiction to the Javadoc. Here is a stack-trace: // // // // // ``` // java.lang.IllegalArgumentException: Invalid byte -1 at offset 7 in '<some bytes>' len=8 // at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:86) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:790) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:308) // at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:198) // at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextEntry(TarArchiveInputStream.java:380) // at de.schlichtherle.truezip.fs.archive.tar.TarInputShop.<init>(TarInputShop.java:91) // at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newTarInputShop(TarDriver.java:159) // at de.schlichtherle.truezip.fs.archive.tar.TarGZipDriver.newTarInputShop(TarGZipDriver.java:82) // at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newInputShop(TarDriver.java:151) // at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newInputShop(TarDriver.java:47) // at de.schlichtherle.truezip.fs.archive.FsDefaultArchiveController.mount(FsDefaultArchiveController.java:170) // at de.schlichtherle.truezip.fs.archive.FsFileSystemArchiveController$ResetFileSystem.autoMount(FsFileSystemArchiveController.java:98) // at de.schlichtherle.truezip.fs.archive.FsFileSystemArchiveController.autoMount(FsFileSystemArchiveController.java:47) // at de.schlichtherle.truezip.fs.archive.FsArchiveController.autoMount(FsArchiveController.java:129) // at de.schlichtherle.truezip.fs.archive.FsArchiveController.getEntry(FsArchiveController.java:160) // at de.schlichtherle.truezip.fs.archive.FsContextController.getEntry(FsContextController.java:117) // at de.schlichtherle.truezip.fs.FsDecoratingController.getEntry(FsDecoratingController.java:76) // at de.schlichtherle.truezip.fs.FsDecoratingController.getEntry(FsDecoratingController.java:76) // at de.schlichtherle.truezip.fs.FsConcurrentController.getEntry(FsConcurrentController.java:164) // at de.schlichtherle.truezip.fs.FsSyncController.getEntry(FsSyncController.java:108) // at de.schlichtherle.truezip.fs.FsFederatingController.getEntry(FsFederatingController.java:156) // at de.schlichtherle.truezip.nio.file.TFileSystem.newDirectoryStream(TFileSystem.java:348) // at de.schlichtherle.truezip.nio.file.TPath.newDirectoryStream(TPath.java:963) // at de.schlichtherle.truezip.nio.file.TFileSystemProvider.newDirectoryStream(TFileSystemProvider.java:344) // at java.nio.file.Files.newDirectoryStream(Files.java:400) // at com.googlecode.boostmavenproject.GetSourcesMojo.convertToJar(GetSourcesMojo.java:248) // at com.googlecode.boostmavenproject.GetSourcesMojo.download(GetSources public void testCOMPRESS178() throws Exception {
315
12
303
src/test/java/org/apache/commons/compress/archivers/TarTestCase.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-178 ## Issue-Title: TarArchiveInputStream throws IllegalArgumentException instead of IOException ## Issue-Description: TarArchiveInputStream is throwing IllegalArgumentException instead of IOException on corrupt files, in direct contradiction to the Javadoc. Here is a stack-trace: ``` java.lang.IllegalArgumentException: Invalid byte -1 at offset 7 in '<some bytes>' len=8 at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:86) at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:790) at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:308) at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:198) at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextEntry(TarArchiveInputStream.java:380) at de.schlichtherle.truezip.fs.archive.tar.TarInputShop.<init>(TarInputShop.java:91) at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newTarInputShop(TarDriver.java:159) at de.schlichtherle.truezip.fs.archive.tar.TarGZipDriver.newTarInputShop(TarGZipDriver.java:82) at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newInputShop(TarDriver.java:151) at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newInputShop(TarDriver.java:47) at de.schlichtherle.truezip.fs.archive.FsDefaultArchiveController.mount(FsDefaultArchiveController.java:170) at de.schlichtherle.truezip.fs.archive.FsFileSystemArchiveController$ResetFileSystem.autoMount(FsFileSystemArchiveController.java:98) at de.schlichtherle.truezip.fs.archive.FsFileSystemArchiveController.autoMount(FsFileSystemArchiveController.java:47) at de.schlichtherle.truezip.fs.archive.FsArchiveController.autoMount(FsArchiveController.java:129) at de.schlichtherle.truezip.fs.archive.FsArchiveController.getEntry(FsArchiveController.java:160) at de.schlichtherle.truezip.fs.archive.FsContextController.getEntry(FsContextController.java:117) at de.schlichtherle.truezip.fs.FsDecoratingController.getEntry(FsDecoratingController.java:76) at de.schlichtherle.truezip.fs.FsDecoratingController.getEntry(FsDecoratingController.java:76) at de.schlichtherle.truezip.fs.FsConcurrentController.getEntry(FsConcurrentController.java:164) at de.schlichtherle.truezip.fs.FsSyncController.getEntry(FsSyncController.java:108) at de.schlichtherle.truezip.fs.FsFederatingController.getEntry(FsFederatingController.java:156) at de.schlichtherle.truezip.nio.file.TFileSystem.newDirectoryStream(TFileSystem.java:348) at de.schlichtherle.truezip.nio.file.TPath.newDirectoryStream(TPath.java:963) at de.schlichtherle.truezip.nio.file.TFileSystemProvider.newDirectoryStream(TFileSystemProvider.java:344) at java.nio.file.Files.newDirectoryStream(Files.java:400) at com.googlecode.boostmavenproject.GetSourcesMojo.convertToJar(GetSourcesMojo.java:248) at com.googlecode.boostmavenproject.GetSourcesMojo.download(GetSources ``` You are a professional Java test case writer, please create a test case named `testCOMPRESS178` for the issue `Compress-COMPRESS-178`, utilizing the provided issue report information and the following function signature. ```java public void testCOMPRESS178() throws Exception { ```
303
[ "org.apache.commons.compress.archivers.tar.TarArchiveInputStream" ]
22152716d4c3b9e09249c67636c90d2e9f0ee3737e4396b93201a7d612082f89
public void testCOMPRESS178() throws Exception
// You are a professional Java test case writer, please create a test case named `testCOMPRESS178` for the issue `Compress-COMPRESS-178`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-178 // // ## Issue-Title: // TarArchiveInputStream throws IllegalArgumentException instead of IOException // // ## Issue-Description: // // TarArchiveInputStream is throwing IllegalArgumentException instead of IOException on corrupt files, in direct contradiction to the Javadoc. Here is a stack-trace: // // // // // ``` // java.lang.IllegalArgumentException: Invalid byte -1 at offset 7 in '<some bytes>' len=8 // at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:86) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:790) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:308) // at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:198) // at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextEntry(TarArchiveInputStream.java:380) // at de.schlichtherle.truezip.fs.archive.tar.TarInputShop.<init>(TarInputShop.java:91) // at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newTarInputShop(TarDriver.java:159) // at de.schlichtherle.truezip.fs.archive.tar.TarGZipDriver.newTarInputShop(TarGZipDriver.java:82) // at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newInputShop(TarDriver.java:151) // at de.schlichtherle.truezip.fs.archive.tar.TarDriver.newInputShop(TarDriver.java:47) // at de.schlichtherle.truezip.fs.archive.FsDefaultArchiveController.mount(FsDefaultArchiveController.java:170) // at de.schlichtherle.truezip.fs.archive.FsFileSystemArchiveController$ResetFileSystem.autoMount(FsFileSystemArchiveController.java:98) // at de.schlichtherle.truezip.fs.archive.FsFileSystemArchiveController.autoMount(FsFileSystemArchiveController.java:47) // at de.schlichtherle.truezip.fs.archive.FsArchiveController.autoMount(FsArchiveController.java:129) // at de.schlichtherle.truezip.fs.archive.FsArchiveController.getEntry(FsArchiveController.java:160) // at de.schlichtherle.truezip.fs.archive.FsContextController.getEntry(FsContextController.java:117) // at de.schlichtherle.truezip.fs.FsDecoratingController.getEntry(FsDecoratingController.java:76) // at de.schlichtherle.truezip.fs.FsDecoratingController.getEntry(FsDecoratingController.java:76) // at de.schlichtherle.truezip.fs.FsConcurrentController.getEntry(FsConcurrentController.java:164) // at de.schlichtherle.truezip.fs.FsSyncController.getEntry(FsSyncController.java:108) // at de.schlichtherle.truezip.fs.FsFederatingController.getEntry(FsFederatingController.java:156) // at de.schlichtherle.truezip.nio.file.TFileSystem.newDirectoryStream(TFileSystem.java:348) // at de.schlichtherle.truezip.nio.file.TPath.newDirectoryStream(TPath.java:963) // at de.schlichtherle.truezip.nio.file.TFileSystemProvider.newDirectoryStream(TFileSystemProvider.java:344) // at java.nio.file.Files.newDirectoryStream(Files.java:400) // at com.googlecode.boostmavenproject.GetSourcesMojo.convertToJar(GetSourcesMojo.java:248) // at com.googlecode.boostmavenproject.GetSourcesMojo.download(GetSources
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.compress.archivers; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.compress.AbstractTestCase; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.utils.IOUtils; public final class TarTestCase extends AbstractTestCase { public void testTarArchiveCreation() throws Exception { final File output = new File(dir, "bla.tar"); final File file1 = getFile("test1.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out); final TarArchiveEntry entry = new TarArchiveEntry("testdata/test1.xml"); entry.setModTime(0); entry.setSize(file1.length()); entry.setUserId(0); entry.setGroupId(0); entry.setUserName("avalon"); entry.setGroupName("excalibur"); entry.setMode(0100000); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.close(); } public void testTarArchiveLongNameCreation() throws Exception { String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml"; byte[] bytes = name.getBytes("UTF-8"); assertEquals(bytes.length, 99); final File output = new File(dir, "bla.tar"); final File file1 = getFile("test1.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out); final TarArchiveEntry entry = new TarArchiveEntry(name); entry.setModTime(0); entry.setSize(file1.length()); entry.setUserId(0); entry.setGroupId(0); entry.setUserName("avalon"); entry.setGroupName("excalibur"); entry.setMode(0100000); os.putArchiveEntry(entry); FileInputStream in = new FileInputStream(file1); IOUtils.copy(in, os); os.closeArchiveEntry(); os.close(); out.close(); in.close(); ArchiveOutputStream os2 = null; try { String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml"; final File output2 = new File(dir, "bla.tar"); final OutputStream out2 = new FileOutputStream(output2); os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2); final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName); entry2.setModTime(0); entry2.setSize(file1.length()); entry2.setUserId(0); entry2.setGroupId(0); entry2.setUserName("avalon"); entry2.setGroupName("excalibur"); entry2.setMode(0100000); os2.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file1), os2); os2.closeArchiveEntry(); } catch(IOException e) { assertTrue(true); } finally { if (os2 != null){ os2.close(); } } } public void testTarUnarchive() throws Exception { final File input = getFile("bla.tar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is); final TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry(); final OutputStream out = new FileOutputStream(new File(dir, entry.getName())); IOUtils.copy(in, out); in.close(); out.close(); } public void testCOMPRESS114() throws Exception { final File input = getFile("COMPRESS-114.tar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is); TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry(); assertEquals("3\u00b1\u00b1\u00b1F06\u00b1W2345\u00b1ZB\u00b1la\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1BLA", entry.getName()); entry = (TarArchiveEntry)in.getNextEntry(); assertEquals("0302-0601-3\u00b1\u00b1\u00b1F06\u00b1W2345\u00b1ZB\u00b1la\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1BLA",entry.getName()); in.close(); } public void testDirectoryEntryFromFile() throws Exception { File[] tmp = createTempDirAndFile(); File archive = null; TarArchiveOutputStream tos = null; TarArchiveInputStream tis = null; try { archive = File.createTempFile("test.", ".tar", tmp[0]); archive.deleteOnExit(); tos = new TarArchiveOutputStream(new FileOutputStream(archive)); long beforeArchiveWrite = tmp[0].lastModified(); TarArchiveEntry in = new TarArchiveEntry(tmp[0], "foo"); tos.putArchiveEntry(in); tos.closeArchiveEntry(); tos.close(); tos = null; tis = new TarArchiveInputStream(new FileInputStream(archive)); TarArchiveEntry out = tis.getNextTarEntry(); tis.close(); tis = null; assertNotNull(out); assertEquals("foo/", out.getName()); assertEquals(0, out.getSize()); // TAR stores time with a granularity of 1 second assertEquals(beforeArchiveWrite / 1000, out.getLastModifiedDate().getTime() / 1000); assertTrue(out.isDirectory()); } finally { if (tis != null) { tis.close(); } if (tos != null) { tos.close(); } tryHardToDelete(archive); tryHardToDelete(tmp[1]); rmdir(tmp[0]); } } public void testExplicitDirectoryEntry() throws Exception { File[] tmp = createTempDirAndFile(); File archive = null; TarArchiveOutputStream tos = null; TarArchiveInputStream tis = null; try { archive = File.createTempFile("test.", ".tar", tmp[0]); archive.deleteOnExit(); tos = new TarArchiveOutputStream(new FileOutputStream(archive)); long beforeArchiveWrite = tmp[0].lastModified(); TarArchiveEntry in = new TarArchiveEntry("foo/"); in.setModTime(beforeArchiveWrite); tos.putArchiveEntry(in); tos.closeArchiveEntry(); tos.close(); tos = null; tis = new TarArchiveInputStream(new FileInputStream(archive)); TarArchiveEntry out = tis.getNextTarEntry(); tis.close(); tis = null; assertNotNull(out); assertEquals("foo/", out.getName()); assertEquals(0, out.getSize()); assertEquals(beforeArchiveWrite / 1000, out.getLastModifiedDate().getTime() / 1000); assertTrue(out.isDirectory()); } finally { if (tis != null) { tis.close(); } if (tos != null) { tos.close(); } tryHardToDelete(archive); tryHardToDelete(tmp[1]); rmdir(tmp[0]); } } public void testFileEntryFromFile() throws Exception { File[] tmp = createTempDirAndFile(); File archive = null; TarArchiveOutputStream tos = null; TarArchiveInputStream tis = null; FileInputStream fis = null; try { archive = File.createTempFile("test.", ".tar", tmp[0]); archive.deleteOnExit(); tos = new TarArchiveOutputStream(new FileOutputStream(archive)); TarArchiveEntry in = new TarArchiveEntry(tmp[1], "foo"); tos.putArchiveEntry(in); byte[] b = new byte[(int) tmp[1].length()]; fis = new FileInputStream(tmp[1]); while (fis.read(b) > 0) { tos.write(b); } fis.close(); fis = null; tos.closeArchiveEntry(); tos.close(); tos = null; tis = new TarArchiveInputStream(new FileInputStream(archive)); TarArchiveEntry out = tis.getNextTarEntry(); tis.close(); tis = null; assertNotNull(out); assertEquals("foo", out.getName()); assertEquals(tmp[1].length(), out.getSize()); assertEquals(tmp[1].lastModified() / 1000, out.getLastModifiedDate().getTime() / 1000); assertFalse(out.isDirectory()); } finally { if (tis != null) { tis.close(); } if (tos != null) { tos.close(); } tryHardToDelete(archive); if (fis != null) { fis.close(); } tryHardToDelete(tmp[1]); rmdir(tmp[0]); } } public void testExplicitFileEntry() throws Exception { File[] tmp = createTempDirAndFile(); File archive = null; TarArchiveOutputStream tos = null; TarArchiveInputStream tis = null; FileInputStream fis = null; try { archive = File.createTempFile("test.", ".tar", tmp[0]); archive.deleteOnExit(); tos = new TarArchiveOutputStream(new FileOutputStream(archive)); TarArchiveEntry in = new TarArchiveEntry("foo"); in.setModTime(tmp[1].lastModified()); in.setSize(tmp[1].length()); tos.putArchiveEntry(in); byte[] b = new byte[(int) tmp[1].length()]; fis = new FileInputStream(tmp[1]); while (fis.read(b) > 0) { tos.write(b); } fis.close(); fis = null; tos.closeArchiveEntry(); tos.close(); tos = null; tis = new TarArchiveInputStream(new FileInputStream(archive)); TarArchiveEntry out = tis.getNextTarEntry(); tis.close(); tis = null; assertNotNull(out); assertEquals("foo", out.getName()); assertEquals(tmp[1].length(), out.getSize()); assertEquals(tmp[1].lastModified() / 1000, out.getLastModifiedDate().getTime() / 1000); assertFalse(out.isDirectory()); } finally { if (tis != null) { tis.close(); } if (tos != null) { tos.close(); } tryHardToDelete(archive); if (fis != null) { fis.close(); } tryHardToDelete(tmp[1]); rmdir(tmp[0]); } } public void testCOMPRESS178() throws Exception { final File input = getFile("COMPRESS-178.tar"); final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is); try { in.getNextEntry(); fail("Expected IOException"); } catch (IOException e) { Throwable t = e.getCause(); assertTrue("Expected cause = IllegalArgumentException", t instanceof IllegalArgumentException); } in.close(); } }
public void testWeirdStringHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdStringHandler(SingleValuedEnum.A)) ; SingleValuedEnum result = mapper.readValue("\"B\"", SingleValuedEnum.class); assertEquals(SingleValuedEnum.A, result); // also, write [databind#1629] try this mapper = new ObjectMapper() .addHandler(new WeirdStringHandler(null)); UUID result2 = mapper.readValue(quote("not a uuid!"), UUID.class); assertNull(result2); }
com.fasterxml.jackson.databind.filter.ProblemHandlerTest::testWeirdStringHandling
src/test/java/com/fasterxml/jackson/databind/filter/ProblemHandlerTest.java
248
src/test/java/com/fasterxml/jackson/databind/filter/ProblemHandlerTest.java
testWeirdStringHandling
package com.fasterxml.jackson.databind.filter; import java.io.IOException; import java.util.Map; import java.util.UUID; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.exc.InvalidTypeIdException; import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; /** * Tests to exercise handler methods of {@link DeserializationProblemHandler}. * * @since 2.8 */ public class ProblemHandlerTest extends BaseMapTest { /* /********************************************************** /* Test handler types /********************************************************** */ static class WeirdKeyHandler extends DeserializationProblemHandler { protected final Object key; public WeirdKeyHandler(Object key0) { key = key0; } @Override public Object handleWeirdKey(DeserializationContext ctxt, Class<?> rawKeyType, String keyValue, String failureMsg) throws IOException { return key; } } static class WeirdNumberHandler extends DeserializationProblemHandler { protected final Object value; public WeirdNumberHandler(Object v0) { value = v0; } @Override public Object handleWeirdNumberValue(DeserializationContext ctxt, Class<?> targetType, Number n, String failureMsg) throws IOException { return value; } } static class WeirdStringHandler extends DeserializationProblemHandler { protected final Object value; public WeirdStringHandler(Object v0) { value = v0; } @Override public Object handleWeirdStringValue(DeserializationContext ctxt, Class<?> targetType, String v, String failureMsg) throws IOException { return value; } } static class InstantiationProblemHandler extends DeserializationProblemHandler { protected final Object value; public InstantiationProblemHandler(Object v0) { value = v0; } @Override public Object handleInstantiationProblem(DeserializationContext ctxt, Class<?> instClass, Object argument, Throwable t) throws IOException { return value; } } static class MissingInstantiationHandler extends DeserializationProblemHandler { protected final Object value; public MissingInstantiationHandler(Object v0) { value = v0; } @Override public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, JsonParser p, String msg) throws IOException { p.skipChildren(); return value; } } static class WeirdTokenHandler extends DeserializationProblemHandler { protected final Object value; public WeirdTokenHandler(Object v) { value = v; } @Override public Object handleUnexpectedToken(DeserializationContext ctxt, Class<?> targetType, JsonToken t, JsonParser p, String failureMsg) throws IOException { return value; } } static class TypeIdHandler extends DeserializationProblemHandler { protected final Class<?> raw; public TypeIdHandler(Class<?> r) { raw = r; } @Override public JavaType handleUnknownTypeId(DeserializationContext ctxt, JavaType baseType, String subTypeId, TypeIdResolver idResolver, String failureMsg) throws IOException { return ctxt.constructType(raw); } } /* /********************************************************** /* Other helper types /********************************************************** */ static class IntKeyMapWrapper { public Map<Integer,String> stuff; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") static class Base { } static class BaseImpl extends Base { public int a; } static class BaseWrapper { public Base value; } @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "clazz") static class Base2 { } static class Base2Impl extends Base2 { public int a; } static class Base2Wrapper { public Base2 value; } enum SingleValuedEnum { A; } static class BustedCtor { public final static BustedCtor INST = new BustedCtor(true); public BustedCtor() { throw new RuntimeException("Fail!"); } private BustedCtor(boolean b) { } } static class NoDefaultCtor { public int value; public NoDefaultCtor(int v) { value = v; } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testWeirdKeyHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdKeyHandler(7)); IntKeyMapWrapper w = mapper.readValue("{\"stuff\":{\"foo\":\"abc\"}}", IntKeyMapWrapper.class); Map<Integer,String> map = w.stuff; assertEquals(1, map.size()); assertEquals("abc", map.values().iterator().next()); assertEquals(Integer.valueOf(7), map.keySet().iterator().next()); } public void testWeirdNumberHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdNumberHandler(SingleValuedEnum.A)) ; SingleValuedEnum result = mapper.readValue("3", SingleValuedEnum.class); assertEquals(SingleValuedEnum.A, result); } public void testWeirdStringHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdStringHandler(SingleValuedEnum.A)) ; SingleValuedEnum result = mapper.readValue("\"B\"", SingleValuedEnum.class); assertEquals(SingleValuedEnum.A, result); // also, write [databind#1629] try this mapper = new ObjectMapper() .addHandler(new WeirdStringHandler(null)); UUID result2 = mapper.readValue(quote("not a uuid!"), UUID.class); assertNull(result2); } public void testInvalidTypeId() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new TypeIdHandler(BaseImpl.class)); BaseWrapper w = mapper.readValue("{\"value\":{\"type\":\"foo\",\"a\":4}}", BaseWrapper.class); assertNotNull(w); assertEquals(BaseImpl.class, w.value.getClass()); } public void testInvalidClassAsId() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new TypeIdHandler(Base2Impl.class)); Base2Wrapper w = mapper.readValue("{\"value\":{\"clazz\":\"com.fizz\",\"a\":4}}", Base2Wrapper.class); assertNotNull(w); assertEquals(Base2Impl.class, w.value.getClass()); } // verify that by default we get special exception type public void testInvalidTypeIdFail() throws Exception { try { MAPPER.readValue("{\"value\":{\"type\":\"foo\",\"a\":4}}", BaseWrapper.class); fail("Should not pass"); } catch (InvalidTypeIdException e) { verifyException(e, "Could not resolve type id 'foo'"); assertEquals(Base.class, e.getBaseType().getRawClass()); assertEquals("foo", e.getTypeId()); } } public void testInstantiationExceptionHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new InstantiationProblemHandler(BustedCtor.INST)); BustedCtor w = mapper.readValue("{ }", BustedCtor.class); assertNotNull(w); } public void testMissingInstantiatorHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new MissingInstantiationHandler(new NoDefaultCtor(13))) ; NoDefaultCtor w = mapper.readValue("{ \"x\" : true }", NoDefaultCtor.class); assertNotNull(w); assertEquals(13, w.value); } public void testUnexpectedTokenHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdTokenHandler(Integer.valueOf(13))) ; Integer v = mapper.readValue("true", Integer.class); assertEquals(Integer.valueOf(13), v); } }
// You are a professional Java test case writer, please create a test case named `testWeirdStringHandling` for the issue `JacksonDatabind-1629`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1629 // // ## Issue-Title: // FromStringDeserializer ignores registered DeserializationProblemHandler for java.util.UUID // // ## Issue-Description: // Culprit appears to be [lines 155-161 of FromStringDeserializer](https://github.com/FasterXML/jackson-databind/blob/60ae6000d361f910ab0d7d269a5bac1fc66f4cd9/src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java#L155-L161): // // // // ``` // // 05-May-2016, tatu: Unlike most usage, this seems legit, so... // JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg); // if (cause != null) { // e.initCause(cause); // } // throw e; // // nothing to do here, yet? We'll fail anyway // // ``` // // The above lines appear to show that the exception will be thrown regardless of any problem handling logic. // // // Test Case: // // // // ``` // import com.fasterxml.jackson.databind.DeserializationContext; // import com.fasterxml.jackson.databind.ObjectMapper; // import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; // import org.junit.Test; // // import java.io.IOException; // import java.util.UUID; // // public class UUIDDeserializerTest { // // // @Test // public void itUsesDeserializationProblemHandlerProperly() throws IOException { // ObjectMapper mapper = new ObjectMapper().addHandler(new DeserializationProblemHandler() { // @Override // public Object handleWeirdStringValue(final DeserializationContext ctxt, final Class<?> targetType, final String valueToConvert, final String failureMsg) throws IOException { // return null; // } // }); // // mapper.readValue("{\"id\" : \"I am not a UUID\"}", IdBean.class); // // // // } // // public static class IdBean { // private UUID id; // // public UUID getId() { // return id; // } // // public void setId(final UUID id) { // this.id = id; // } // } // } // // ``` // // The handler handles the issue properly; but an exception is thrown anyway: // // // // ``` // an not deserialize value of type java.util.UUID from String "I am not a UUID": not a valid textual representation // at [Source: (String)"{"id" : "I am not a UUID"}"; line: 1, column: 9] (through reference chain: com.company.test.UUIDDeserializerTest$IdBean["id"]) // com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.UUID from String "I am not a UUID": not a valid textual representation // at [Source: (String)"{"id" : "I am not a UUID"}"; line: 1, column: 9] (through reference chain: com.company.test.UUIDDeserializerTest$IdBean["id"]) // at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67) // at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1504) // at com.fasterxml.jackson.databind.deser.std.FromStringDeserializer.deserialize(FromStringDeserializer.java:156) // at com.faster public void testWeirdStringHandling() throws Exception {
248
83
235
src/test/java/com/fasterxml/jackson/databind/filter/ProblemHandlerTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1629 ## Issue-Title: FromStringDeserializer ignores registered DeserializationProblemHandler for java.util.UUID ## Issue-Description: Culprit appears to be [lines 155-161 of FromStringDeserializer](https://github.com/FasterXML/jackson-databind/blob/60ae6000d361f910ab0d7d269a5bac1fc66f4cd9/src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java#L155-L161): ``` // 05-May-2016, tatu: Unlike most usage, this seems legit, so... JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg); if (cause != null) { e.initCause(cause); } throw e; // nothing to do here, yet? We'll fail anyway ``` The above lines appear to show that the exception will be thrown regardless of any problem handling logic. Test Case: ``` import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import org.junit.Test; import java.io.IOException; import java.util.UUID; public class UUIDDeserializerTest { @Test public void itUsesDeserializationProblemHandlerProperly() throws IOException { ObjectMapper mapper = new ObjectMapper().addHandler(new DeserializationProblemHandler() { @Override public Object handleWeirdStringValue(final DeserializationContext ctxt, final Class<?> targetType, final String valueToConvert, final String failureMsg) throws IOException { return null; } }); mapper.readValue("{\"id\" : \"I am not a UUID\"}", IdBean.class); } public static class IdBean { private UUID id; public UUID getId() { return id; } public void setId(final UUID id) { this.id = id; } } } ``` The handler handles the issue properly; but an exception is thrown anyway: ``` an not deserialize value of type java.util.UUID from String "I am not a UUID": not a valid textual representation at [Source: (String)"{"id" : "I am not a UUID"}"; line: 1, column: 9] (through reference chain: com.company.test.UUIDDeserializerTest$IdBean["id"]) com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.UUID from String "I am not a UUID": not a valid textual representation at [Source: (String)"{"id" : "I am not a UUID"}"; line: 1, column: 9] (through reference chain: com.company.test.UUIDDeserializerTest$IdBean["id"]) at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67) at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1504) at com.fasterxml.jackson.databind.deser.std.FromStringDeserializer.deserialize(FromStringDeserializer.java:156) at com.faster ``` You are a professional Java test case writer, please create a test case named `testWeirdStringHandling` for the issue `JacksonDatabind-1629`, utilizing the provided issue report information and the following function signature. ```java public void testWeirdStringHandling() throws Exception { ```
235
[ "com.fasterxml.jackson.databind.deser.std.FromStringDeserializer" ]
221c9eecaee2abdb3eb96414023a3a01fb0613d1636b8adb62e4ac2cd1e9056f
public void testWeirdStringHandling() throws Exception
// You are a professional Java test case writer, please create a test case named `testWeirdStringHandling` for the issue `JacksonDatabind-1629`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1629 // // ## Issue-Title: // FromStringDeserializer ignores registered DeserializationProblemHandler for java.util.UUID // // ## Issue-Description: // Culprit appears to be [lines 155-161 of FromStringDeserializer](https://github.com/FasterXML/jackson-databind/blob/60ae6000d361f910ab0d7d269a5bac1fc66f4cd9/src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java#L155-L161): // // // // ``` // // 05-May-2016, tatu: Unlike most usage, this seems legit, so... // JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg); // if (cause != null) { // e.initCause(cause); // } // throw e; // // nothing to do here, yet? We'll fail anyway // // ``` // // The above lines appear to show that the exception will be thrown regardless of any problem handling logic. // // // Test Case: // // // // ``` // import com.fasterxml.jackson.databind.DeserializationContext; // import com.fasterxml.jackson.databind.ObjectMapper; // import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; // import org.junit.Test; // // import java.io.IOException; // import java.util.UUID; // // public class UUIDDeserializerTest { // // // @Test // public void itUsesDeserializationProblemHandlerProperly() throws IOException { // ObjectMapper mapper = new ObjectMapper().addHandler(new DeserializationProblemHandler() { // @Override // public Object handleWeirdStringValue(final DeserializationContext ctxt, final Class<?> targetType, final String valueToConvert, final String failureMsg) throws IOException { // return null; // } // }); // // mapper.readValue("{\"id\" : \"I am not a UUID\"}", IdBean.class); // // // // } // // public static class IdBean { // private UUID id; // // public UUID getId() { // return id; // } // // public void setId(final UUID id) { // this.id = id; // } // } // } // // ``` // // The handler handles the issue properly; but an exception is thrown anyway: // // // // ``` // an not deserialize value of type java.util.UUID from String "I am not a UUID": not a valid textual representation // at [Source: (String)"{"id" : "I am not a UUID"}"; line: 1, column: 9] (through reference chain: com.company.test.UUIDDeserializerTest$IdBean["id"]) // com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.UUID from String "I am not a UUID": not a valid textual representation // at [Source: (String)"{"id" : "I am not a UUID"}"; line: 1, column: 9] (through reference chain: com.company.test.UUIDDeserializerTest$IdBean["id"]) // at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67) // at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1504) // at com.fasterxml.jackson.databind.deser.std.FromStringDeserializer.deserialize(FromStringDeserializer.java:156) // at com.faster
JacksonDatabind
package com.fasterxml.jackson.databind.filter; import java.io.IOException; import java.util.Map; import java.util.UUID; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.exc.InvalidTypeIdException; import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; /** * Tests to exercise handler methods of {@link DeserializationProblemHandler}. * * @since 2.8 */ public class ProblemHandlerTest extends BaseMapTest { /* /********************************************************** /* Test handler types /********************************************************** */ static class WeirdKeyHandler extends DeserializationProblemHandler { protected final Object key; public WeirdKeyHandler(Object key0) { key = key0; } @Override public Object handleWeirdKey(DeserializationContext ctxt, Class<?> rawKeyType, String keyValue, String failureMsg) throws IOException { return key; } } static class WeirdNumberHandler extends DeserializationProblemHandler { protected final Object value; public WeirdNumberHandler(Object v0) { value = v0; } @Override public Object handleWeirdNumberValue(DeserializationContext ctxt, Class<?> targetType, Number n, String failureMsg) throws IOException { return value; } } static class WeirdStringHandler extends DeserializationProblemHandler { protected final Object value; public WeirdStringHandler(Object v0) { value = v0; } @Override public Object handleWeirdStringValue(DeserializationContext ctxt, Class<?> targetType, String v, String failureMsg) throws IOException { return value; } } static class InstantiationProblemHandler extends DeserializationProblemHandler { protected final Object value; public InstantiationProblemHandler(Object v0) { value = v0; } @Override public Object handleInstantiationProblem(DeserializationContext ctxt, Class<?> instClass, Object argument, Throwable t) throws IOException { return value; } } static class MissingInstantiationHandler extends DeserializationProblemHandler { protected final Object value; public MissingInstantiationHandler(Object v0) { value = v0; } @Override public Object handleMissingInstantiator(DeserializationContext ctxt, Class<?> instClass, JsonParser p, String msg) throws IOException { p.skipChildren(); return value; } } static class WeirdTokenHandler extends DeserializationProblemHandler { protected final Object value; public WeirdTokenHandler(Object v) { value = v; } @Override public Object handleUnexpectedToken(DeserializationContext ctxt, Class<?> targetType, JsonToken t, JsonParser p, String failureMsg) throws IOException { return value; } } static class TypeIdHandler extends DeserializationProblemHandler { protected final Class<?> raw; public TypeIdHandler(Class<?> r) { raw = r; } @Override public JavaType handleUnknownTypeId(DeserializationContext ctxt, JavaType baseType, String subTypeId, TypeIdResolver idResolver, String failureMsg) throws IOException { return ctxt.constructType(raw); } } /* /********************************************************** /* Other helper types /********************************************************** */ static class IntKeyMapWrapper { public Map<Integer,String> stuff; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") static class Base { } static class BaseImpl extends Base { public int a; } static class BaseWrapper { public Base value; } @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "clazz") static class Base2 { } static class Base2Impl extends Base2 { public int a; } static class Base2Wrapper { public Base2 value; } enum SingleValuedEnum { A; } static class BustedCtor { public final static BustedCtor INST = new BustedCtor(true); public BustedCtor() { throw new RuntimeException("Fail!"); } private BustedCtor(boolean b) { } } static class NoDefaultCtor { public int value; public NoDefaultCtor(int v) { value = v; } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testWeirdKeyHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdKeyHandler(7)); IntKeyMapWrapper w = mapper.readValue("{\"stuff\":{\"foo\":\"abc\"}}", IntKeyMapWrapper.class); Map<Integer,String> map = w.stuff; assertEquals(1, map.size()); assertEquals("abc", map.values().iterator().next()); assertEquals(Integer.valueOf(7), map.keySet().iterator().next()); } public void testWeirdNumberHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdNumberHandler(SingleValuedEnum.A)) ; SingleValuedEnum result = mapper.readValue("3", SingleValuedEnum.class); assertEquals(SingleValuedEnum.A, result); } public void testWeirdStringHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdStringHandler(SingleValuedEnum.A)) ; SingleValuedEnum result = mapper.readValue("\"B\"", SingleValuedEnum.class); assertEquals(SingleValuedEnum.A, result); // also, write [databind#1629] try this mapper = new ObjectMapper() .addHandler(new WeirdStringHandler(null)); UUID result2 = mapper.readValue(quote("not a uuid!"), UUID.class); assertNull(result2); } public void testInvalidTypeId() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new TypeIdHandler(BaseImpl.class)); BaseWrapper w = mapper.readValue("{\"value\":{\"type\":\"foo\",\"a\":4}}", BaseWrapper.class); assertNotNull(w); assertEquals(BaseImpl.class, w.value.getClass()); } public void testInvalidClassAsId() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new TypeIdHandler(Base2Impl.class)); Base2Wrapper w = mapper.readValue("{\"value\":{\"clazz\":\"com.fizz\",\"a\":4}}", Base2Wrapper.class); assertNotNull(w); assertEquals(Base2Impl.class, w.value.getClass()); } // verify that by default we get special exception type public void testInvalidTypeIdFail() throws Exception { try { MAPPER.readValue("{\"value\":{\"type\":\"foo\",\"a\":4}}", BaseWrapper.class); fail("Should not pass"); } catch (InvalidTypeIdException e) { verifyException(e, "Could not resolve type id 'foo'"); assertEquals(Base.class, e.getBaseType().getRawClass()); assertEquals("foo", e.getTypeId()); } } public void testInstantiationExceptionHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new InstantiationProblemHandler(BustedCtor.INST)); BustedCtor w = mapper.readValue("{ }", BustedCtor.class); assertNotNull(w); } public void testMissingInstantiatorHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new MissingInstantiationHandler(new NoDefaultCtor(13))) ; NoDefaultCtor w = mapper.readValue("{ \"x\" : true }", NoDefaultCtor.class); assertNotNull(w); assertEquals(13, w.value); } public void testUnexpectedTokenHandling() throws Exception { ObjectMapper mapper = new ObjectMapper() .addHandler(new WeirdTokenHandler(Integer.valueOf(13))) ; Integer v = mapper.readValue("true", Integer.class); assertEquals(Integer.valueOf(13), v); } }
@Test public void testSingleVariableAndConstraint() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(10.0, solution.getPoint()[0], 0.0); assertEquals(30.0, solution.getValue(), 0.0); }
org.apache.commons.math.optimization.linear.SimplexSolverTest::testSingleVariableAndConstraint
src/test/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
76
src/test/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
testSingleVariableAndConstraint
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.optimization.linear; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.linear.RealVectorImpl; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.OptimizationException; import org.apache.commons.math.optimization.RealPointValuePair; import org.junit.Test; public class SimplexSolverTest { @Test public void testMath272() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(0.0, solution.getPoint()[0], .0000001); assertEquals(1.0, solution.getPoint()[1], .0000001); assertEquals(1.0, solution.getPoint()[2], .0000001); assertEquals(3.0, solution.getValue(), .0000001); } @Test public void testSimplexSolver() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 7); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(57.0, solution.getValue(), 0.0); } @Test public void testSingleVariableAndConstraint() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(10.0, solution.getPoint()[0], 0.0); assertEquals(30.0, solution.getValue(), 0.0); } /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(50.0, solution.getValue(), 0.0); } @Test public void testMinimization() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false); assertEquals(4.0, solution.getPoint()[0], 0.0); assertEquals(0.0, solution.getPoint()[1], 0.0); assertEquals(-13.0, solution.getValue(), 0.0); } @Test public void testSolutionWithNegativeDecisionVariable() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(-2.0, solution.getPoint()[0], 0.0); assertEquals(8.0, solution.getPoint()[1], 0.0); assertEquals(12.0, solution.getValue(), 0.0); } @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test public void testRestrictVariablesToNonNegative() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); assertEquals(480.419243986254, solution.getPoint()[1], .0000001); assertEquals(0.0, solution.getPoint()[2], .0000001); assertEquals(0.0, solution.getPoint()[3], .0000001); assertEquals(0.0, solution.getPoint()[4], .0000001); assertEquals(1438556.7491409, solution.getValue(), .0000001); } @Test public void testEpsilon() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(1.0, solution.getPoint()[0], 0.0); assertEquals(1.0, solution.getPoint()[1], 0.0); assertEquals(0.0, solution.getPoint()[2], 0.0); assertEquals(15.0, solution.getValue(), 0.0); } @Test public void testTrivialModel() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(0, solution.getValue(), .0000001); } @Test public void testLargeModel() throws OptimizationException { double[] objective = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(7518.0, solution.getValue(), .0000001); } /** * Converts a test string to a {@link LinearConstraint}. * Ex: x0 + x1 + x2 + x3 - x12 = 0 */ private LinearConstraint equationFromString(int numCoefficients, String s) { Relationship relationship; if (s.contains(">=")) { relationship = Relationship.GEQ; } else if (s.contains("<=")) { relationship = Relationship.LEQ; } else if (s.contains("=")) { relationship = Relationship.EQ; } else { throw new IllegalArgumentException(); } String[] equationParts = s.split("[>|<]?="); double rhs = Double.parseDouble(equationParts[1].trim()); RealVector lhs = new RealVectorImpl(numCoefficients); String left = equationParts[0].replaceAll(" ?x", ""); String[] coefficients = left.split(" "); for (String coefficient : coefficients) { double value = coefficient.charAt(0) == '-' ? -1 : 1; int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim()); lhs.setEntry(index, value); } return new LinearConstraint(lhs, relationship, rhs); } }
// You are a professional Java test case writer, please create a test case named `testSingleVariableAndConstraint` for the issue `Math-MATH-273`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-273 // // ## Issue-Title: // Basic variable is not found correctly in simplex tableau // // ## Issue-Description: // // The last patch to SimplexTableau caused an automated test suite I'm running at work to go down a new code path and uncover what is hopefully the last bug remaining in the Simplex code. // // SimplexTableau was assuming an entry in the tableau had to be nonzero to indicate a basic variable, which is incorrect - the entry should have a value equal to 1. // // // // // @Test public void testSingleVariableAndConstraint() throws OptimizationException {
76
87
66
src/test/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
src/test
```markdown ## Issue-ID: Math-MATH-273 ## Issue-Title: Basic variable is not found correctly in simplex tableau ## Issue-Description: The last patch to SimplexTableau caused an automated test suite I'm running at work to go down a new code path and uncover what is hopefully the last bug remaining in the Simplex code. SimplexTableau was assuming an entry in the tableau had to be nonzero to indicate a basic variable, which is incorrect - the entry should have a value equal to 1. ``` You are a professional Java test case writer, please create a test case named `testSingleVariableAndConstraint` for the issue `Math-MATH-273`, utilizing the provided issue report information and the following function signature. ```java @Test public void testSingleVariableAndConstraint() throws OptimizationException { ```
66
[ "org.apache.commons.math.optimization.linear.SimplexTableau" ]
22840ec9ef83e966f8ce23e2f25780c5d9ea97f55ed3ae99f9eaaa99645effb8
@Test public void testSingleVariableAndConstraint() throws OptimizationException
// You are a professional Java test case writer, please create a test case named `testSingleVariableAndConstraint` for the issue `Math-MATH-273`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-273 // // ## Issue-Title: // Basic variable is not found correctly in simplex tableau // // ## Issue-Description: // // The last patch to SimplexTableau caused an automated test suite I'm running at work to go down a new code path and uncover what is hopefully the last bug remaining in the Simplex code. // // SimplexTableau was assuming an entry in the tableau had to be nonzero to indicate a basic variable, which is incorrect - the entry should have a value equal to 1. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.optimization.linear; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.linear.RealVectorImpl; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.OptimizationException; import org.apache.commons.math.optimization.RealPointValuePair; import org.junit.Test; public class SimplexSolverTest { @Test public void testMath272() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(0.0, solution.getPoint()[0], .0000001); assertEquals(1.0, solution.getPoint()[1], .0000001); assertEquals(1.0, solution.getPoint()[2], .0000001); assertEquals(3.0, solution.getValue(), .0000001); } @Test public void testSimplexSolver() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 7); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(57.0, solution.getValue(), 0.0); } @Test public void testSingleVariableAndConstraint() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(10.0, solution.getPoint()[0], 0.0); assertEquals(30.0, solution.getValue(), 0.0); } /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(50.0, solution.getValue(), 0.0); } @Test public void testMinimization() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false); assertEquals(4.0, solution.getPoint()[0], 0.0); assertEquals(0.0, solution.getPoint()[1], 0.0); assertEquals(-13.0, solution.getValue(), 0.0); } @Test public void testSolutionWithNegativeDecisionVariable() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(-2.0, solution.getPoint()[0], 0.0); assertEquals(8.0, solution.getPoint()[1], 0.0); assertEquals(12.0, solution.getValue(), 0.0); } @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test public void testRestrictVariablesToNonNegative() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); assertEquals(480.419243986254, solution.getPoint()[1], .0000001); assertEquals(0.0, solution.getPoint()[2], .0000001); assertEquals(0.0, solution.getPoint()[3], .0000001); assertEquals(0.0, solution.getPoint()[4], .0000001); assertEquals(1438556.7491409, solution.getValue(), .0000001); } @Test public void testEpsilon() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(1.0, solution.getPoint()[0], 0.0); assertEquals(1.0, solution.getPoint()[1], 0.0); assertEquals(0.0, solution.getPoint()[2], 0.0); assertEquals(15.0, solution.getValue(), 0.0); } @Test public void testTrivialModel() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(0, solution.getValue(), .0000001); } @Test public void testLargeModel() throws OptimizationException { double[] objective = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(7518.0, solution.getValue(), .0000001); } /** * Converts a test string to a {@link LinearConstraint}. * Ex: x0 + x1 + x2 + x3 - x12 = 0 */ private LinearConstraint equationFromString(int numCoefficients, String s) { Relationship relationship; if (s.contains(">=")) { relationship = Relationship.GEQ; } else if (s.contains("<=")) { relationship = Relationship.LEQ; } else if (s.contains("=")) { relationship = Relationship.EQ; } else { throw new IllegalArgumentException(); } String[] equationParts = s.split("[>|<]?="); double rhs = Double.parseDouble(equationParts[1].trim()); RealVector lhs = new RealVectorImpl(numCoefficients); String left = equationParts[0].replaceAll(" ?x", ""); String[] coefficients = left.split(" "); for (String coefficient : coefficients) { double value = coefficient.charAt(0) == '-' ? -1 : 1; int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim()); lhs.setEntry(index, value); } return new LinearConstraint(lhs, relationship, rhs); } }
public void testIssue2088UnwrappedFieldsAfterLastCreatorProp() throws Exception { Issue2088Bean bean = MAPPER.readValue("{\"x\":1,\"a\":2,\"y\":3,\"b\":4}", Issue2088Bean.class); assertEquals(1, bean.x); assertEquals(2, bean.w.a); assertEquals(3, bean.y); assertEquals(4, bean.w.b); }
com.fasterxml.jackson.databind.struct.TestUnwrapped::testIssue2088UnwrappedFieldsAfterLastCreatorProp
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
254
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
testIssue2088UnwrappedFieldsAfterLastCreatorProp
package com.fasterxml.jackson.databind.struct; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; /** * Unit tests for verifying that basic {@link JsonUnwrapped} annotation * handling works as expected; some more advanced tests are separated out * to more specific test classes (like prefix/suffix handling). */ public class TestUnwrapped extends BaseMapTest { static class Unwrapping { public String name; @JsonUnwrapped public Location location; public Unwrapping() { } public Unwrapping(String str, int x, int y) { name = str; location = new Location(x, y); } } final static class Location { public int x; public int y; public Location() { } public Location(int x, int y) { this.x = x; this.y = y; } } static class DeepUnwrapping { @JsonUnwrapped public Unwrapping unwrapped; public DeepUnwrapping() { } public DeepUnwrapping(String str, int x, int y) { unwrapped = new Unwrapping(str, x, y); } } static class UnwrappingWithCreator { public String name; @JsonUnwrapped public Location location; @JsonCreator public UnwrappingWithCreator(@JsonProperty("name") String n) { name = n; } } // Class with two unwrapped properties static class TwoUnwrappedProperties { @JsonUnwrapped public Location location; @JsonUnwrapped public Name name; public TwoUnwrappedProperties() { } } static class Name { public String first, last; } // [databind#615] static class Parent { @JsonUnwrapped public Child c1; public Parent() { } public Parent(String str) { c1 = new Child(str); } } static class Child { public String field; public Child() { } public Child(String f) { field = f; } } static class Inner { public String animal; } static class Outer { // @JsonProperty @JsonUnwrapped private Inner inner; } // [databind#1493]: case-insensitive handling static class Person { @JsonUnwrapped(prefix = "businessAddress.") public Address businessAddress; } static class Address { public String street; public String addon; public String zip; public String town; public String country; } // [databind#2088] static class Issue2088Bean { int x; int y; @JsonUnwrapped Issue2088UnwrappedBean w; public Issue2088Bean(@JsonProperty("x") int x, @JsonProperty("y") int y) { this.x = x; this.y = y; } public void setW(Issue2088UnwrappedBean w) { this.w = w; } } static class Issue2088UnwrappedBean { int a; int b; public Issue2088UnwrappedBean(@JsonProperty("a") int a, @JsonProperty("b") int b) { this.a = a; this.b = b; } } /* /********************************************************** /* Tests, serialization /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new Unwrapping("Tatu", 1, 2))); } public void testDeepUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new DeepUnwrapping("Tatu", 1, 2))); } /* /********************************************************** /* Tests, deserialization /********************************************************** */ public void testSimpleUnwrappedDeserialize() throws Exception { Unwrapping bean = MAPPER.readValue("{\"name\":\"Tatu\",\"y\":7,\"x\":-13}", Unwrapping.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); } public void testDoubleUnwrapping() throws Exception { TwoUnwrappedProperties bean = MAPPER.readValue("{\"first\":\"Joe\",\"y\":7,\"last\":\"Smith\",\"x\":-13}", TwoUnwrappedProperties.class); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); Name name = bean.name; assertNotNull(name); assertEquals("Joe", name.first); assertEquals("Smith", name.last); } public void testDeepUnwrapping() throws Exception { DeepUnwrapping bean = MAPPER.readValue("{\"x\":3,\"name\":\"Bob\",\"y\":27}", DeepUnwrapping.class); Unwrapping uw = bean.unwrapped; assertNotNull(uw); assertEquals("Bob", uw.name); Location loc = uw.location; assertNotNull(loc); assertEquals(3, loc.x); assertEquals(27, loc.y); } public void testUnwrappedDeserializeWithCreator() throws Exception { UnwrappingWithCreator bean = MAPPER.readValue("{\"x\":1,\"y\":2,\"name\":\"Tatu\"}", UnwrappingWithCreator.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(1, loc.x); assertEquals(2, loc.y); } public void testIssue615() throws Exception { Parent input = new Parent("name"); String json = MAPPER.writeValueAsString(input); Parent output = MAPPER.readValue(json, Parent.class); assertEquals("name", output.c1.field); } public void testUnwrappedAsPropertyIndicator() throws Exception { Inner inner = new Inner(); inner.animal = "Zebra"; Outer outer = new Outer(); outer.inner = inner; String actual = MAPPER.writeValueAsString(outer); assertTrue(actual.contains("animal")); assertTrue(actual.contains("Zebra")); assertFalse(actual.contains("inner")); } // [databind#1493]: case-insensitive handling public void testCaseInsensitiveUnwrap() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); Person p = mapper.readValue("{ }", Person.class); assertNotNull(p); } // [databind#2088]: accidental skipping of values public void testIssue2088UnwrappedFieldsAfterLastCreatorProp() throws Exception { Issue2088Bean bean = MAPPER.readValue("{\"x\":1,\"a\":2,\"y\":3,\"b\":4}", Issue2088Bean.class); assertEquals(1, bean.x); assertEquals(2, bean.w.a); assertEquals(3, bean.y); assertEquals(4, bean.w.b); } }
// You are a professional Java test case writer, please create a test case named `testIssue2088UnwrappedFieldsAfterLastCreatorProp` for the issue `JacksonDatabind-2088`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2088 // // ## Issue-Title: // @JsonUnwrapped fields are skipped when using PropertyBasedCreator if they appear after the last creator property // // ## Issue-Description: // Example: // // // // ``` // static class Bean { // int x; // int y; // // @JsonUnwrapped // UnwrappedBean w; // // public Bean(@JsonProperty("x") int x, @JsonProperty("y") int y) { // this.x = x; // this.y = y; // } // // public void setW(UnwrappedBean w) { // this.w = w; // } // } // // static class UnwrappedBean { // int a; // int b; // // public UnwrappedBean(@JsonProperty("a") int a, @JsonProperty("b") int b) { // this.a = a; // this.b = b; // } // } // ``` // // // ``` // {"x": 1, "a": 2, "y": 3, "b": 4} // ``` // // `x`, `y`, and `a` are deserialized as expected. `b` is skipped entirely. I think I've found the root cause and the fix doesn't appear to break any tests; opening a PR for further review. // // // // public void testIssue2088UnwrappedFieldsAfterLastCreatorProp() throws Exception {
254
// [databind#2088]: accidental skipping of values
101
247
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-2088 ## Issue-Title: @JsonUnwrapped fields are skipped when using PropertyBasedCreator if they appear after the last creator property ## Issue-Description: Example: ``` static class Bean { int x; int y; @JsonUnwrapped UnwrappedBean w; public Bean(@JsonProperty("x") int x, @JsonProperty("y") int y) { this.x = x; this.y = y; } public void setW(UnwrappedBean w) { this.w = w; } } static class UnwrappedBean { int a; int b; public UnwrappedBean(@JsonProperty("a") int a, @JsonProperty("b") int b) { this.a = a; this.b = b; } } ``` ``` {"x": 1, "a": 2, "y": 3, "b": 4} ``` `x`, `y`, and `a` are deserialized as expected. `b` is skipped entirely. I think I've found the root cause and the fix doesn't appear to break any tests; opening a PR for further review. ``` You are a professional Java test case writer, please create a test case named `testIssue2088UnwrappedFieldsAfterLastCreatorProp` for the issue `JacksonDatabind-2088`, utilizing the provided issue report information and the following function signature. ```java public void testIssue2088UnwrappedFieldsAfterLastCreatorProp() throws Exception { ```
247
[ "com.fasterxml.jackson.databind.deser.BeanDeserializer" ]
23c3231a04637e1b0e3a229640e3dbc37194d70a7c5ab7e4665ddbdbdaba7500
public void testIssue2088UnwrappedFieldsAfterLastCreatorProp() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue2088UnwrappedFieldsAfterLastCreatorProp` for the issue `JacksonDatabind-2088`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2088 // // ## Issue-Title: // @JsonUnwrapped fields are skipped when using PropertyBasedCreator if they appear after the last creator property // // ## Issue-Description: // Example: // // // // ``` // static class Bean { // int x; // int y; // // @JsonUnwrapped // UnwrappedBean w; // // public Bean(@JsonProperty("x") int x, @JsonProperty("y") int y) { // this.x = x; // this.y = y; // } // // public void setW(UnwrappedBean w) { // this.w = w; // } // } // // static class UnwrappedBean { // int a; // int b; // // public UnwrappedBean(@JsonProperty("a") int a, @JsonProperty("b") int b) { // this.a = a; // this.b = b; // } // } // ``` // // // ``` // {"x": 1, "a": 2, "y": 3, "b": 4} // ``` // // `x`, `y`, and `a` are deserialized as expected. `b` is skipped entirely. I think I've found the root cause and the fix doesn't appear to break any tests; opening a PR for further review. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.struct; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; /** * Unit tests for verifying that basic {@link JsonUnwrapped} annotation * handling works as expected; some more advanced tests are separated out * to more specific test classes (like prefix/suffix handling). */ public class TestUnwrapped extends BaseMapTest { static class Unwrapping { public String name; @JsonUnwrapped public Location location; public Unwrapping() { } public Unwrapping(String str, int x, int y) { name = str; location = new Location(x, y); } } final static class Location { public int x; public int y; public Location() { } public Location(int x, int y) { this.x = x; this.y = y; } } static class DeepUnwrapping { @JsonUnwrapped public Unwrapping unwrapped; public DeepUnwrapping() { } public DeepUnwrapping(String str, int x, int y) { unwrapped = new Unwrapping(str, x, y); } } static class UnwrappingWithCreator { public String name; @JsonUnwrapped public Location location; @JsonCreator public UnwrappingWithCreator(@JsonProperty("name") String n) { name = n; } } // Class with two unwrapped properties static class TwoUnwrappedProperties { @JsonUnwrapped public Location location; @JsonUnwrapped public Name name; public TwoUnwrappedProperties() { } } static class Name { public String first, last; } // [databind#615] static class Parent { @JsonUnwrapped public Child c1; public Parent() { } public Parent(String str) { c1 = new Child(str); } } static class Child { public String field; public Child() { } public Child(String f) { field = f; } } static class Inner { public String animal; } static class Outer { // @JsonProperty @JsonUnwrapped private Inner inner; } // [databind#1493]: case-insensitive handling static class Person { @JsonUnwrapped(prefix = "businessAddress.") public Address businessAddress; } static class Address { public String street; public String addon; public String zip; public String town; public String country; } // [databind#2088] static class Issue2088Bean { int x; int y; @JsonUnwrapped Issue2088UnwrappedBean w; public Issue2088Bean(@JsonProperty("x") int x, @JsonProperty("y") int y) { this.x = x; this.y = y; } public void setW(Issue2088UnwrappedBean w) { this.w = w; } } static class Issue2088UnwrappedBean { int a; int b; public Issue2088UnwrappedBean(@JsonProperty("a") int a, @JsonProperty("b") int b) { this.a = a; this.b = b; } } /* /********************************************************** /* Tests, serialization /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new Unwrapping("Tatu", 1, 2))); } public void testDeepUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new DeepUnwrapping("Tatu", 1, 2))); } /* /********************************************************** /* Tests, deserialization /********************************************************** */ public void testSimpleUnwrappedDeserialize() throws Exception { Unwrapping bean = MAPPER.readValue("{\"name\":\"Tatu\",\"y\":7,\"x\":-13}", Unwrapping.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); } public void testDoubleUnwrapping() throws Exception { TwoUnwrappedProperties bean = MAPPER.readValue("{\"first\":\"Joe\",\"y\":7,\"last\":\"Smith\",\"x\":-13}", TwoUnwrappedProperties.class); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); Name name = bean.name; assertNotNull(name); assertEquals("Joe", name.first); assertEquals("Smith", name.last); } public void testDeepUnwrapping() throws Exception { DeepUnwrapping bean = MAPPER.readValue("{\"x\":3,\"name\":\"Bob\",\"y\":27}", DeepUnwrapping.class); Unwrapping uw = bean.unwrapped; assertNotNull(uw); assertEquals("Bob", uw.name); Location loc = uw.location; assertNotNull(loc); assertEquals(3, loc.x); assertEquals(27, loc.y); } public void testUnwrappedDeserializeWithCreator() throws Exception { UnwrappingWithCreator bean = MAPPER.readValue("{\"x\":1,\"y\":2,\"name\":\"Tatu\"}", UnwrappingWithCreator.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(1, loc.x); assertEquals(2, loc.y); } public void testIssue615() throws Exception { Parent input = new Parent("name"); String json = MAPPER.writeValueAsString(input); Parent output = MAPPER.readValue(json, Parent.class); assertEquals("name", output.c1.field); } public void testUnwrappedAsPropertyIndicator() throws Exception { Inner inner = new Inner(); inner.animal = "Zebra"; Outer outer = new Outer(); outer.inner = inner; String actual = MAPPER.writeValueAsString(outer); assertTrue(actual.contains("animal")); assertTrue(actual.contains("Zebra")); assertFalse(actual.contains("inner")); } // [databind#1493]: case-insensitive handling public void testCaseInsensitiveUnwrap() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); Person p = mapper.readValue("{ }", Person.class); assertNotNull(p); } // [databind#2088]: accidental skipping of values public void testIssue2088UnwrappedFieldsAfterLastCreatorProp() throws Exception { Issue2088Bean bean = MAPPER.readValue("{\"x\":1,\"a\":2,\"y\":3,\"b\":4}", Issue2088Bean.class); assertEquals(1, bean.x); assertEquals(2, bean.w.a); assertEquals(3, bean.y); assertEquals(4, bean.w.b); } }
@Test public void testExactOptionNameMatch() throws ParseException { new DefaultParser().parse(getOptions(), new String[]{"--prefix"}); }
org.apache.commons.cli.bug.BugCLI252Test::testExactOptionNameMatch
src/test/java/org/apache/commons/cli/bug/BugCLI252Test.java
10
src/test/java/org/apache/commons/cli/bug/BugCLI252Test.java
testExactOptionNameMatch
package org.apache.commons.cli.bug; import org.apache.commons.cli.*; import org.junit.Test; public class BugCLI252Test extends DefaultParserTest { @Test public void testExactOptionNameMatch() throws ParseException { new DefaultParser().parse(getOptions(), new String[]{"--prefix"}); } @Test(expected = AmbiguousOptionException.class) public void testAmbiquousOptionName() throws ParseException { new DefaultParser().parse(getOptions(), new String[]{"--pref"}); } private Options getOptions() { Options options = new Options(); options.addOption(Option.builder().longOpt("prefix").build()); options.addOption(Option.builder().longOpt("prefixplusplus").build()); return options; } }
// You are a professional Java test case writer, please create a test case named `testExactOptionNameMatch` for the issue `Cli-CLI-252`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-252 // // ## Issue-Title: // LongOpt falsely detected as ambiguous // // ## Issue-Description: // // Options options = new Options(); // // options.addOption(Option.builder().longOpt("importToOpen").hasArg().argName("FILE").build()); // // options.addOption(Option.builder("i").longOpt("import").hasArg().argName("FILE").build()); // // // Parsing "--import=FILE" is not possible since 1.3 as it throws a AmbiguousOptionException stating that it cannot decide whether import is import or importToOpen. In 1.2 this is not an issue. // // // The root lies in the new DefaultParser which does a startsWith check internally. // // // // // @Test public void testExactOptionNameMatch() throws ParseException {
10
35
7
src/test/java/org/apache/commons/cli/bug/BugCLI252Test.java
src/test/java
```markdown ## Issue-ID: Cli-CLI-252 ## Issue-Title: LongOpt falsely detected as ambiguous ## Issue-Description: Options options = new Options(); options.addOption(Option.builder().longOpt("importToOpen").hasArg().argName("FILE").build()); options.addOption(Option.builder("i").longOpt("import").hasArg().argName("FILE").build()); Parsing "--import=FILE" is not possible since 1.3 as it throws a AmbiguousOptionException stating that it cannot decide whether import is import or importToOpen. In 1.2 this is not an issue. The root lies in the new DefaultParser which does a startsWith check internally. ``` You are a professional Java test case writer, please create a test case named `testExactOptionNameMatch` for the issue `Cli-CLI-252`, utilizing the provided issue report information and the following function signature. ```java @Test public void testExactOptionNameMatch() throws ParseException { ```
7
[ "org.apache.commons.cli.Options" ]
2404c7d8c81bde7f47d1fa98525ecc6f3ac02a0aa03e9e5161d40458c7e0980b
@Test public void testExactOptionNameMatch() throws ParseException
// You are a professional Java test case writer, please create a test case named `testExactOptionNameMatch` for the issue `Cli-CLI-252`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-252 // // ## Issue-Title: // LongOpt falsely detected as ambiguous // // ## Issue-Description: // // Options options = new Options(); // // options.addOption(Option.builder().longOpt("importToOpen").hasArg().argName("FILE").build()); // // options.addOption(Option.builder("i").longOpt("import").hasArg().argName("FILE").build()); // // // Parsing "--import=FILE" is not possible since 1.3 as it throws a AmbiguousOptionException stating that it cannot decide whether import is import or importToOpen. In 1.2 this is not an issue. // // // The root lies in the new DefaultParser which does a startsWith check internally. // // // // //
Cli
package org.apache.commons.cli.bug; import org.apache.commons.cli.*; import org.junit.Test; public class BugCLI252Test extends DefaultParserTest { @Test public void testExactOptionNameMatch() throws ParseException { new DefaultParser().parse(getOptions(), new String[]{"--prefix"}); } @Test(expected = AmbiguousOptionException.class) public void testAmbiquousOptionName() throws ParseException { new DefaultParser().parse(getOptions(), new String[]{"--pref"}); } private Options getOptions() { Options options = new Options(); options.addOption(Option.builder().longOpt("prefix").build()); options.addOption(Option.builder().longOpt("prefixplusplus").build()); return options; } }
public void testStringBuilder() throws Exception { StringBuilder sb = MAPPER.readValue(quote("abc"), StringBuilder.class); assertEquals("abc", sb.toString()); }
com.fasterxml.jackson.databind.deser.TestJdkTypes::testStringBuilder
src/test/java/com/fasterxml/jackson/databind/deser/TestJdkTypes.java
426
src/test/java/com/fasterxml/jackson/databind/deser/TestJdkTypes.java
testStringBuilder
package com.fasterxml.jackson.databind.deser; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Currency; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.module.SimpleModule; public class TestJdkTypes extends BaseMapTest { static class PrimitivesBean { public boolean booleanValue = true; public byte byteValue = 3; public char charValue = 'a'; public short shortValue = 37; public int intValue = 1; public long longValue = 100L; public float floatValue = 0.25f; public double doubleValue = -1.0; } // for [JACKSON-616] static class WrappersBean { public Boolean booleanValue; public Byte byteValue; public Character charValue; public Short shortValue; public Integer intValue; public Long longValue; public Float floatValue; public Double doubleValue; } static class ParamClassBean { public String name = "bar"; public Class<String> clazz ; public ParamClassBean() { } public ParamClassBean(String name) { this.name = name; clazz = String.class; } } static class BooleanBean { public Boolean wrapper; public boolean primitive; protected Boolean ctor; @JsonCreator public BooleanBean(@JsonProperty("ctor") Boolean foo) { ctor = foo; } } // [Issue#429] static class StackTraceBean { public final static int NUM = 13; @JsonProperty("Location") @JsonDeserialize(using=MyStackTraceElementDeserializer.class) protected StackTraceElement location; } @SuppressWarnings("serial") static class MyStackTraceElementDeserializer extends StdDeserializer<StackTraceElement> { public MyStackTraceElementDeserializer() { super(StackTraceElement.class); } @Override public StackTraceElement deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { jp.skipChildren(); return new StackTraceElement("a", "b", "b", StackTraceBean.NUM); } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); /** * Related to issues [JACKSON-155], [#170]. */ public void testFile() throws Exception { // Not portable etc... has to do: File src = new File("/test").getAbsoluteFile(); String abs = src.getAbsolutePath(); // escape backslashes (for portability with windows) String json = MAPPER.writeValueAsString(abs); File result = MAPPER.readValue(json, File.class); assertEquals(abs, result.getAbsolutePath()); // Then #170 final ObjectMapper mapper2 = new ObjectMapper(); mapper2.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE); result = mapper2.readValue(json, File.class); assertEquals(abs, result.getAbsolutePath()); } public void testRegexps() throws IOException { final String PATTERN_STR = "abc:\\s?(\\d+)"; Pattern exp = Pattern.compile(PATTERN_STR); /* Ok: easiest way is to just serialize first; problem * is the backslash */ String json = MAPPER.writeValueAsString(exp); Pattern result = MAPPER.readValue(json, Pattern.class); assertEquals(exp.pattern(), result.pattern()); } public void testCurrency() throws IOException { Currency usd = Currency.getInstance("USD"); assertEquals(usd, new ObjectMapper().readValue(quote("USD"), Currency.class)); } /** * Test for [JACKSON-419] */ public void testLocale() throws IOException { assertEquals(new Locale("en"), MAPPER.readValue(quote("en"), Locale.class)); assertEquals(new Locale("es", "ES"), MAPPER.readValue(quote("es_ES"), Locale.class)); assertEquals(new Locale("FI", "fi", "savo"), MAPPER.readValue(quote("fi_FI_savo"), Locale.class)); } /** * Test for [JACKSON-420] (add DeserializationConfig.FAIL_ON_NULL_FOR_PRIMITIVES) */ public void testNullForPrimitives() throws IOException { // by default, ok to rely on defaults PrimitivesBean bean = MAPPER.readValue("{\"intValue\":null, \"booleanValue\":null, \"doubleValue\":null}", PrimitivesBean.class); assertNotNull(bean); assertEquals(0, bean.intValue); assertEquals(false, bean.booleanValue); assertEquals(0.0, bean.doubleValue); bean = MAPPER.readValue("{\"byteValue\":null, \"longValue\":null, \"floatValue\":null}", PrimitivesBean.class); assertNotNull(bean); assertEquals((byte) 0, bean.byteValue); assertEquals(0L, bean.longValue); assertEquals(0.0f, bean.floatValue); // but not when enabled final ObjectMapper mapper2 = new ObjectMapper(); mapper2.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true); // boolean try { mapper2.readValue("{\"booleanValue\":null}", PrimitivesBean.class); fail("Expected failure for boolean + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type boolean"); } // byte/char/short/int/long try { mapper2.readValue("{\"byteValue\":null}", PrimitivesBean.class); fail("Expected failure for byte + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type byte"); } try { mapper2.readValue("{\"charValue\":null}", PrimitivesBean.class); fail("Expected failure for char + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type char"); } try { mapper2.readValue("{\"shortValue\":null}", PrimitivesBean.class); fail("Expected failure for short + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type short"); } try { mapper2.readValue("{\"intValue\":null}", PrimitivesBean.class); fail("Expected failure for int + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type int"); } try { mapper2.readValue("{\"longValue\":null}", PrimitivesBean.class); fail("Expected failure for long + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type long"); } // float/double try { mapper2.readValue("{\"floatValue\":null}", PrimitivesBean.class); fail("Expected failure for float + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type float"); } try { mapper2.readValue("{\"doubleValue\":null}", PrimitivesBean.class); fail("Expected failure for double + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type double"); } } /** * Test for [JACKSON-483], allow handling of CharSequence */ public void testCharSequence() throws IOException { CharSequence cs = MAPPER.readValue("\"abc\"", CharSequence.class); assertEquals(String.class, cs.getClass()); assertEquals("abc", cs.toString()); } // [JACKSON-484] public void testInetAddress() throws IOException { InetAddress address = MAPPER.readValue(quote("127.0.0.1"), InetAddress.class); assertEquals("127.0.0.1", address.getHostAddress()); // should we try resolving host names? That requires connectivity... final String HOST = "google.com"; address = MAPPER.readValue(quote(HOST), InetAddress.class); assertEquals(HOST, address.getHostName()); } public void testInetSocketAddress() throws IOException { InetSocketAddress address = MAPPER.readValue(quote("127.0.0.1"), InetSocketAddress.class); assertEquals("127.0.0.1", address.getAddress().getHostAddress()); InetSocketAddress ip6 = MAPPER.readValue( quote("2001:db8:85a3:8d3:1319:8a2e:370:7348"), InetSocketAddress.class); assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6.getAddress().getHostAddress()); InetSocketAddress ip6port = MAPPER.readValue( quote("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443"), InetSocketAddress.class); assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6port.getAddress().getHostAddress()); assertEquals(443, ip6port.getPort()); // should we try resolving host names? That requires connectivity... final String HOST = "www.google.com"; address = MAPPER.readValue(quote(HOST), InetSocketAddress.class); assertEquals(HOST, address.getHostName()); final String HOST_AND_PORT = HOST+":80"; address = MAPPER.readValue(quote(HOST_AND_PORT), InetSocketAddress.class); assertEquals(HOST, address.getHostName()); assertEquals(80, address.getPort()); } // [JACKSON-597] public void testClass() throws IOException { ObjectMapper mapper = new ObjectMapper(); assertSame(String.class, mapper.readValue(quote("java.lang.String"), Class.class)); // then primitive types assertSame(Boolean.TYPE, mapper.readValue(quote("boolean"), Class.class)); assertSame(Byte.TYPE, mapper.readValue(quote("byte"), Class.class)); assertSame(Short.TYPE, mapper.readValue(quote("short"), Class.class)); assertSame(Character.TYPE, mapper.readValue(quote("char"), Class.class)); assertSame(Integer.TYPE, mapper.readValue(quote("int"), Class.class)); assertSame(Long.TYPE, mapper.readValue(quote("long"), Class.class)); assertSame(Float.TYPE, mapper.readValue(quote("float"), Class.class)); assertSame(Double.TYPE, mapper.readValue(quote("double"), Class.class)); assertSame(Void.TYPE, mapper.readValue(quote("void"), Class.class)); } // [JACKSON-605] public void testClassWithParams() throws IOException { String json = MAPPER.writeValueAsString(new ParamClassBean("Foobar")); ParamClassBean result = MAPPER.readValue(json, ParamClassBean.class); assertEquals("Foobar", result.name); assertSame(String.class, result.clazz); } // by default, should return nulls, n'est pas? public void testEmptyStringForWrappers() throws IOException { WrappersBean bean; // by default, ok to rely on defaults bean = MAPPER.readValue("{\"booleanValue\":\"\"}", WrappersBean.class); assertNull(bean.booleanValue); bean = MAPPER.readValue("{\"byteValue\":\"\"}", WrappersBean.class); assertNull(bean.byteValue); // char/Character is different... not sure if this should work or not: bean = MAPPER.readValue("{\"charValue\":\"\"}", WrappersBean.class); assertNull(bean.charValue); bean = MAPPER.readValue("{\"shortValue\":\"\"}", WrappersBean.class); assertNull(bean.shortValue); bean = MAPPER.readValue("{\"intValue\":\"\"}", WrappersBean.class); assertNull(bean.intValue); bean = MAPPER.readValue("{\"longValue\":\"\"}", WrappersBean.class); assertNull(bean.longValue); bean = MAPPER.readValue("{\"floatValue\":\"\"}", WrappersBean.class); assertNull(bean.floatValue); bean = MAPPER.readValue("{\"doubleValue\":\"\"}", WrappersBean.class); assertNull(bean.doubleValue); } // for [JACKSON-616] // @since 1.9 public void testEmptyStringForPrimitives() throws IOException { PrimitivesBean bean; bean = MAPPER.readValue("{\"booleanValue\":\"\"}", PrimitivesBean.class); assertFalse(bean.booleanValue); bean = MAPPER.readValue("{\"byteValue\":\"\"}", PrimitivesBean.class); assertEquals((byte) 0, bean.byteValue); bean = MAPPER.readValue("{\"charValue\":\"\"}", PrimitivesBean.class); assertEquals((char) 0, bean.charValue); bean = MAPPER.readValue("{\"shortValue\":\"\"}", PrimitivesBean.class); assertEquals((short) 0, bean.shortValue); bean = MAPPER.readValue("{\"intValue\":\"\"}", PrimitivesBean.class); assertEquals(0, bean.intValue); bean = MAPPER.readValue("{\"longValue\":\"\"}", PrimitivesBean.class); assertEquals(0L, bean.longValue); bean = MAPPER.readValue("{\"floatValue\":\"\"}", PrimitivesBean.class); assertEquals(0.0f, bean.floatValue); bean = MAPPER.readValue("{\"doubleValue\":\"\"}", PrimitivesBean.class); assertEquals(0.0, bean.doubleValue); } // for [JACKSON-652] // @since 1.9 public void testUntypedWithJsonArrays() throws Exception { // by default we get: Object ob = MAPPER.readValue("[1]", Object.class); assertTrue(ob instanceof List<?>); // but can change to produce Object[]: MAPPER.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); ob = MAPPER.readValue("[1]", Object.class); assertEquals(Object[].class, ob.getClass()); } // Test for verifying that Long values are coerced to boolean correctly as well public void testLongToBoolean() throws Exception { long value = 1L + Integer.MAX_VALUE; BooleanBean b = MAPPER.readValue("{\"primitive\" : "+value+", \"wrapper\":"+value+", \"ctor\":"+value+"}", BooleanBean.class); assertEquals(Boolean.TRUE, b.wrapper); assertTrue(b.primitive); assertEquals(Boolean.TRUE, b.ctor); } // [JACKSON-789] public void testCharset() throws Exception { Charset UTF8 = Charset.forName("UTF-8"); assertSame(UTF8, MAPPER.readValue(quote("UTF-8"), Charset.class)); } // [JACKSON-888] public void testStackTraceElement() throws Exception { StackTraceElement elem = null; try { throw new IllegalStateException(); } catch (Exception e) { elem = e.getStackTrace()[0]; } String json = MAPPER.writeValueAsString(elem); StackTraceElement back = MAPPER.readValue(json, StackTraceElement.class); assertEquals("testStackTraceElement", back.getMethodName()); assertEquals(elem.getLineNumber(), back.getLineNumber()); assertEquals(elem.getClassName(), back.getClassName()); assertEquals(elem.isNativeMethod(), back.isNativeMethod()); assertTrue(back.getClassName().endsWith("TestJdkTypes")); assertFalse(back.isNativeMethod()); } // [Issue#239] public void testByteBuffer() throws Exception { byte[] INPUT = new byte[] { 1, 3, 9, -1, 6 }; String exp = MAPPER.writeValueAsString(INPUT); ByteBuffer result = MAPPER.readValue(exp, ByteBuffer.class); assertNotNull(result); assertEquals(INPUT.length, result.remaining()); for (int i = 0; i < INPUT.length; ++i) { assertEquals(INPUT[i], result.get()); } assertEquals(0, result.remaining()); } public void testStringBuilder() throws Exception { StringBuilder sb = MAPPER.readValue(quote("abc"), StringBuilder.class); assertEquals("abc", sb.toString()); } // [Issue#429] public void testStackTraceElementWithCustom() throws Exception { // first, via bean that contains StackTraceElement StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"), StackTraceBean.class); assertNotNull(bean); assertNotNull(bean.location); assertEquals(StackTraceBean.NUM, bean.location.getLineNumber()); // and then directly, iff registered ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addDeserializer(StackTraceElement.class, new MyStackTraceElementDeserializer()); mapper.registerModule(module); StackTraceElement elem = mapper.readValue("123", StackTraceElement.class); assertNotNull(elem); assertEquals(StackTraceBean.NUM, elem.getLineNumber()); // and finally, even as part of real exception IOException ioe = mapper.readValue(aposToQuotes("{'stackTrace':[ 123, 456 ]}"), IOException.class); assertNotNull(ioe); StackTraceElement[] traces = ioe.getStackTrace(); assertNotNull(traces); assertEquals(2, traces.length); assertEquals(StackTraceBean.NUM, traces[0].getLineNumber()); assertEquals(StackTraceBean.NUM, traces[1].getLineNumber()); } /* /********************************************************** /* Single-array handling tests /********************************************************** */ // [Issue#381] public void testSingleElementArray() throws Exception { final int intTest = 932832; final double doubleTest = 32.3234; final long longTest = 2374237428374293423L; final short shortTest = (short) intTest; final float floatTest = 84.3743f; final byte byteTest = (byte) 43; final char charTest = 'c'; final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); final int intValue = mapper.readValue(asArray(intTest), Integer.TYPE); assertEquals(intTest, intValue); final Integer integerWrapperValue = mapper.readValue(asArray(Integer.valueOf(intTest)), Integer.class); assertEquals(Integer.valueOf(intTest), integerWrapperValue); final double doubleValue = mapper.readValue(asArray(doubleTest), Double.class); assertEquals(doubleTest, doubleValue); final Double doubleWrapperValue = mapper.readValue(asArray(Double.valueOf(doubleTest)), Double.class); assertEquals(Double.valueOf(doubleTest), doubleWrapperValue); final long longValue = mapper.readValue(asArray(longTest), Long.TYPE); assertEquals(longTest, longValue); final Long longWrapperValue = mapper.readValue(asArray(Long.valueOf(longTest)), Long.class); assertEquals(Long.valueOf(longTest), longWrapperValue); final short shortValue = mapper.readValue(asArray(shortTest), Short.TYPE); assertEquals(shortTest, shortValue); final Short shortWrapperValue = mapper.readValue(asArray(Short.valueOf(shortTest)), Short.class); assertEquals(Short.valueOf(shortTest), shortWrapperValue); final float floatValue = mapper.readValue(asArray(floatTest), Float.TYPE); assertEquals(floatTest, floatValue); final Float floatWrapperValue = mapper.readValue(asArray(Float.valueOf(floatTest)), Float.class); assertEquals(Float.valueOf(floatTest), floatWrapperValue); final byte byteValue = mapper.readValue(asArray(byteTest), Byte.TYPE); assertEquals(byteTest, byteValue); final Byte byteWrapperValue = mapper.readValue(asArray(Byte.valueOf(byteTest)), Byte.class); assertEquals(Byte.valueOf(byteTest), byteWrapperValue); final char charValue = mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.TYPE); assertEquals(charTest, charValue); final Character charWrapperValue = mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.class); assertEquals(Character.valueOf(charTest), charWrapperValue); final boolean booleanTrueValue = mapper.readValue(asArray(true), Boolean.TYPE); assertTrue(booleanTrueValue); final boolean booleanFalseValue = mapper.readValue(asArray(false), Boolean.TYPE); assertFalse(booleanFalseValue); final Boolean booleanWrapperTrueValue = mapper.readValue(asArray(Boolean.valueOf(true)), Boolean.class); assertEquals(Boolean.TRUE, booleanWrapperTrueValue); } private static String asArray(Object value) { final String stringVal = value.toString(); return new StringBuilder(stringVal.length() + 2).append("[").append(stringVal).append("]").toString(); } public void testSingleElementArrayException() throws Exception { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); try { mapper.readValue("[42]", Integer.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Integer.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42.273]", Double.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42.2723]", Double.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342]", Long.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342342]", Long.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Short.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Short.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[327.2323]", Float.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[82.81902]", Float.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[22]", Byte.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[22]", Byte.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("['d']", Character.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("['d']", Character.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[true]", Boolean.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[true]", Boolean.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } } public void testMultiValueArrayException() throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); try { mapper.readValue("[42,42]", Integer.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42,42]", Integer.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42.273,42.273]", Double.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42.2723,42.273]", Double.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342,42342342342342]", Long.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342342,42342342342342]", Long.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42,42]", Short.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42,42]", Short.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[327.2323,327.2323]", Float.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[82.81902,327.2323]", Float.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[22,23]", Byte.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[22,23]", Byte.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue(asArray(quote("c") + "," + quote("d")), Character.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue(asArray(quote("c") + "," + quote("d")), Character.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[true,false]", Boolean.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[true,false]", Boolean.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } } }
// You are a professional Java test case writer, please create a test case named `testStringBuilder` for the issue `JacksonDatabind-667`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-667 // // ## Issue-Title: // Problem with bogus conflict between single-arg-String vs CharSequence constructor // // ## Issue-Description: // Although it is good idea to allow recognizing `CharSequence` as almost like an alias for `String`, this can cause problems for classes like `StringBuilder` that have separate constructors for both. // // This actually throws a bogus exception for 2.5.0, due to introduction of ability to recognize `CharSequence`. // // // // public void testStringBuilder() throws Exception {
426
8
422
src/test/java/com/fasterxml/jackson/databind/deser/TestJdkTypes.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-667 ## Issue-Title: Problem with bogus conflict between single-arg-String vs CharSequence constructor ## Issue-Description: Although it is good idea to allow recognizing `CharSequence` as almost like an alias for `String`, this can cause problems for classes like `StringBuilder` that have separate constructors for both. This actually throws a bogus exception for 2.5.0, due to introduction of ability to recognize `CharSequence`. ``` You are a professional Java test case writer, please create a test case named `testStringBuilder` for the issue `JacksonDatabind-667`, utilizing the provided issue report information and the following function signature. ```java public void testStringBuilder() throws Exception { ```
422
[ "com.fasterxml.jackson.databind.deser.impl.CreatorCollector" ]
240718e3a471571164791f059150dda9b5e88d4fc6cf4ca7e81ef1f433252762
public void testStringBuilder() throws Exception
// You are a professional Java test case writer, please create a test case named `testStringBuilder` for the issue `JacksonDatabind-667`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-667 // // ## Issue-Title: // Problem with bogus conflict between single-arg-String vs CharSequence constructor // // ## Issue-Description: // Although it is good idea to allow recognizing `CharSequence` as almost like an alias for `String`, this can cause problems for classes like `StringBuilder` that have separate constructors for both. // // This actually throws a bogus exception for 2.5.0, due to introduction of ability to recognize `CharSequence`. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.deser; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Currency; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.module.SimpleModule; public class TestJdkTypes extends BaseMapTest { static class PrimitivesBean { public boolean booleanValue = true; public byte byteValue = 3; public char charValue = 'a'; public short shortValue = 37; public int intValue = 1; public long longValue = 100L; public float floatValue = 0.25f; public double doubleValue = -1.0; } // for [JACKSON-616] static class WrappersBean { public Boolean booleanValue; public Byte byteValue; public Character charValue; public Short shortValue; public Integer intValue; public Long longValue; public Float floatValue; public Double doubleValue; } static class ParamClassBean { public String name = "bar"; public Class<String> clazz ; public ParamClassBean() { } public ParamClassBean(String name) { this.name = name; clazz = String.class; } } static class BooleanBean { public Boolean wrapper; public boolean primitive; protected Boolean ctor; @JsonCreator public BooleanBean(@JsonProperty("ctor") Boolean foo) { ctor = foo; } } // [Issue#429] static class StackTraceBean { public final static int NUM = 13; @JsonProperty("Location") @JsonDeserialize(using=MyStackTraceElementDeserializer.class) protected StackTraceElement location; } @SuppressWarnings("serial") static class MyStackTraceElementDeserializer extends StdDeserializer<StackTraceElement> { public MyStackTraceElementDeserializer() { super(StackTraceElement.class); } @Override public StackTraceElement deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { jp.skipChildren(); return new StackTraceElement("a", "b", "b", StackTraceBean.NUM); } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); /** * Related to issues [JACKSON-155], [#170]. */ public void testFile() throws Exception { // Not portable etc... has to do: File src = new File("/test").getAbsoluteFile(); String abs = src.getAbsolutePath(); // escape backslashes (for portability with windows) String json = MAPPER.writeValueAsString(abs); File result = MAPPER.readValue(json, File.class); assertEquals(abs, result.getAbsolutePath()); // Then #170 final ObjectMapper mapper2 = new ObjectMapper(); mapper2.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE); result = mapper2.readValue(json, File.class); assertEquals(abs, result.getAbsolutePath()); } public void testRegexps() throws IOException { final String PATTERN_STR = "abc:\\s?(\\d+)"; Pattern exp = Pattern.compile(PATTERN_STR); /* Ok: easiest way is to just serialize first; problem * is the backslash */ String json = MAPPER.writeValueAsString(exp); Pattern result = MAPPER.readValue(json, Pattern.class); assertEquals(exp.pattern(), result.pattern()); } public void testCurrency() throws IOException { Currency usd = Currency.getInstance("USD"); assertEquals(usd, new ObjectMapper().readValue(quote("USD"), Currency.class)); } /** * Test for [JACKSON-419] */ public void testLocale() throws IOException { assertEquals(new Locale("en"), MAPPER.readValue(quote("en"), Locale.class)); assertEquals(new Locale("es", "ES"), MAPPER.readValue(quote("es_ES"), Locale.class)); assertEquals(new Locale("FI", "fi", "savo"), MAPPER.readValue(quote("fi_FI_savo"), Locale.class)); } /** * Test for [JACKSON-420] (add DeserializationConfig.FAIL_ON_NULL_FOR_PRIMITIVES) */ public void testNullForPrimitives() throws IOException { // by default, ok to rely on defaults PrimitivesBean bean = MAPPER.readValue("{\"intValue\":null, \"booleanValue\":null, \"doubleValue\":null}", PrimitivesBean.class); assertNotNull(bean); assertEquals(0, bean.intValue); assertEquals(false, bean.booleanValue); assertEquals(0.0, bean.doubleValue); bean = MAPPER.readValue("{\"byteValue\":null, \"longValue\":null, \"floatValue\":null}", PrimitivesBean.class); assertNotNull(bean); assertEquals((byte) 0, bean.byteValue); assertEquals(0L, bean.longValue); assertEquals(0.0f, bean.floatValue); // but not when enabled final ObjectMapper mapper2 = new ObjectMapper(); mapper2.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true); // boolean try { mapper2.readValue("{\"booleanValue\":null}", PrimitivesBean.class); fail("Expected failure for boolean + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type boolean"); } // byte/char/short/int/long try { mapper2.readValue("{\"byteValue\":null}", PrimitivesBean.class); fail("Expected failure for byte + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type byte"); } try { mapper2.readValue("{\"charValue\":null}", PrimitivesBean.class); fail("Expected failure for char + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type char"); } try { mapper2.readValue("{\"shortValue\":null}", PrimitivesBean.class); fail("Expected failure for short + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type short"); } try { mapper2.readValue("{\"intValue\":null}", PrimitivesBean.class); fail("Expected failure for int + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type int"); } try { mapper2.readValue("{\"longValue\":null}", PrimitivesBean.class); fail("Expected failure for long + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type long"); } // float/double try { mapper2.readValue("{\"floatValue\":null}", PrimitivesBean.class); fail("Expected failure for float + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type float"); } try { mapper2.readValue("{\"doubleValue\":null}", PrimitivesBean.class); fail("Expected failure for double + null"); } catch (JsonMappingException e) { verifyException(e, "Can not map JSON null into type double"); } } /** * Test for [JACKSON-483], allow handling of CharSequence */ public void testCharSequence() throws IOException { CharSequence cs = MAPPER.readValue("\"abc\"", CharSequence.class); assertEquals(String.class, cs.getClass()); assertEquals("abc", cs.toString()); } // [JACKSON-484] public void testInetAddress() throws IOException { InetAddress address = MAPPER.readValue(quote("127.0.0.1"), InetAddress.class); assertEquals("127.0.0.1", address.getHostAddress()); // should we try resolving host names? That requires connectivity... final String HOST = "google.com"; address = MAPPER.readValue(quote(HOST), InetAddress.class); assertEquals(HOST, address.getHostName()); } public void testInetSocketAddress() throws IOException { InetSocketAddress address = MAPPER.readValue(quote("127.0.0.1"), InetSocketAddress.class); assertEquals("127.0.0.1", address.getAddress().getHostAddress()); InetSocketAddress ip6 = MAPPER.readValue( quote("2001:db8:85a3:8d3:1319:8a2e:370:7348"), InetSocketAddress.class); assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6.getAddress().getHostAddress()); InetSocketAddress ip6port = MAPPER.readValue( quote("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443"), InetSocketAddress.class); assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6port.getAddress().getHostAddress()); assertEquals(443, ip6port.getPort()); // should we try resolving host names? That requires connectivity... final String HOST = "www.google.com"; address = MAPPER.readValue(quote(HOST), InetSocketAddress.class); assertEquals(HOST, address.getHostName()); final String HOST_AND_PORT = HOST+":80"; address = MAPPER.readValue(quote(HOST_AND_PORT), InetSocketAddress.class); assertEquals(HOST, address.getHostName()); assertEquals(80, address.getPort()); } // [JACKSON-597] public void testClass() throws IOException { ObjectMapper mapper = new ObjectMapper(); assertSame(String.class, mapper.readValue(quote("java.lang.String"), Class.class)); // then primitive types assertSame(Boolean.TYPE, mapper.readValue(quote("boolean"), Class.class)); assertSame(Byte.TYPE, mapper.readValue(quote("byte"), Class.class)); assertSame(Short.TYPE, mapper.readValue(quote("short"), Class.class)); assertSame(Character.TYPE, mapper.readValue(quote("char"), Class.class)); assertSame(Integer.TYPE, mapper.readValue(quote("int"), Class.class)); assertSame(Long.TYPE, mapper.readValue(quote("long"), Class.class)); assertSame(Float.TYPE, mapper.readValue(quote("float"), Class.class)); assertSame(Double.TYPE, mapper.readValue(quote("double"), Class.class)); assertSame(Void.TYPE, mapper.readValue(quote("void"), Class.class)); } // [JACKSON-605] public void testClassWithParams() throws IOException { String json = MAPPER.writeValueAsString(new ParamClassBean("Foobar")); ParamClassBean result = MAPPER.readValue(json, ParamClassBean.class); assertEquals("Foobar", result.name); assertSame(String.class, result.clazz); } // by default, should return nulls, n'est pas? public void testEmptyStringForWrappers() throws IOException { WrappersBean bean; // by default, ok to rely on defaults bean = MAPPER.readValue("{\"booleanValue\":\"\"}", WrappersBean.class); assertNull(bean.booleanValue); bean = MAPPER.readValue("{\"byteValue\":\"\"}", WrappersBean.class); assertNull(bean.byteValue); // char/Character is different... not sure if this should work or not: bean = MAPPER.readValue("{\"charValue\":\"\"}", WrappersBean.class); assertNull(bean.charValue); bean = MAPPER.readValue("{\"shortValue\":\"\"}", WrappersBean.class); assertNull(bean.shortValue); bean = MAPPER.readValue("{\"intValue\":\"\"}", WrappersBean.class); assertNull(bean.intValue); bean = MAPPER.readValue("{\"longValue\":\"\"}", WrappersBean.class); assertNull(bean.longValue); bean = MAPPER.readValue("{\"floatValue\":\"\"}", WrappersBean.class); assertNull(bean.floatValue); bean = MAPPER.readValue("{\"doubleValue\":\"\"}", WrappersBean.class); assertNull(bean.doubleValue); } // for [JACKSON-616] // @since 1.9 public void testEmptyStringForPrimitives() throws IOException { PrimitivesBean bean; bean = MAPPER.readValue("{\"booleanValue\":\"\"}", PrimitivesBean.class); assertFalse(bean.booleanValue); bean = MAPPER.readValue("{\"byteValue\":\"\"}", PrimitivesBean.class); assertEquals((byte) 0, bean.byteValue); bean = MAPPER.readValue("{\"charValue\":\"\"}", PrimitivesBean.class); assertEquals((char) 0, bean.charValue); bean = MAPPER.readValue("{\"shortValue\":\"\"}", PrimitivesBean.class); assertEquals((short) 0, bean.shortValue); bean = MAPPER.readValue("{\"intValue\":\"\"}", PrimitivesBean.class); assertEquals(0, bean.intValue); bean = MAPPER.readValue("{\"longValue\":\"\"}", PrimitivesBean.class); assertEquals(0L, bean.longValue); bean = MAPPER.readValue("{\"floatValue\":\"\"}", PrimitivesBean.class); assertEquals(0.0f, bean.floatValue); bean = MAPPER.readValue("{\"doubleValue\":\"\"}", PrimitivesBean.class); assertEquals(0.0, bean.doubleValue); } // for [JACKSON-652] // @since 1.9 public void testUntypedWithJsonArrays() throws Exception { // by default we get: Object ob = MAPPER.readValue("[1]", Object.class); assertTrue(ob instanceof List<?>); // but can change to produce Object[]: MAPPER.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); ob = MAPPER.readValue("[1]", Object.class); assertEquals(Object[].class, ob.getClass()); } // Test for verifying that Long values are coerced to boolean correctly as well public void testLongToBoolean() throws Exception { long value = 1L + Integer.MAX_VALUE; BooleanBean b = MAPPER.readValue("{\"primitive\" : "+value+", \"wrapper\":"+value+", \"ctor\":"+value+"}", BooleanBean.class); assertEquals(Boolean.TRUE, b.wrapper); assertTrue(b.primitive); assertEquals(Boolean.TRUE, b.ctor); } // [JACKSON-789] public void testCharset() throws Exception { Charset UTF8 = Charset.forName("UTF-8"); assertSame(UTF8, MAPPER.readValue(quote("UTF-8"), Charset.class)); } // [JACKSON-888] public void testStackTraceElement() throws Exception { StackTraceElement elem = null; try { throw new IllegalStateException(); } catch (Exception e) { elem = e.getStackTrace()[0]; } String json = MAPPER.writeValueAsString(elem); StackTraceElement back = MAPPER.readValue(json, StackTraceElement.class); assertEquals("testStackTraceElement", back.getMethodName()); assertEquals(elem.getLineNumber(), back.getLineNumber()); assertEquals(elem.getClassName(), back.getClassName()); assertEquals(elem.isNativeMethod(), back.isNativeMethod()); assertTrue(back.getClassName().endsWith("TestJdkTypes")); assertFalse(back.isNativeMethod()); } // [Issue#239] public void testByteBuffer() throws Exception { byte[] INPUT = new byte[] { 1, 3, 9, -1, 6 }; String exp = MAPPER.writeValueAsString(INPUT); ByteBuffer result = MAPPER.readValue(exp, ByteBuffer.class); assertNotNull(result); assertEquals(INPUT.length, result.remaining()); for (int i = 0; i < INPUT.length; ++i) { assertEquals(INPUT[i], result.get()); } assertEquals(0, result.remaining()); } public void testStringBuilder() throws Exception { StringBuilder sb = MAPPER.readValue(quote("abc"), StringBuilder.class); assertEquals("abc", sb.toString()); } // [Issue#429] public void testStackTraceElementWithCustom() throws Exception { // first, via bean that contains StackTraceElement StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"), StackTraceBean.class); assertNotNull(bean); assertNotNull(bean.location); assertEquals(StackTraceBean.NUM, bean.location.getLineNumber()); // and then directly, iff registered ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addDeserializer(StackTraceElement.class, new MyStackTraceElementDeserializer()); mapper.registerModule(module); StackTraceElement elem = mapper.readValue("123", StackTraceElement.class); assertNotNull(elem); assertEquals(StackTraceBean.NUM, elem.getLineNumber()); // and finally, even as part of real exception IOException ioe = mapper.readValue(aposToQuotes("{'stackTrace':[ 123, 456 ]}"), IOException.class); assertNotNull(ioe); StackTraceElement[] traces = ioe.getStackTrace(); assertNotNull(traces); assertEquals(2, traces.length); assertEquals(StackTraceBean.NUM, traces[0].getLineNumber()); assertEquals(StackTraceBean.NUM, traces[1].getLineNumber()); } /* /********************************************************** /* Single-array handling tests /********************************************************** */ // [Issue#381] public void testSingleElementArray() throws Exception { final int intTest = 932832; final double doubleTest = 32.3234; final long longTest = 2374237428374293423L; final short shortTest = (short) intTest; final float floatTest = 84.3743f; final byte byteTest = (byte) 43; final char charTest = 'c'; final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); final int intValue = mapper.readValue(asArray(intTest), Integer.TYPE); assertEquals(intTest, intValue); final Integer integerWrapperValue = mapper.readValue(asArray(Integer.valueOf(intTest)), Integer.class); assertEquals(Integer.valueOf(intTest), integerWrapperValue); final double doubleValue = mapper.readValue(asArray(doubleTest), Double.class); assertEquals(doubleTest, doubleValue); final Double doubleWrapperValue = mapper.readValue(asArray(Double.valueOf(doubleTest)), Double.class); assertEquals(Double.valueOf(doubleTest), doubleWrapperValue); final long longValue = mapper.readValue(asArray(longTest), Long.TYPE); assertEquals(longTest, longValue); final Long longWrapperValue = mapper.readValue(asArray(Long.valueOf(longTest)), Long.class); assertEquals(Long.valueOf(longTest), longWrapperValue); final short shortValue = mapper.readValue(asArray(shortTest), Short.TYPE); assertEquals(shortTest, shortValue); final Short shortWrapperValue = mapper.readValue(asArray(Short.valueOf(shortTest)), Short.class); assertEquals(Short.valueOf(shortTest), shortWrapperValue); final float floatValue = mapper.readValue(asArray(floatTest), Float.TYPE); assertEquals(floatTest, floatValue); final Float floatWrapperValue = mapper.readValue(asArray(Float.valueOf(floatTest)), Float.class); assertEquals(Float.valueOf(floatTest), floatWrapperValue); final byte byteValue = mapper.readValue(asArray(byteTest), Byte.TYPE); assertEquals(byteTest, byteValue); final Byte byteWrapperValue = mapper.readValue(asArray(Byte.valueOf(byteTest)), Byte.class); assertEquals(Byte.valueOf(byteTest), byteWrapperValue); final char charValue = mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.TYPE); assertEquals(charTest, charValue); final Character charWrapperValue = mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.class); assertEquals(Character.valueOf(charTest), charWrapperValue); final boolean booleanTrueValue = mapper.readValue(asArray(true), Boolean.TYPE); assertTrue(booleanTrueValue); final boolean booleanFalseValue = mapper.readValue(asArray(false), Boolean.TYPE); assertFalse(booleanFalseValue); final Boolean booleanWrapperTrueValue = mapper.readValue(asArray(Boolean.valueOf(true)), Boolean.class); assertEquals(Boolean.TRUE, booleanWrapperTrueValue); } private static String asArray(Object value) { final String stringVal = value.toString(); return new StringBuilder(stringVal.length() + 2).append("[").append(stringVal).append("]").toString(); } public void testSingleElementArrayException() throws Exception { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); try { mapper.readValue("[42]", Integer.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Integer.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42.273]", Double.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42.2723]", Double.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342]", Long.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342342]", Long.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Short.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Short.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[327.2323]", Float.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[82.81902]", Float.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[22]", Byte.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[22]", Byte.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("['d']", Character.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("['d']", Character.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[true]", Boolean.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[true]", Boolean.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } } public void testMultiValueArrayException() throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); try { mapper.readValue("[42,42]", Integer.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42,42]", Integer.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42.273,42.273]", Double.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42.2723,42.273]", Double.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342,42342342342342]", Long.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342342,42342342342342]", Long.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42,42]", Short.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[42,42]", Short.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[327.2323,327.2323]", Float.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[82.81902,327.2323]", Float.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[22,23]", Byte.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[22,23]", Byte.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue(asArray(quote("c") + "," + quote("d")), Character.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue(asArray(quote("c") + "," + quote("d")), Character.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[true,false]", Boolean.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } try { mapper.readValue("[true,false]", Boolean.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (JsonMappingException exp) { //Exception was thrown correctly } } }
@Test public void testMath789() { final RealMatrix m1 = MatrixUtils.createRealMatrix(new double[][]{ {0.013445532, 0.010394690, 0.009881156, 0.010499559}, {0.010394690, 0.023006616, 0.008196856, 0.010732709}, {0.009881156, 0.008196856, 0.019023866, 0.009210099}, {0.010499559, 0.010732709, 0.009210099, 0.019107243} }); RealMatrix root1 = new RectangularCholeskyDecomposition(m1, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM1 = root1.multiply(root1.transpose()); Assert.assertEquals(0.0, m1.subtract(rebuiltM1).getNorm(), 1.0e-16); final RealMatrix m2 = MatrixUtils.createRealMatrix(new double[][]{ {0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.013445532, 0.010394690, 0.009881156, 0.010499559}, {0.0, 0.010394690, 0.023006616, 0.008196856, 0.010732709}, {0.0, 0.009881156, 0.008196856, 0.019023866, 0.009210099}, {0.0, 0.010499559, 0.010732709, 0.009210099, 0.019107243} }); RealMatrix root2 = new RectangularCholeskyDecomposition(m2, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM2 = root2.multiply(root2.transpose()); Assert.assertEquals(0.0, m2.subtract(rebuiltM2).getNorm(), 1.0e-16); final RealMatrix m3 = MatrixUtils.createRealMatrix(new double[][]{ {0.013445532, 0.010394690, 0.0, 0.009881156, 0.010499559}, {0.010394690, 0.023006616, 0.0, 0.008196856, 0.010732709}, {0.0, 0.0, 0.0, 0.0, 0.0}, {0.009881156, 0.008196856, 0.0, 0.019023866, 0.009210099}, {0.010499559, 0.010732709, 0.0, 0.009210099, 0.019107243} }); RealMatrix root3 = new RectangularCholeskyDecomposition(m3, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM3 = root3.multiply(root3.transpose()); Assert.assertEquals(0.0, m3.subtract(rebuiltM3).getNorm(), 1.0e-16); }
org.apache.commons.math3.linear.RectangularCholeskyDecompositionTest::testMath789
src/test/java/org/apache/commons/math3/linear/RectangularCholeskyDecompositionTest.java
109
src/test/java/org/apache/commons/math3/linear/RectangularCholeskyDecompositionTest.java
testMath789
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.linear; import org.junit.Test; import org.junit.Assert; public class RectangularCholeskyDecompositionTest { @Test public void testDecomposition3x3() { RealMatrix m = MatrixUtils.createRealMatrix(new double[][] { { 1, 9, 9 }, { 9, 225, 225 }, { 9, 225, 625 } }); RectangularCholeskyDecomposition d = new RectangularCholeskyDecomposition(m, 1.0e-6); // as this decomposition permutes lines and columns, the root is NOT triangular // (in fact here it is the lower right part of the matrix which is zero and // the upper left non-zero) Assert.assertEquals(0.8, d.getRootMatrix().getEntry(0, 2), 1.0e-15); Assert.assertEquals(25.0, d.getRootMatrix().getEntry(2, 0), 1.0e-15); Assert.assertEquals(0.0, d.getRootMatrix().getEntry(2, 2), 1.0e-15); RealMatrix root = d.getRootMatrix(); RealMatrix rebuiltM = root.multiply(root.transpose()); Assert.assertEquals(0.0, m.subtract(rebuiltM).getNorm(), 1.0e-15); } @Test public void testFullRank() { RealMatrix base = MatrixUtils.createRealMatrix(new double[][] { { 0.1159548705, 0., 0., 0. }, { 0.0896442724, 0.1223540781, 0., 0. }, { 0.0852155322, 4.558668e-3, 0.1083577299, 0. }, { 0.0905486674, 0.0213768077, 0.0128878333, 0.1014155693 } }); RealMatrix m = base.multiply(base.transpose()); RectangularCholeskyDecomposition d = new RectangularCholeskyDecomposition(m, 1.0e-10); RealMatrix root = d.getRootMatrix(); RealMatrix rebuiltM = root.multiply(root.transpose()); Assert.assertEquals(0.0, m.subtract(rebuiltM).getNorm(), 1.0e-15); // the pivoted Cholesky decomposition is *not* unique. Here, the root is // not equal to the original trianbular base matrix Assert.assertTrue(root.subtract(base).getNorm() > 0.3); } @Test public void testMath789() { final RealMatrix m1 = MatrixUtils.createRealMatrix(new double[][]{ {0.013445532, 0.010394690, 0.009881156, 0.010499559}, {0.010394690, 0.023006616, 0.008196856, 0.010732709}, {0.009881156, 0.008196856, 0.019023866, 0.009210099}, {0.010499559, 0.010732709, 0.009210099, 0.019107243} }); RealMatrix root1 = new RectangularCholeskyDecomposition(m1, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM1 = root1.multiply(root1.transpose()); Assert.assertEquals(0.0, m1.subtract(rebuiltM1).getNorm(), 1.0e-16); final RealMatrix m2 = MatrixUtils.createRealMatrix(new double[][]{ {0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.013445532, 0.010394690, 0.009881156, 0.010499559}, {0.0, 0.010394690, 0.023006616, 0.008196856, 0.010732709}, {0.0, 0.009881156, 0.008196856, 0.019023866, 0.009210099}, {0.0, 0.010499559, 0.010732709, 0.009210099, 0.019107243} }); RealMatrix root2 = new RectangularCholeskyDecomposition(m2, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM2 = root2.multiply(root2.transpose()); Assert.assertEquals(0.0, m2.subtract(rebuiltM2).getNorm(), 1.0e-16); final RealMatrix m3 = MatrixUtils.createRealMatrix(new double[][]{ {0.013445532, 0.010394690, 0.0, 0.009881156, 0.010499559}, {0.010394690, 0.023006616, 0.0, 0.008196856, 0.010732709}, {0.0, 0.0, 0.0, 0.0, 0.0}, {0.009881156, 0.008196856, 0.0, 0.019023866, 0.009210099}, {0.010499559, 0.010732709, 0.0, 0.009210099, 0.019107243} }); RealMatrix root3 = new RectangularCholeskyDecomposition(m3, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM3 = root3.multiply(root3.transpose()); Assert.assertEquals(0.0, m3.subtract(rebuiltM3).getNorm(), 1.0e-16); } }
// You are a professional Java test case writer, please create a test case named `testMath789` for the issue `Math-MATH-789`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-789 // // ## Issue-Title: // Correlated random vector generator fails (silently) when faced with zero rows in covariance matrix // // ## Issue-Description: // // The following three matrices (which are basically permutations of each other) produce different results when sampling a multi-variate Gaussian with the help of CorrelatedRandomVectorGenerator (sample covariances calculated in R, based on 10,000 samples): // // // Array2DRowRealMatrix // // // { // {0.0,0.0,0.0,0.0,0.0} // , // // // {0.0,0.013445532,0.01039469,0.009881156,0.010499559} // , // // // {0.0,0.01039469,0.023006616,0.008196856,0.010732709} // , // // // {0.0,0.009881156,0.008196856,0.019023866,0.009210099} // , // // {0.0,0.010499559,0.010732709,0.009210099,0.019107243}} // // // > cov(data1) // // V1 V2 V3 V4 V5 // // V1 0 0.000000000 0.00000000 0.000000000 0.000000000 // // V2 0 0.013383931 0.01034401 0.009913271 0.010506733 // // V3 0 0.010344006 0.02309479 0.008374730 0.010759306 // // V4 0 0.009913271 0.00837473 0.019005488 0.009187287 // // V5 0 0.010506733 0.01075931 0.009187287 0.019021483 // // // Array2DRowRealMatrix // // // { // {0.013445532,0.01039469,0.0,0.009881156,0.010499559} // , // // // {0.01039469,0.023006616,0.0,0.008196856,0.010732709} // , // // // {0.0,0.0,0.0,0.0,0.0}, // {0.009881156,0.008196856,0.0,0.019023866,0.009210099}, // // {0.010499559,0.010732709,0.0,0.009210099,0.019107243}} // // // // > cov(data2) // // V1 V2 V3 V4 V5 // // V1 0.006922905 0.010507692 0 0.005817399 0.010330529 // // V2 0.010507692 0.023428918 0 0.008273152 0.010735568 // // V3 0.000000000 0.000000000 0 0.000000000 0.000000000 // // V4 0.005817399 0.008273152 0 0.004929843 0.009048759 // // V5 0.010330529 0.010735568 0 0.009048759 0.018683544 // // // // Array2DRowRealMatrix{ // {0.013445532,0.01039469,0.009881156,0.010499559}, // {0.01039469,0.023006616,0.008196856,0.010732709}, // {0.009881156,0.008196856,0.019023866,0.009210099}, // // {0.010499559,0.010732709,0.009210099,0.019107243}} // // // // > cov(data3) // // V1 V2 V3 V4 // // V1 0.013445047 0.010478862 0.009955904 0.010529542 // // V2 0.010478862 0.022910522 0.008610113 0.011046353 // // V3 0.009955904 0.008610113 0.019250975 @Test public void testMath789() {
109
21
74
src/test/java/org/apache/commons/math3/linear/RectangularCholeskyDecompositionTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-789 ## Issue-Title: Correlated random vector generator fails (silently) when faced with zero rows in covariance matrix ## Issue-Description: The following three matrices (which are basically permutations of each other) produce different results when sampling a multi-variate Gaussian with the help of CorrelatedRandomVectorGenerator (sample covariances calculated in R, based on 10,000 samples): Array2DRowRealMatrix { {0.0,0.0,0.0,0.0,0.0} , {0.0,0.013445532,0.01039469,0.009881156,0.010499559} , {0.0,0.01039469,0.023006616,0.008196856,0.010732709} , {0.0,0.009881156,0.008196856,0.019023866,0.009210099} , {0.0,0.010499559,0.010732709,0.009210099,0.019107243}} > cov(data1) V1 V2 V3 V4 V5 V1 0 0.000000000 0.00000000 0.000000000 0.000000000 V2 0 0.013383931 0.01034401 0.009913271 0.010506733 V3 0 0.010344006 0.02309479 0.008374730 0.010759306 V4 0 0.009913271 0.00837473 0.019005488 0.009187287 V5 0 0.010506733 0.01075931 0.009187287 0.019021483 Array2DRowRealMatrix { {0.013445532,0.01039469,0.0,0.009881156,0.010499559} , {0.01039469,0.023006616,0.0,0.008196856,0.010732709} , {0.0,0.0,0.0,0.0,0.0}, {0.009881156,0.008196856,0.0,0.019023866,0.009210099}, {0.010499559,0.010732709,0.0,0.009210099,0.019107243}} > cov(data2) V1 V2 V3 V4 V5 V1 0.006922905 0.010507692 0 0.005817399 0.010330529 V2 0.010507692 0.023428918 0 0.008273152 0.010735568 V3 0.000000000 0.000000000 0 0.000000000 0.000000000 V4 0.005817399 0.008273152 0 0.004929843 0.009048759 V5 0.010330529 0.010735568 0 0.009048759 0.018683544 Array2DRowRealMatrix{ {0.013445532,0.01039469,0.009881156,0.010499559}, {0.01039469,0.023006616,0.008196856,0.010732709}, {0.009881156,0.008196856,0.019023866,0.009210099}, {0.010499559,0.010732709,0.009210099,0.019107243}} > cov(data3) V1 V2 V3 V4 V1 0.013445047 0.010478862 0.009955904 0.010529542 V2 0.010478862 0.022910522 0.008610113 0.011046353 V3 0.009955904 0.008610113 0.019250975 ``` You are a professional Java test case writer, please create a test case named `testMath789` for the issue `Math-MATH-789`, utilizing the provided issue report information and the following function signature. ```java @Test public void testMath789() { ```
74
[ "org.apache.commons.math3.linear.RectangularCholeskyDecomposition" ]
25ce6f904e47dc9c04734dc916bd41f91530199ea50d7316ad0bef227ada4a73
@Test public void testMath789()
// You are a professional Java test case writer, please create a test case named `testMath789` for the issue `Math-MATH-789`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-789 // // ## Issue-Title: // Correlated random vector generator fails (silently) when faced with zero rows in covariance matrix // // ## Issue-Description: // // The following three matrices (which are basically permutations of each other) produce different results when sampling a multi-variate Gaussian with the help of CorrelatedRandomVectorGenerator (sample covariances calculated in R, based on 10,000 samples): // // // Array2DRowRealMatrix // // // { // {0.0,0.0,0.0,0.0,0.0} // , // // // {0.0,0.013445532,0.01039469,0.009881156,0.010499559} // , // // // {0.0,0.01039469,0.023006616,0.008196856,0.010732709} // , // // // {0.0,0.009881156,0.008196856,0.019023866,0.009210099} // , // // {0.0,0.010499559,0.010732709,0.009210099,0.019107243}} // // // > cov(data1) // // V1 V2 V3 V4 V5 // // V1 0 0.000000000 0.00000000 0.000000000 0.000000000 // // V2 0 0.013383931 0.01034401 0.009913271 0.010506733 // // V3 0 0.010344006 0.02309479 0.008374730 0.010759306 // // V4 0 0.009913271 0.00837473 0.019005488 0.009187287 // // V5 0 0.010506733 0.01075931 0.009187287 0.019021483 // // // Array2DRowRealMatrix // // // { // {0.013445532,0.01039469,0.0,0.009881156,0.010499559} // , // // // {0.01039469,0.023006616,0.0,0.008196856,0.010732709} // , // // // {0.0,0.0,0.0,0.0,0.0}, // {0.009881156,0.008196856,0.0,0.019023866,0.009210099}, // // {0.010499559,0.010732709,0.0,0.009210099,0.019107243}} // // // // > cov(data2) // // V1 V2 V3 V4 V5 // // V1 0.006922905 0.010507692 0 0.005817399 0.010330529 // // V2 0.010507692 0.023428918 0 0.008273152 0.010735568 // // V3 0.000000000 0.000000000 0 0.000000000 0.000000000 // // V4 0.005817399 0.008273152 0 0.004929843 0.009048759 // // V5 0.010330529 0.010735568 0 0.009048759 0.018683544 // // // // Array2DRowRealMatrix{ // {0.013445532,0.01039469,0.009881156,0.010499559}, // {0.01039469,0.023006616,0.008196856,0.010732709}, // {0.009881156,0.008196856,0.019023866,0.009210099}, // // {0.010499559,0.010732709,0.009210099,0.019107243}} // // // // > cov(data3) // // V1 V2 V3 V4 // // V1 0.013445047 0.010478862 0.009955904 0.010529542 // // V2 0.010478862 0.022910522 0.008610113 0.011046353 // // V3 0.009955904 0.008610113 0.019250975
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.linear; import org.junit.Test; import org.junit.Assert; public class RectangularCholeskyDecompositionTest { @Test public void testDecomposition3x3() { RealMatrix m = MatrixUtils.createRealMatrix(new double[][] { { 1, 9, 9 }, { 9, 225, 225 }, { 9, 225, 625 } }); RectangularCholeskyDecomposition d = new RectangularCholeskyDecomposition(m, 1.0e-6); // as this decomposition permutes lines and columns, the root is NOT triangular // (in fact here it is the lower right part of the matrix which is zero and // the upper left non-zero) Assert.assertEquals(0.8, d.getRootMatrix().getEntry(0, 2), 1.0e-15); Assert.assertEquals(25.0, d.getRootMatrix().getEntry(2, 0), 1.0e-15); Assert.assertEquals(0.0, d.getRootMatrix().getEntry(2, 2), 1.0e-15); RealMatrix root = d.getRootMatrix(); RealMatrix rebuiltM = root.multiply(root.transpose()); Assert.assertEquals(0.0, m.subtract(rebuiltM).getNorm(), 1.0e-15); } @Test public void testFullRank() { RealMatrix base = MatrixUtils.createRealMatrix(new double[][] { { 0.1159548705, 0., 0., 0. }, { 0.0896442724, 0.1223540781, 0., 0. }, { 0.0852155322, 4.558668e-3, 0.1083577299, 0. }, { 0.0905486674, 0.0213768077, 0.0128878333, 0.1014155693 } }); RealMatrix m = base.multiply(base.transpose()); RectangularCholeskyDecomposition d = new RectangularCholeskyDecomposition(m, 1.0e-10); RealMatrix root = d.getRootMatrix(); RealMatrix rebuiltM = root.multiply(root.transpose()); Assert.assertEquals(0.0, m.subtract(rebuiltM).getNorm(), 1.0e-15); // the pivoted Cholesky decomposition is *not* unique. Here, the root is // not equal to the original trianbular base matrix Assert.assertTrue(root.subtract(base).getNorm() > 0.3); } @Test public void testMath789() { final RealMatrix m1 = MatrixUtils.createRealMatrix(new double[][]{ {0.013445532, 0.010394690, 0.009881156, 0.010499559}, {0.010394690, 0.023006616, 0.008196856, 0.010732709}, {0.009881156, 0.008196856, 0.019023866, 0.009210099}, {0.010499559, 0.010732709, 0.009210099, 0.019107243} }); RealMatrix root1 = new RectangularCholeskyDecomposition(m1, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM1 = root1.multiply(root1.transpose()); Assert.assertEquals(0.0, m1.subtract(rebuiltM1).getNorm(), 1.0e-16); final RealMatrix m2 = MatrixUtils.createRealMatrix(new double[][]{ {0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.013445532, 0.010394690, 0.009881156, 0.010499559}, {0.0, 0.010394690, 0.023006616, 0.008196856, 0.010732709}, {0.0, 0.009881156, 0.008196856, 0.019023866, 0.009210099}, {0.0, 0.010499559, 0.010732709, 0.009210099, 0.019107243} }); RealMatrix root2 = new RectangularCholeskyDecomposition(m2, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM2 = root2.multiply(root2.transpose()); Assert.assertEquals(0.0, m2.subtract(rebuiltM2).getNorm(), 1.0e-16); final RealMatrix m3 = MatrixUtils.createRealMatrix(new double[][]{ {0.013445532, 0.010394690, 0.0, 0.009881156, 0.010499559}, {0.010394690, 0.023006616, 0.0, 0.008196856, 0.010732709}, {0.0, 0.0, 0.0, 0.0, 0.0}, {0.009881156, 0.008196856, 0.0, 0.019023866, 0.009210099}, {0.010499559, 0.010732709, 0.0, 0.009210099, 0.019107243} }); RealMatrix root3 = new RectangularCholeskyDecomposition(m3, 1.0e-10).getRootMatrix(); RealMatrix rebuiltM3 = root3.multiply(root3.transpose()); Assert.assertEquals(0.0, m3.subtract(rebuiltM3).getNorm(), 1.0e-16); } }
public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); }
com.google.javascript.jscomp.TypeCheckTest::testIssue586
test/com/google/javascript/jscomp/TypeCheckTest.java
5,454
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue586
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferrable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode] :2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Tehnically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes thru this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a runtime cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {boolean} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. May be it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n"+ "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n"+ "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // ok, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format()); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format("number")); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format()); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testFunctionLiteralUndefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testIssue586` for the issue `Closure-586`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-586 // // ## Issue-Title: // Type checking error when replacing a function with a stub after calling. // // ## Issue-Description: // Given the following Javascript: // // /\*\* @constructor \*/ // var myclass = function() { // } // // /\*\* @param {boolean} success \*/ // myclass.prototype.fn = function(success) { } // // myclass.prototype.test = function() { // this.fn(); // this.fn = function() { }; // } // // I would expect an error at both lines of test(). Instead, the second line causes the error in the first not to be reported. // // public void testIssue586() throws Exception {
5,454
48
5,441
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-586 ## Issue-Title: Type checking error when replacing a function with a stub after calling. ## Issue-Description: Given the following Javascript: /\*\* @constructor \*/ var myclass = function() { } /\*\* @param {boolean} success \*/ myclass.prototype.fn = function(success) { } myclass.prototype.test = function() { this.fn(); this.fn = function() { }; } I would expect an error at both lines of test(). Instead, the second line causes the error in the first not to be reported. ``` You are a professional Java test case writer, please create a test case named `testIssue586` for the issue `Closure-586`, utilizing the provided issue report information and the following function signature. ```java public void testIssue586() throws Exception { ```
5,441
[ "com.google.javascript.jscomp.TypedScopeCreator" ]
26bc0c2808e473ff6e6caf715fee92c23783be55508a0e5d77ee80a304b4eb69
public void testIssue586() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue586` for the issue `Closure-586`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-586 // // ## Issue-Title: // Type checking error when replacing a function with a stub after calling. // // ## Issue-Description: // Given the following Javascript: // // /\*\* @constructor \*/ // var myclass = function() { // } // // /\*\* @param {boolean} success \*/ // myclass.prototype.fn = function(success) { } // // myclass.prototype.test = function() { // this.fn(); // this.fn = function() { }; // } // // I would expect an error at both lines of test(). Instead, the second line causes the error in the first not to be reported. // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferrable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode] :2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Tehnically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes thru this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a runtime cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {boolean} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. May be it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n"+ "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n"+ "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // ok, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format()); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format("number")); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format()); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testFunctionLiteralUndefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
public void testSevenEmptyFiles() throws Exception { testCompress252(7, 0); }
org.apache.commons.compress.archivers.sevenz.SevenZOutputFileTest::testSevenEmptyFiles
src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFileTest.java
183
src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFileTest.java
testSevenEmptyFiles
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.sevenz; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.Date; import org.apache.commons.compress.AbstractTestCase; public class SevenZOutputFileTest extends AbstractTestCase { private File output; public void tearDown() throws Exception { if (output != null && !output.delete()) { output.deleteOnExit(); } } public void testDirectoriesAndEmptyFiles() throws Exception { File output = new File(dir, "empties.7z"); Date accessDate = new Date(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -1); Date creationDate = cal.getTime(); SevenZOutputFile outArchive = new SevenZOutputFile(output); try { SevenZArchiveEntry entry = outArchive.createArchiveEntry(dir, "foo/"); outArchive.putArchiveEntry(entry); outArchive.closeArchiveEntry(); entry = new SevenZArchiveEntry(); entry.setName("foo/bar"); entry.setCreationDate(creationDate); entry.setAccessDate(accessDate); outArchive.putArchiveEntry(entry); outArchive.write(new byte[0]); outArchive.closeArchiveEntry(); entry = new SevenZArchiveEntry(); entry.setName("xyzzy"); outArchive.putArchiveEntry(entry); outArchive.write(0); outArchive.closeArchiveEntry(); entry = outArchive.createArchiveEntry(dir, "baz/"); entry.setAntiItem(true); outArchive.putArchiveEntry(entry); outArchive.closeArchiveEntry(); entry = new SevenZArchiveEntry(); entry.setName("dada"); entry.setHasWindowsAttributes(true); entry.setWindowsAttributes(17); outArchive.putArchiveEntry(entry); outArchive.write(5); outArchive.write(42); outArchive.closeArchiveEntry(); outArchive.finish(); } finally { outArchive.close(); } final SevenZFile archive = new SevenZFile(output); try { SevenZArchiveEntry entry = archive.getNextEntry(); assert(entry != null); assertEquals("foo/", entry.getName()); assertTrue(entry.isDirectory()); assertFalse(entry.isAntiItem()); entry = archive.getNextEntry(); assert(entry != null); assertEquals("foo/bar", entry.getName()); assertFalse(entry.isDirectory()); assertFalse(entry.isAntiItem()); assertEquals(0, entry.getSize()); assertFalse(entry.getHasLastModifiedDate()); assertEquals(accessDate, entry.getAccessDate()); assertEquals(creationDate, entry.getCreationDate()); entry = archive.getNextEntry(); assert(entry != null); assertEquals("xyzzy", entry.getName()); assertEquals(1, entry.getSize()); assertFalse(entry.getHasAccessDate()); assertFalse(entry.getHasCreationDate()); assertEquals(0, archive.read()); entry = archive.getNextEntry(); assert(entry != null); assertEquals("baz/", entry.getName()); assertTrue(entry.isDirectory()); assertTrue(entry.isAntiItem()); entry = archive.getNextEntry(); assert(entry != null); assertEquals("dada", entry.getName()); assertEquals(2, entry.getSize()); byte[] content = new byte[2]; assertEquals(2, archive.read(content)); assertEquals(5, content[0]); assertEquals(42, content[1]); assertEquals(17, entry.getWindowsAttributes()); assert(archive.getNextEntry() == null); } finally { archive.close(); } } public void testDirectoriesOnly() throws Exception { File output = new File(dir, "dirs.7z"); SevenZOutputFile outArchive = new SevenZOutputFile(output); try { SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setName("foo/"); entry.setDirectory(true); outArchive.putArchiveEntry(entry); outArchive.closeArchiveEntry(); } finally { outArchive.close(); } final SevenZFile archive = new SevenZFile(output); try { SevenZArchiveEntry entry = archive.getNextEntry(); assert(entry != null); assertEquals("foo/", entry.getName()); assertTrue(entry.isDirectory()); assertFalse(entry.isAntiItem()); assert(archive.getNextEntry() == null); } finally { archive.close(); } } public void testCantFinishTwice() throws Exception { File output = new File(dir, "finish.7z"); SevenZOutputFile outArchive = new SevenZOutputFile(output); try { outArchive.finish(); outArchive.finish(); fail("shouldn't be able to call finish twice"); } catch (IOException ex) { assertEquals("This archive has already been finished", ex.getMessage()); } finally { outArchive.close(); } } public void testSixEmptyFiles() throws Exception { testCompress252(6, 0); } public void testSixFilesSomeNotEmpty() throws Exception { testCompress252(6, 2); } public void testSevenEmptyFiles() throws Exception { testCompress252(7, 0); } public void testSevenFilesSomeNotEmpty() throws Exception { testCompress252(7, 2); } public void testEightEmptyFiles() throws Exception { testCompress252(8, 0); } public void testEightFilesSomeNotEmpty() throws Exception { testCompress252(8, 2); } public void testNineEmptyFiles() throws Exception { testCompress252(9, 0); } public void testNineFilesSomeNotEmpty() throws Exception { testCompress252(9, 2); } private void testCompress252(int numberOfFiles, int numberOfNonEmptyFiles) throws Exception { int nonEmptyModulus = numberOfNonEmptyFiles != 0 ? numberOfFiles / numberOfNonEmptyFiles : numberOfFiles + 1; output = new File(dir, "COMPRESS252-" + numberOfFiles + "-" + numberOfNonEmptyFiles + ".7z"); SevenZOutputFile archive = new SevenZOutputFile(output); try { addDir(archive); for (int i = 0; i < numberOfFiles; i++) { addFile(archive, i, (i + 1) % nonEmptyModulus == 0); } } finally { archive.close(); } verifyCompress252(output, numberOfFiles, numberOfNonEmptyFiles); } private void verifyCompress252(File output, int numberOfFiles, int numberOfNonEmptyFiles) throws Exception { SevenZFile archive = new SevenZFile(output); int filesFound = 0; int nonEmptyFilesFound = 0; try { verifyDir(archive); Boolean b = verifyFile(archive, filesFound++); while (b != null) { if (Boolean.TRUE.equals(b)) { nonEmptyFilesFound++; } b = verifyFile(archive, filesFound++); } } finally { archive.close(); } assertEquals(numberOfFiles + 1, filesFound); assertEquals(numberOfNonEmptyFiles, nonEmptyFilesFound); } private void addDir(SevenZOutputFile archive) throws Exception { SevenZArchiveEntry entry = archive.createArchiveEntry(dir, "foo/"); archive.putArchiveEntry(entry); archive.closeArchiveEntry(); } private void verifyDir(SevenZFile archive) throws Exception { SevenZArchiveEntry entry = archive.getNextEntry(); assertNotNull(entry); assertEquals("foo/", entry.getName()); assertTrue(entry.isDirectory()); } private void addFile(SevenZOutputFile archive, int index, boolean nonEmpty) throws Exception { SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setName("foo/" + index + ".txt"); archive.putArchiveEntry(entry); archive.write(nonEmpty ? new byte[] { 17 } : new byte[0]); archive.closeArchiveEntry(); } private Boolean verifyFile(SevenZFile archive, int index) throws Exception { SevenZArchiveEntry entry = archive.getNextEntry(); if (entry == null) { return null; } assertEquals("foo/" + index + ".txt", entry.getName()); assertEquals(false, entry.isDirectory()); if (entry.getSize() == 0) { return false; } assertEquals(1, entry.getSize()); assertEquals(17, archive.read()); assertEquals(-1, archive.read()); return true; } }
// You are a professional Java test case writer, please create a test case named `testSevenEmptyFiles` for the issue `Compress-COMPRESS-252`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-252 // // ## Issue-Title: // Writing 7z empty entries produces incorrect or corrupt archive // // ## Issue-Description: // // I couldn't find an exact rule that causes this incorrect behavior, but I tried to reduce it to some simple scenarios to reproduce it: // // // Input: A folder with certain files -> tried to archive it. // // If the folder contains more than 7 files the incorrect behavior appears. // // // Scenario 1: 7 empty files // // Result: The created archive contains a single folder entry with the name of the archive (no matter which was the name of the file) // // // Scenario 2: 7 files, some empty, some with content // // Result: The created archive contains a folder entry with the name of the archive and a number of file entries also with the name of the archive. The number of the entries is equal to the number of non empty files. // // // Scenario 3: 8 empty files // // Result: 7zip Manager cannot open archive and stops working. // // // Scenario 4.1: 8 files: some empty, some with content, last file (alphabetically) with content // // Result: same behavior as described for Scenario 2. // // // Scenario 4.2: 8 files, some empty, some with content, last file empy // // Result: archive is corrupt, the following message is received: "Cannot open file 'archivename.7z' as archive" (7Zip Manager does not crash). // // // // // public void testSevenEmptyFiles() throws Exception {
183
21
181
src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFileTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-252 ## Issue-Title: Writing 7z empty entries produces incorrect or corrupt archive ## Issue-Description: I couldn't find an exact rule that causes this incorrect behavior, but I tried to reduce it to some simple scenarios to reproduce it: Input: A folder with certain files -> tried to archive it. If the folder contains more than 7 files the incorrect behavior appears. Scenario 1: 7 empty files Result: The created archive contains a single folder entry with the name of the archive (no matter which was the name of the file) Scenario 2: 7 files, some empty, some with content Result: The created archive contains a folder entry with the name of the archive and a number of file entries also with the name of the archive. The number of the entries is equal to the number of non empty files. Scenario 3: 8 empty files Result: 7zip Manager cannot open archive and stops working. Scenario 4.1: 8 files: some empty, some with content, last file (alphabetically) with content Result: same behavior as described for Scenario 2. Scenario 4.2: 8 files, some empty, some with content, last file empy Result: archive is corrupt, the following message is received: "Cannot open file 'archivename.7z' as archive" (7Zip Manager does not crash). ``` You are a professional Java test case writer, please create a test case named `testSevenEmptyFiles` for the issue `Compress-COMPRESS-252`, utilizing the provided issue report information and the following function signature. ```java public void testSevenEmptyFiles() throws Exception { ```
181
[ "org.apache.commons.compress.archivers.sevenz.SevenZOutputFile" ]
272c97e4ee0c7cfde081b872001292c9757bb65de33ad2b8559ded884889824b
public void testSevenEmptyFiles() throws Exception
// You are a professional Java test case writer, please create a test case named `testSevenEmptyFiles` for the issue `Compress-COMPRESS-252`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-252 // // ## Issue-Title: // Writing 7z empty entries produces incorrect or corrupt archive // // ## Issue-Description: // // I couldn't find an exact rule that causes this incorrect behavior, but I tried to reduce it to some simple scenarios to reproduce it: // // // Input: A folder with certain files -> tried to archive it. // // If the folder contains more than 7 files the incorrect behavior appears. // // // Scenario 1: 7 empty files // // Result: The created archive contains a single folder entry with the name of the archive (no matter which was the name of the file) // // // Scenario 2: 7 files, some empty, some with content // // Result: The created archive contains a folder entry with the name of the archive and a number of file entries also with the name of the archive. The number of the entries is equal to the number of non empty files. // // // Scenario 3: 8 empty files // // Result: 7zip Manager cannot open archive and stops working. // // // Scenario 4.1: 8 files: some empty, some with content, last file (alphabetically) with content // // Result: same behavior as described for Scenario 2. // // // Scenario 4.2: 8 files, some empty, some with content, last file empy // // Result: archive is corrupt, the following message is received: "Cannot open file 'archivename.7z' as archive" (7Zip Manager does not crash). // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.sevenz; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.Date; import org.apache.commons.compress.AbstractTestCase; public class SevenZOutputFileTest extends AbstractTestCase { private File output; public void tearDown() throws Exception { if (output != null && !output.delete()) { output.deleteOnExit(); } } public void testDirectoriesAndEmptyFiles() throws Exception { File output = new File(dir, "empties.7z"); Date accessDate = new Date(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -1); Date creationDate = cal.getTime(); SevenZOutputFile outArchive = new SevenZOutputFile(output); try { SevenZArchiveEntry entry = outArchive.createArchiveEntry(dir, "foo/"); outArchive.putArchiveEntry(entry); outArchive.closeArchiveEntry(); entry = new SevenZArchiveEntry(); entry.setName("foo/bar"); entry.setCreationDate(creationDate); entry.setAccessDate(accessDate); outArchive.putArchiveEntry(entry); outArchive.write(new byte[0]); outArchive.closeArchiveEntry(); entry = new SevenZArchiveEntry(); entry.setName("xyzzy"); outArchive.putArchiveEntry(entry); outArchive.write(0); outArchive.closeArchiveEntry(); entry = outArchive.createArchiveEntry(dir, "baz/"); entry.setAntiItem(true); outArchive.putArchiveEntry(entry); outArchive.closeArchiveEntry(); entry = new SevenZArchiveEntry(); entry.setName("dada"); entry.setHasWindowsAttributes(true); entry.setWindowsAttributes(17); outArchive.putArchiveEntry(entry); outArchive.write(5); outArchive.write(42); outArchive.closeArchiveEntry(); outArchive.finish(); } finally { outArchive.close(); } final SevenZFile archive = new SevenZFile(output); try { SevenZArchiveEntry entry = archive.getNextEntry(); assert(entry != null); assertEquals("foo/", entry.getName()); assertTrue(entry.isDirectory()); assertFalse(entry.isAntiItem()); entry = archive.getNextEntry(); assert(entry != null); assertEquals("foo/bar", entry.getName()); assertFalse(entry.isDirectory()); assertFalse(entry.isAntiItem()); assertEquals(0, entry.getSize()); assertFalse(entry.getHasLastModifiedDate()); assertEquals(accessDate, entry.getAccessDate()); assertEquals(creationDate, entry.getCreationDate()); entry = archive.getNextEntry(); assert(entry != null); assertEquals("xyzzy", entry.getName()); assertEquals(1, entry.getSize()); assertFalse(entry.getHasAccessDate()); assertFalse(entry.getHasCreationDate()); assertEquals(0, archive.read()); entry = archive.getNextEntry(); assert(entry != null); assertEquals("baz/", entry.getName()); assertTrue(entry.isDirectory()); assertTrue(entry.isAntiItem()); entry = archive.getNextEntry(); assert(entry != null); assertEquals("dada", entry.getName()); assertEquals(2, entry.getSize()); byte[] content = new byte[2]; assertEquals(2, archive.read(content)); assertEquals(5, content[0]); assertEquals(42, content[1]); assertEquals(17, entry.getWindowsAttributes()); assert(archive.getNextEntry() == null); } finally { archive.close(); } } public void testDirectoriesOnly() throws Exception { File output = new File(dir, "dirs.7z"); SevenZOutputFile outArchive = new SevenZOutputFile(output); try { SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setName("foo/"); entry.setDirectory(true); outArchive.putArchiveEntry(entry); outArchive.closeArchiveEntry(); } finally { outArchive.close(); } final SevenZFile archive = new SevenZFile(output); try { SevenZArchiveEntry entry = archive.getNextEntry(); assert(entry != null); assertEquals("foo/", entry.getName()); assertTrue(entry.isDirectory()); assertFalse(entry.isAntiItem()); assert(archive.getNextEntry() == null); } finally { archive.close(); } } public void testCantFinishTwice() throws Exception { File output = new File(dir, "finish.7z"); SevenZOutputFile outArchive = new SevenZOutputFile(output); try { outArchive.finish(); outArchive.finish(); fail("shouldn't be able to call finish twice"); } catch (IOException ex) { assertEquals("This archive has already been finished", ex.getMessage()); } finally { outArchive.close(); } } public void testSixEmptyFiles() throws Exception { testCompress252(6, 0); } public void testSixFilesSomeNotEmpty() throws Exception { testCompress252(6, 2); } public void testSevenEmptyFiles() throws Exception { testCompress252(7, 0); } public void testSevenFilesSomeNotEmpty() throws Exception { testCompress252(7, 2); } public void testEightEmptyFiles() throws Exception { testCompress252(8, 0); } public void testEightFilesSomeNotEmpty() throws Exception { testCompress252(8, 2); } public void testNineEmptyFiles() throws Exception { testCompress252(9, 0); } public void testNineFilesSomeNotEmpty() throws Exception { testCompress252(9, 2); } private void testCompress252(int numberOfFiles, int numberOfNonEmptyFiles) throws Exception { int nonEmptyModulus = numberOfNonEmptyFiles != 0 ? numberOfFiles / numberOfNonEmptyFiles : numberOfFiles + 1; output = new File(dir, "COMPRESS252-" + numberOfFiles + "-" + numberOfNonEmptyFiles + ".7z"); SevenZOutputFile archive = new SevenZOutputFile(output); try { addDir(archive); for (int i = 0; i < numberOfFiles; i++) { addFile(archive, i, (i + 1) % nonEmptyModulus == 0); } } finally { archive.close(); } verifyCompress252(output, numberOfFiles, numberOfNonEmptyFiles); } private void verifyCompress252(File output, int numberOfFiles, int numberOfNonEmptyFiles) throws Exception { SevenZFile archive = new SevenZFile(output); int filesFound = 0; int nonEmptyFilesFound = 0; try { verifyDir(archive); Boolean b = verifyFile(archive, filesFound++); while (b != null) { if (Boolean.TRUE.equals(b)) { nonEmptyFilesFound++; } b = verifyFile(archive, filesFound++); } } finally { archive.close(); } assertEquals(numberOfFiles + 1, filesFound); assertEquals(numberOfNonEmptyFiles, nonEmptyFilesFound); } private void addDir(SevenZOutputFile archive) throws Exception { SevenZArchiveEntry entry = archive.createArchiveEntry(dir, "foo/"); archive.putArchiveEntry(entry); archive.closeArchiveEntry(); } private void verifyDir(SevenZFile archive) throws Exception { SevenZArchiveEntry entry = archive.getNextEntry(); assertNotNull(entry); assertEquals("foo/", entry.getName()); assertTrue(entry.isDirectory()); } private void addFile(SevenZOutputFile archive, int index, boolean nonEmpty) throws Exception { SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setName("foo/" + index + ".txt"); archive.putArchiveEntry(entry); archive.write(nonEmpty ? new byte[] { 17 } : new byte[0]); archive.closeArchiveEntry(); } private Boolean verifyFile(SevenZFile archive, int index) throws Exception { SevenZArchiveEntry entry = archive.getNextEntry(); if (entry == null) { return null; } assertEquals("foo/" + index + ".txt", entry.getName()); assertEquals(false, entry.isDirectory()); if (entry.getSize() == 0) { return false; } assertEquals(1, entry.getSize()); assertEquals(17, archive.read()); assertEquals(-1, archive.read()); return true; } }
public void testExceptions() { final char[] DUMMY = new char[]{'a'}; // valid char array try { RandomStringUtils.random(-1); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, true, true); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(1, new char[0]); // must not provide empty array => IAE fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, ""); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, (String)null); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random()); fail(); } catch (IllegalArgumentException ex) {} }
org.apache.commons.lang3.RandomStringUtilsTest::testExceptions
src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
170
src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
testExceptions
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; /** * Unit tests {@link org.apache.commons.lang3.RandomStringUtils}. * * @version $Id$ */ public class RandomStringUtilsTest extends junit.framework.TestCase { /** * Construct a new instance of RandomStringUtilsTest with the specified name */ public RandomStringUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new RandomStringUtils()); Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(RandomStringUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(RandomStringUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Test the implementation */ public void testRandomStringUtils() { String r1 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r1.length()); String r2 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAscii(50); assertEquals("randomAscii(50) length", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("char between 32 and 127", r1.charAt(i) >= 32 && r1.charAt(i) <= 127); } r2 = RandomStringUtils.randomAscii(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphabetic(50); assertEquals("randomAlphabetic(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphabetic", true, Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphanumeric(50); assertEquals("randomAlphanumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphanumeric", true, Character.isLetterOrDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomNumeric(50); assertEquals("randomNumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains numeric", true, Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i))); } r2 = RandomStringUtils.randomNumeric(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); String set = "abcdefg"; r1 = RandomStringUtils.random(50, set); assertEquals("random(50, \"abcdefg\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); set = "stuvwxyz"; r1 = RandomStringUtils.random(50, set.toCharArray()); assertEquals("random(50, \"stuvwxyz\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); long seed = System.currentTimeMillis(); r1 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); r2 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); assertEquals("r1.equals(r2)", r1, r2); r1 = RandomStringUtils.random(0); assertEquals("random(0).equals(\"\")", "", r1); } public void testLANG805() { long seed = System.currentTimeMillis(); assertEquals("aaa", RandomStringUtils.random(3,0,0,false,false,new char[]{'a'},new Random(seed))); } public void testExceptions() { final char[] DUMMY = new char[]{'a'}; // valid char array try { RandomStringUtils.random(-1); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, true, true); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(1, new char[0]); // must not provide empty array => IAE fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, ""); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, (String)null); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random()); fail(); } catch (IllegalArgumentException ex) {} } /** * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7 */ public void testRandomAlphaNumeric() {} // Defects4J: flaky method // public void testRandomAlphaNumeric() { // char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'}; // boolean[] found = {false, false, false, false, false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAlphanumeric(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("alphanumeric character not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure '0' and '9' are generated by randomNumeric * This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46 */ public void testRandomNumeric() {} // Defects4J: flaky method // public void testRandomNumeric() { // char[] testChars = {'0','9'}; // boolean[] found = {false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomNumeric(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("digit not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure boundary alpha characters are generated by randomAlphabetic * This test will fail randomly with probability = 4 * (51/52)**1000 ~ 1.58E-8 */ public void testRandomAlphabetic() {} // Defects4J: flaky method // public void testRandomAlphabetic() { // char[] testChars = {'a', 'z', 'A', 'Z'}; // boolean[] found = {false, false, false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAlphabetic(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("alphanumeric character not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure 32 and 127 are generated by randomNumeric * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5 */ public void testRandomAscii() {} // Defects4J: flaky method // public void testRandomAscii() { // char[] testChars = {(char) 32, (char) 126}; // boolean[] found = {false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAscii(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("ascii character not generated in 1000 attempts: " // + (int) testChars[i] + // " -- repeated failures indicate a problem"); // } // } // } /** * Test homogeneity of random strings generated -- * i.e., test that characters show up with expected frequencies * in generated strings. Will fail randomly about 1 in 1000 times. * Repeated failures indicate a problem. */ public void testRandomStringUtilsHomog() {} // Defects4J: flaky method // public void testRandomStringUtilsHomog() { // String set = "abc"; // char[] chars = set.toCharArray(); // String gen = ""; // int[] counts = {0,0,0}; // int[] expected = {200,200,200}; // for (int i = 0; i< 100; i++) { // gen = RandomStringUtils.random(6,chars); // for (int j = 0; j < 6; j++) { // switch (gen.charAt(j)) { // case 'a': {counts[0]++; break;} // case 'b': {counts[1]++; break;} // case 'c': {counts[2]++; break;} // default: {fail("generated character not in set");} // } // } // } // // Perform chi-square test with df = 3-1 = 2, testing at .001 level // assertTrue("test homogeneity -- will fail about 1 in 1000 times", // chiSquare(expected,counts) < 13.82); // } /** * Computes Chi-Square statistic given observed and expected counts * @param observed array of observed frequency counts * @param expected array of expected frequency counts */ private double chiSquare(int[] expected, int[] observed) { double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { dev = observed[i] - expected[i]; sumSq += dev * dev / expected[i]; } return sumSq; } /** * Checks if the string got by {@link RandomStringUtils#random(int)} * can be converted to UTF-8 and back without loss. * * @see <a href="http://issues.apache.org/jira/browse/LANG-100">LANG-100</a> * * @throws Exception */ public void testLang100() throws Exception { int size = 5000; String encoding = "UTF-8"; String orig = RandomStringUtils.random(size); byte[] bytes = orig.getBytes(encoding); String copy = new String(bytes, encoding); // for a verbose compare: for (int i=0; i < orig.length() && i < copy.length(); i++) { char o = orig.charAt(i); char c = copy.charAt(i); assertEquals("differs at " + i + "(" + Integer.toHexString(new Character(o).hashCode()) + "," + Integer.toHexString(new Character(c).hashCode()) + ")", o, c); } // compare length also assertEquals(orig.length(), copy.length()); // just to be complete assertEquals(orig, copy); } }
// You are a professional Java test case writer, please create a test case named `testExceptions` for the issue `Lang-LANG-805`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-805 // // ## Issue-Title: // RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException // // ## Issue-Description: // // In commons-lang 2.6 line 250 : // // // // // ``` // ch = chars[random.nextInt(gap) + start]; // ``` // // // ~~This line of code takes a random int to fetch a char in the *chars* array regardless of its size.~~ // // ~~(Besides *start* is useless here)~~ // // // ~~Fixed version would be :~~ // // // // // ``` // //ch = chars[random.nextInt(gap)%chars.length]; // ``` // // // When user pass 0 as *end* or when the array is not null but empty this line ends up with an exception // // // // // public void testExceptions() {
170
12
132
src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-805 ## Issue-Title: RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException ## Issue-Description: In commons-lang 2.6 line 250 : ``` ch = chars[random.nextInt(gap) + start]; ``` ~~This line of code takes a random int to fetch a char in the *chars* array regardless of its size.~~ ~~(Besides *start* is useless here)~~ ~~Fixed version would be :~~ ``` //ch = chars[random.nextInt(gap)%chars.length]; ``` When user pass 0 as *end* or when the array is not null but empty this line ends up with an exception ``` You are a professional Java test case writer, please create a test case named `testExceptions` for the issue `Lang-LANG-805`, utilizing the provided issue report information and the following function signature. ```java public void testExceptions() { ```
132
[ "org.apache.commons.lang3.RandomStringUtils" ]
27495b08596937e1eeb3c272e56e2e273a10f2806ba33c0469796d8e8ef555b5
public void testExceptions()
// You are a professional Java test case writer, please create a test case named `testExceptions` for the issue `Lang-LANG-805`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-805 // // ## Issue-Title: // RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException // // ## Issue-Description: // // In commons-lang 2.6 line 250 : // // // // // ``` // ch = chars[random.nextInt(gap) + start]; // ``` // // // ~~This line of code takes a random int to fetch a char in the *chars* array regardless of its size.~~ // // ~~(Besides *start* is useless here)~~ // // // ~~Fixed version would be :~~ // // // // // ``` // //ch = chars[random.nextInt(gap)%chars.length]; // ``` // // // When user pass 0 as *end* or when the array is not null but empty this line ends up with an exception // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; /** * Unit tests {@link org.apache.commons.lang3.RandomStringUtils}. * * @version $Id$ */ public class RandomStringUtilsTest extends junit.framework.TestCase { /** * Construct a new instance of RandomStringUtilsTest with the specified name */ public RandomStringUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new RandomStringUtils()); Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(RandomStringUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(RandomStringUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Test the implementation */ public void testRandomStringUtils() { String r1 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r1.length()); String r2 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAscii(50); assertEquals("randomAscii(50) length", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("char between 32 and 127", r1.charAt(i) >= 32 && r1.charAt(i) <= 127); } r2 = RandomStringUtils.randomAscii(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphabetic(50); assertEquals("randomAlphabetic(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphabetic", true, Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphanumeric(50); assertEquals("randomAlphanumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphanumeric", true, Character.isLetterOrDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomNumeric(50); assertEquals("randomNumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains numeric", true, Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i))); } r2 = RandomStringUtils.randomNumeric(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); String set = "abcdefg"; r1 = RandomStringUtils.random(50, set); assertEquals("random(50, \"abcdefg\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); set = "stuvwxyz"; r1 = RandomStringUtils.random(50, set.toCharArray()); assertEquals("random(50, \"stuvwxyz\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); long seed = System.currentTimeMillis(); r1 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); r2 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); assertEquals("r1.equals(r2)", r1, r2); r1 = RandomStringUtils.random(0); assertEquals("random(0).equals(\"\")", "", r1); } public void testLANG805() { long seed = System.currentTimeMillis(); assertEquals("aaa", RandomStringUtils.random(3,0,0,false,false,new char[]{'a'},new Random(seed))); } public void testExceptions() { final char[] DUMMY = new char[]{'a'}; // valid char array try { RandomStringUtils.random(-1); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, true, true); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(1, new char[0]); // must not provide empty array => IAE fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, ""); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, (String)null); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random()); fail(); } catch (IllegalArgumentException ex) {} } /** * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7 */ public void testRandomAlphaNumeric() {} // Defects4J: flaky method // public void testRandomAlphaNumeric() { // char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'}; // boolean[] found = {false, false, false, false, false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAlphanumeric(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("alphanumeric character not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure '0' and '9' are generated by randomNumeric * This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46 */ public void testRandomNumeric() {} // Defects4J: flaky method // public void testRandomNumeric() { // char[] testChars = {'0','9'}; // boolean[] found = {false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomNumeric(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("digit not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure boundary alpha characters are generated by randomAlphabetic * This test will fail randomly with probability = 4 * (51/52)**1000 ~ 1.58E-8 */ public void testRandomAlphabetic() {} // Defects4J: flaky method // public void testRandomAlphabetic() { // char[] testChars = {'a', 'z', 'A', 'Z'}; // boolean[] found = {false, false, false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAlphabetic(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("alphanumeric character not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure 32 and 127 are generated by randomNumeric * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5 */ public void testRandomAscii() {} // Defects4J: flaky method // public void testRandomAscii() { // char[] testChars = {(char) 32, (char) 126}; // boolean[] found = {false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAscii(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("ascii character not generated in 1000 attempts: " // + (int) testChars[i] + // " -- repeated failures indicate a problem"); // } // } // } /** * Test homogeneity of random strings generated -- * i.e., test that characters show up with expected frequencies * in generated strings. Will fail randomly about 1 in 1000 times. * Repeated failures indicate a problem. */ public void testRandomStringUtilsHomog() {} // Defects4J: flaky method // public void testRandomStringUtilsHomog() { // String set = "abc"; // char[] chars = set.toCharArray(); // String gen = ""; // int[] counts = {0,0,0}; // int[] expected = {200,200,200}; // for (int i = 0; i< 100; i++) { // gen = RandomStringUtils.random(6,chars); // for (int j = 0; j < 6; j++) { // switch (gen.charAt(j)) { // case 'a': {counts[0]++; break;} // case 'b': {counts[1]++; break;} // case 'c': {counts[2]++; break;} // default: {fail("generated character not in set");} // } // } // } // // Perform chi-square test with df = 3-1 = 2, testing at .001 level // assertTrue("test homogeneity -- will fail about 1 in 1000 times", // chiSquare(expected,counts) < 13.82); // } /** * Computes Chi-Square statistic given observed and expected counts * @param observed array of observed frequency counts * @param expected array of expected frequency counts */ private double chiSquare(int[] expected, int[] observed) { double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { dev = observed[i] - expected[i]; sumSq += dev * dev / expected[i]; } return sumSq; } /** * Checks if the string got by {@link RandomStringUtils#random(int)} * can be converted to UTF-8 and back without loss. * * @see <a href="http://issues.apache.org/jira/browse/LANG-100">LANG-100</a> * * @throws Exception */ public void testLang100() throws Exception { int size = 5000; String encoding = "UTF-8"; String orig = RandomStringUtils.random(size); byte[] bytes = orig.getBytes(encoding); String copy = new String(bytes, encoding); // for a verbose compare: for (int i=0; i < orig.length() && i < copy.length(); i++) { char o = orig.charAt(i); char c = copy.charAt(i); assertEquals("differs at " + i + "(" + Integer.toHexString(new Character(o).hashCode()) + "," + Integer.toHexString(new Character(c).hashCode()) + ")", o, c); } // compare length also assertEquals(orig.length(), copy.length()); // just to be complete assertEquals(orig, copy); } }
public void testLang538() { final String dateTime = "2009-10-16T16:42:16.000Z"; // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", dateTime, format.format(cal)); }
org.apache.commons.lang3.time.FastDateFormatTest::testLang538
src/test/org/apache/commons/lang3/time/FastDateFormatTest.java
349
src/test/org/apache/commons/lang3/time/FastDateFormatTest.java
testLang538
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.lang3.SerializationUtils; /** * Unit tests {@link org.apache.commons.lang3.time.FastDateFormat}. * * @author Sean Schofield * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @author Fredrik Westermarck * @since 2.0 * @version $Id$ */ public class FastDateFormatTest extends TestCase { public FastDateFormatTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(FastDateFormatTest.class); suite.setName("FastDateFormat Tests"); return suite; } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void test_getInstance() { FastDateFormat format1 = FastDateFormat.getInstance(); FastDateFormat format2 = FastDateFormat.getInstance(); assertSame(format1, format2); assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern()); } public void test_getInstance_String() { FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format2, format3); assertEquals("MM/DD/yyyy", format1.getPattern()); assertEquals(TimeZone.getDefault(), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); } public void test_getInstance_String_TimeZone() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik")); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault()); FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertSame(format3, format4); assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5); assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void test_getInstance_String_Locale() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format1, format3); assertSame(Locale.GERMANY, format1.getLocale()); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateTimeInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_getInstance_String_TimeZone_Locale() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault(), Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format3.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertEquals(true, format3.getTimeZoneOverridesCalendar()); assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format2.getLocale()); assertEquals(Locale.GERMANY, format3.getLocale()); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void testFormat() {} // Defects4J: flaky method // public void testFormat() { // Locale realDefaultLocale = Locale.getDefault(); // TimeZone realDefaultZone = TimeZone.getDefault(); // try { // Locale.setDefault(Locale.US); // TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); // FastDateFormat fdf = null; // SimpleDateFormat sdf = null; // // GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); // GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); // Date date1 = cal1.getTime(); // Date date2 = cal2.getTime(); // long millis1 = date1.getTime(); // long millis2 = date2.getTime(); // // fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); // sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // assertEquals(sdf.format(date1), fdf.format(date1)); // assertEquals("2003-01-10T15:33:20", fdf.format(date1)); // assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); // assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); // assertEquals("2003-07-10T09:00:00", fdf.format(date2)); // assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); // assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); // // fdf = FastDateFormat.getInstance("Z"); // assertEquals("-0500", fdf.format(date1)); // assertEquals("-0500", fdf.format(cal1)); // assertEquals("-0500", fdf.format(millis1)); // // fdf = FastDateFormat.getInstance("Z"); // assertEquals("-0400", fdf.format(date2)); // assertEquals("-0400", fdf.format(cal2)); // assertEquals("-0400", fdf.format(millis2)); // // fdf = FastDateFormat.getInstance("ZZ"); // assertEquals("-05:00", fdf.format(date1)); // assertEquals("-05:00", fdf.format(cal1)); // assertEquals("-05:00", fdf.format(millis1)); // // fdf = FastDateFormat.getInstance("ZZ"); // assertEquals("-04:00", fdf.format(date2)); // assertEquals("-04:00", fdf.format(cal2)); // assertEquals("-04:00", fdf.format(millis2)); // // String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + // " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; // fdf = FastDateFormat.getInstance(pattern); // sdf = new SimpleDateFormat(pattern); // assertEquals(sdf.format(date1), fdf.format(date1)); // assertEquals(sdf.format(date2), fdf.format(date2)); // // } finally { // Locale.setDefault(realDefaultLocale); // TimeZone.setDefault(realDefaultZone); // } // } /** * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}. */ public void testShortDateStyleWithLocales() { Locale usLocale = Locale.US; Locale swedishLocale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2004, 1, 3); FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale); assertEquals("2/3/04", fdf.format(cal)); fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale); assertEquals("2004-02-03", fdf.format(cal)); } /** * Tests that pre-1000AD years get padded with yyyy */ public void testLowYearPadding() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD"); cal.set(1,0,1); assertEquals("0001/01/01", format.format(cal)); cal.set(10,0,1); assertEquals("0010/01/01", format.format(cal)); cal.set(100,0,1); assertEquals("0100/01/01", format.format(cal)); cal.set(999,0,1); assertEquals("0999/01/01", format.format(cal)); } /** * Show Bug #39410 is solved */ public void testMilleniumBug() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy"); cal.set(1000,0,1); assertEquals("01.01.1000", format.format(cal)); } /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ // TODO: Fix this problem public void testSimpleDate() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); } public void testLang303() { Calendar cal = Calendar.getInstance(); cal.set(2004,11,31); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); String output = format.format(cal); format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) ); assertEquals(output, format.format(cal)); } public void testLang538() { final String dateTime = "2009-10-16T16:42:16.000Z"; // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", dateTime, format.format(cal)); } }
// You are a professional Java test case writer, please create a test case named `testLang538` for the issue `Lang-LANG-538`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-538 // // ## Issue-Title: // DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations // // ## Issue-Description: // // If a Calendar object is constructed in certain ways a call to Calendar.setTimeZone does not correctly change the Calendars fields. Calling Calenar.getTime() seems to fix this problem. While this is probably a bug in the JDK, it would be nice if DateFormatUtils was smart enough to detect/resolve this problem. // // // For example, the following unit test fails: // // // // // ``` // public void testFormat_CalendarIsoMsZulu() { // final String dateTime = "2009-10-16T16:42:16.000Z"; // // // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone // GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); // cal.clear(); // cal.set(2009, 9, 16, 8, 42, 16); // // // FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); // assertEquals("dateTime", dateTime, format.format(cal)); // } // // ``` // // // However, this unit test passes: // // // // // ``` // public void testFormat_CalendarIsoMsZulu() { // final String dateTime = "2009-10-16T16:42:16.000Z"; // GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); // cal.clear(); // cal.set(2009, 9, 16, 8, 42, 16); // cal.getTime(); // // FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); // assertEquals("dateTime", dateTime, format.format(cal)); // } // // ``` // // // // // public void testLang538() {
349
38
338
src/test/org/apache/commons/lang3/time/FastDateFormatTest.java
src/test
```markdown ## Issue-ID: Lang-LANG-538 ## Issue-Title: DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations ## Issue-Description: If a Calendar object is constructed in certain ways a call to Calendar.setTimeZone does not correctly change the Calendars fields. Calling Calenar.getTime() seems to fix this problem. While this is probably a bug in the JDK, it would be nice if DateFormatUtils was smart enough to detect/resolve this problem. For example, the following unit test fails: ``` public void testFormat_CalendarIsoMsZulu() { final String dateTime = "2009-10-16T16:42:16.000Z"; // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", dateTime, format.format(cal)); } ``` However, this unit test passes: ``` public void testFormat_CalendarIsoMsZulu() { final String dateTime = "2009-10-16T16:42:16.000Z"; GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); cal.getTime(); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", dateTime, format.format(cal)); } ``` ``` You are a professional Java test case writer, please create a test case named `testLang538` for the issue `Lang-LANG-538`, utilizing the provided issue report information and the following function signature. ```java public void testLang538() { ```
338
[ "org.apache.commons.lang3.time.FastDateFormat" ]
27b70638cd9688fa24588d5bdfe52c136c8025fe13381321ceda294042517d12
public void testLang538()
// You are a professional Java test case writer, please create a test case named `testLang538` for the issue `Lang-LANG-538`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-538 // // ## Issue-Title: // DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations // // ## Issue-Description: // // If a Calendar object is constructed in certain ways a call to Calendar.setTimeZone does not correctly change the Calendars fields. Calling Calenar.getTime() seems to fix this problem. While this is probably a bug in the JDK, it would be nice if DateFormatUtils was smart enough to detect/resolve this problem. // // // For example, the following unit test fails: // // // // // ``` // public void testFormat_CalendarIsoMsZulu() { // final String dateTime = "2009-10-16T16:42:16.000Z"; // // // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone // GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); // cal.clear(); // cal.set(2009, 9, 16, 8, 42, 16); // // // FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); // assertEquals("dateTime", dateTime, format.format(cal)); // } // // ``` // // // However, this unit test passes: // // // // // ``` // public void testFormat_CalendarIsoMsZulu() { // final String dateTime = "2009-10-16T16:42:16.000Z"; // GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); // cal.clear(); // cal.set(2009, 9, 16, 8, 42, 16); // cal.getTime(); // // FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); // assertEquals("dateTime", dateTime, format.format(cal)); // } // // ``` // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.lang3.SerializationUtils; /** * Unit tests {@link org.apache.commons.lang3.time.FastDateFormat}. * * @author Sean Schofield * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @author Fredrik Westermarck * @since 2.0 * @version $Id$ */ public class FastDateFormatTest extends TestCase { public FastDateFormatTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(FastDateFormatTest.class); suite.setName("FastDateFormat Tests"); return suite; } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void test_getInstance() { FastDateFormat format1 = FastDateFormat.getInstance(); FastDateFormat format2 = FastDateFormat.getInstance(); assertSame(format1, format2); assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern()); } public void test_getInstance_String() { FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format2, format3); assertEquals("MM/DD/yyyy", format1.getPattern()); assertEquals(TimeZone.getDefault(), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); } public void test_getInstance_String_TimeZone() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik")); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault()); FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertSame(format3, format4); assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5); assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void test_getInstance_String_Locale() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format1, format3); assertSame(Locale.GERMANY, format1.getLocale()); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateTimeInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_getInstance_String_TimeZone_Locale() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault(), Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format3.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertEquals(true, format3.getTimeZoneOverridesCalendar()); assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format2.getLocale()); assertEquals(Locale.GERMANY, format3.getLocale()); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void testFormat() {} // Defects4J: flaky method // public void testFormat() { // Locale realDefaultLocale = Locale.getDefault(); // TimeZone realDefaultZone = TimeZone.getDefault(); // try { // Locale.setDefault(Locale.US); // TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); // FastDateFormat fdf = null; // SimpleDateFormat sdf = null; // // GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); // GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); // Date date1 = cal1.getTime(); // Date date2 = cal2.getTime(); // long millis1 = date1.getTime(); // long millis2 = date2.getTime(); // // fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); // sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // assertEquals(sdf.format(date1), fdf.format(date1)); // assertEquals("2003-01-10T15:33:20", fdf.format(date1)); // assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); // assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); // assertEquals("2003-07-10T09:00:00", fdf.format(date2)); // assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); // assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); // // fdf = FastDateFormat.getInstance("Z"); // assertEquals("-0500", fdf.format(date1)); // assertEquals("-0500", fdf.format(cal1)); // assertEquals("-0500", fdf.format(millis1)); // // fdf = FastDateFormat.getInstance("Z"); // assertEquals("-0400", fdf.format(date2)); // assertEquals("-0400", fdf.format(cal2)); // assertEquals("-0400", fdf.format(millis2)); // // fdf = FastDateFormat.getInstance("ZZ"); // assertEquals("-05:00", fdf.format(date1)); // assertEquals("-05:00", fdf.format(cal1)); // assertEquals("-05:00", fdf.format(millis1)); // // fdf = FastDateFormat.getInstance("ZZ"); // assertEquals("-04:00", fdf.format(date2)); // assertEquals("-04:00", fdf.format(cal2)); // assertEquals("-04:00", fdf.format(millis2)); // // String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + // " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; // fdf = FastDateFormat.getInstance(pattern); // sdf = new SimpleDateFormat(pattern); // assertEquals(sdf.format(date1), fdf.format(date1)); // assertEquals(sdf.format(date2), fdf.format(date2)); // // } finally { // Locale.setDefault(realDefaultLocale); // TimeZone.setDefault(realDefaultZone); // } // } /** * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}. */ public void testShortDateStyleWithLocales() { Locale usLocale = Locale.US; Locale swedishLocale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2004, 1, 3); FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale); assertEquals("2/3/04", fdf.format(cal)); fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale); assertEquals("2004-02-03", fdf.format(cal)); } /** * Tests that pre-1000AD years get padded with yyyy */ public void testLowYearPadding() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD"); cal.set(1,0,1); assertEquals("0001/01/01", format.format(cal)); cal.set(10,0,1); assertEquals("0010/01/01", format.format(cal)); cal.set(100,0,1); assertEquals("0100/01/01", format.format(cal)); cal.set(999,0,1); assertEquals("0999/01/01", format.format(cal)); } /** * Show Bug #39410 is solved */ public void testMilleniumBug() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy"); cal.set(1000,0,1); assertEquals("01.01.1000", format.format(cal)); } /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ // TODO: Fix this problem public void testSimpleDate() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); } public void testLang303() { Calendar cal = Calendar.getInstance(); cal.set(2004,11,31); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); String output = format.format(cal); format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) ); assertEquals(output, format.format(cal)); } public void testLang538() { final String dateTime = "2009-10-16T16:42:16.000Z"; // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", dateTime, format.format(cal)); } }
public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); }
com.google.javascript.jscomp.TypeCheckTest::testIssue688
test/com/google/javascript/jscomp/TypeCheckTest.java
5,921
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue688
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2);" + "}", "Property name2 never defined on rec"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testGenerics1() throws Exception { String FN_DECL = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( FN_DECL + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void disable_testBackwardsInferenceGoogArrayFilter1() throws Exception { // TODO(johnlenz): this doesn't fail because any Array is regarded as // a subtype of any other array regardless of the type parameter. testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testIssue688` for the issue `Closure-688`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-688 // // ## Issue-Title: // @const dumps type cast information // // ## Issue-Description: // The following code compiles fine: // // /\*\* // \* Class defining an interface with two numbers. // \* @interface // \*/ // function TwoNumbers() {} // // /\*\* @type number \*/ // TwoNumbers.prototype.first; // // /\*\* @type number \*/ // TwoNumbers.prototype.second; // // var SOME\_DEFAULT = // /\*\* @type {TwoNumbers} \*/ ({first: 1, second: 2}); // // /\*\* // \* Class with a two number member. // \* @constructor // \*/ // function HasTwoNumbers() { // /\*\* @type {TwoNumbers} \*/ // this.twoNumbers = this.getTwoNumbers(); // } // // /\*\* // \* Get the default two numbers. // \* @return {TwoNumbers} // \*/ // HasTwoNumbers.prototype.getTwoNumbers = function() { // return SOME\_DEFAULT; // }; // // Now realizing that SOME\_DEFAULTS is actually a preset constant which should not change I would like to say for that line (just adding an @const) // // /\*\* @const \*/ var SOME\_DEFAULT = // /\*\* @type {TwoNumbers} \*/ ({first: 1, second: 2}); // // However that starts throwing warnings as adding the @const makes the compiler dump the type. (Does the value get inlined without the typecast?) // // Expected: // Compiles fine. // // Error can be reproduced on: // http://closure-compiler.appspot.com/home // copy-past the attached file in there, it throws a warning and does not compile. // // public void testIssue688() throws Exception {
5,921
17
5,904
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-688 ## Issue-Title: @const dumps type cast information ## Issue-Description: The following code compiles fine: /\*\* \* Class defining an interface with two numbers. \* @interface \*/ function TwoNumbers() {} /\*\* @type number \*/ TwoNumbers.prototype.first; /\*\* @type number \*/ TwoNumbers.prototype.second; var SOME\_DEFAULT = /\*\* @type {TwoNumbers} \*/ ({first: 1, second: 2}); /\*\* \* Class with a two number member. \* @constructor \*/ function HasTwoNumbers() { /\*\* @type {TwoNumbers} \*/ this.twoNumbers = this.getTwoNumbers(); } /\*\* \* Get the default two numbers. \* @return {TwoNumbers} \*/ HasTwoNumbers.prototype.getTwoNumbers = function() { return SOME\_DEFAULT; }; Now realizing that SOME\_DEFAULTS is actually a preset constant which should not change I would like to say for that line (just adding an @const) /\*\* @const \*/ var SOME\_DEFAULT = /\*\* @type {TwoNumbers} \*/ ({first: 1, second: 2}); However that starts throwing warnings as adding the @const makes the compiler dump the type. (Does the value get inlined without the typecast?) Expected: Compiles fine. Error can be reproduced on: http://closure-compiler.appspot.com/home copy-past the attached file in there, it throws a warning and does not compile. ``` You are a professional Java test case writer, please create a test case named `testIssue688` for the issue `Closure-688`, utilizing the provided issue report information and the following function signature. ```java public void testIssue688() throws Exception { ```
5,904
[ "com.google.javascript.jscomp.TypedScopeCreator" ]
28136ab5f0788dad90d13c40547f7f0cb8f8ba4698f9c433f4fbf81df351da8f
public void testIssue688() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue688` for the issue `Closure-688`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-688 // // ## Issue-Title: // @const dumps type cast information // // ## Issue-Description: // The following code compiles fine: // // /\*\* // \* Class defining an interface with two numbers. // \* @interface // \*/ // function TwoNumbers() {} // // /\*\* @type number \*/ // TwoNumbers.prototype.first; // // /\*\* @type number \*/ // TwoNumbers.prototype.second; // // var SOME\_DEFAULT = // /\*\* @type {TwoNumbers} \*/ ({first: 1, second: 2}); // // /\*\* // \* Class with a two number member. // \* @constructor // \*/ // function HasTwoNumbers() { // /\*\* @type {TwoNumbers} \*/ // this.twoNumbers = this.getTwoNumbers(); // } // // /\*\* // \* Get the default two numbers. // \* @return {TwoNumbers} // \*/ // HasTwoNumbers.prototype.getTwoNumbers = function() { // return SOME\_DEFAULT; // }; // // Now realizing that SOME\_DEFAULTS is actually a preset constant which should not change I would like to say for that line (just adding an @const) // // /\*\* @const \*/ var SOME\_DEFAULT = // /\*\* @type {TwoNumbers} \*/ ({first: 1, second: 2}); // // However that starts throwing warnings as adding the @const makes the compiler dump the type. (Does the value get inlined without the typecast?) // // Expected: // Compiles fine. // // Error can be reproduced on: // http://closure-compiler.appspot.com/home // copy-past the attached file in there, it throws a warning and does not compile. // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testParameterizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2);" + "}", "Property name2 never defined on rec"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of Object\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : Object\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testGenerics1() throws Exception { String FN_DECL = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( FN_DECL + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void disable_testBackwardsInferenceGoogArrayFilter1() throws Exception { // TODO(johnlenz): this doesn't fail because any Array is regarded as // a subtype of any other array regardless of the type parameter. testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
@SuppressWarnings("resource") public void testTokensSingleMatchWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); assertFalse(p.hasCurrentToken()); assertNull(p.getCurrentToken()); assertEquals(JsonTokenId.ID_NO_TOKEN, p.getCurrentTokenId()); assertFalse(p.isExpectedStartObjectToken()); assertFalse(p.isExpectedStartArrayToken()); // {'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true} // String result = readAndWrite(JSON_F, p); // assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertEquals(JsonToken.START_OBJECT, p.getCurrentToken()); assertTrue(p.isExpectedStartObjectToken()); assertFalse(p.isExpectedStartArrayToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(JsonToken.FIELD_NAME, p.getCurrentToken()); assertEquals("ob", p.getCurrentName()); // assertEquals("ob", p.getText()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertEquals("ob", p.getCurrentName()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("value", p.getCurrentName()); assertEquals("value", p.getText()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(JsonToken.VALUE_NUMBER_INT, p.getCurrentToken()); assertEquals(NumberType.INT, p.getNumberType()); assertEquals(3, p.getIntValue()); assertEquals("value", p.getCurrentName()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertEquals(JsonToken.END_OBJECT, p.getCurrentToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertEquals(JsonToken.END_OBJECT, p.getCurrentToken()); p.clearCurrentToken(); assertNull(p.getCurrentToken()); p.close(); }
com.fasterxml.jackson.core.filter.TokenVerifyingParserFiltering330Test::testTokensSingleMatchWithPath
src/test/java/com/fasterxml/jackson/core/filter/TokenVerifyingParserFiltering330Test.java
117
src/test/java/com/fasterxml/jackson/core/filter/TokenVerifyingParserFiltering330Test.java
testTokensSingleMatchWithPath
package com.fasterxml.jackson.core.filter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.filter.FilteringParserDelegate; import com.fasterxml.jackson.core.filter.TokenFilter; // Tests for [core#330] public class TokenVerifyingParserFiltering330Test extends BaseTest { static class NameMatchFilter extends TokenFilter { private final Set<String> _names; public NameMatchFilter(String... names) { _names = new HashSet<String>(Arrays.asList(names)); } @Override public TokenFilter includeElement(int index) { return this; } @Override public TokenFilter includeProperty(String name) { if (_names.contains(name)) { return TokenFilter.INCLUDE_ALL; } return this; } @Override protected boolean _includeScalar() { return false; } } /* /********************************************************** /* Test methods /********************************************************** */ private final JsonFactory JSON_F = new JsonFactory(); private final String SIMPLE = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}"); @SuppressWarnings("resource") public void testBasicSingleMatchFilteringWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); // {'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true} String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); } @SuppressWarnings("resource") public void testTokensSingleMatchWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); assertFalse(p.hasCurrentToken()); assertNull(p.getCurrentToken()); assertEquals(JsonTokenId.ID_NO_TOKEN, p.getCurrentTokenId()); assertFalse(p.isExpectedStartObjectToken()); assertFalse(p.isExpectedStartArrayToken()); // {'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true} // String result = readAndWrite(JSON_F, p); // assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertEquals(JsonToken.START_OBJECT, p.getCurrentToken()); assertTrue(p.isExpectedStartObjectToken()); assertFalse(p.isExpectedStartArrayToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(JsonToken.FIELD_NAME, p.getCurrentToken()); assertEquals("ob", p.getCurrentName()); // assertEquals("ob", p.getText()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertEquals("ob", p.getCurrentName()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("value", p.getCurrentName()); assertEquals("value", p.getText()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(JsonToken.VALUE_NUMBER_INT, p.getCurrentToken()); assertEquals(NumberType.INT, p.getNumberType()); assertEquals(3, p.getIntValue()); assertEquals("value", p.getCurrentName()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertEquals(JsonToken.END_OBJECT, p.getCurrentToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertEquals(JsonToken.END_OBJECT, p.getCurrentToken()); p.clearCurrentToken(); assertNull(p.getCurrentToken()); p.close(); } @SuppressWarnings("resource") public void testSkippingForSingleWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); // assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); assertToken(JsonToken.START_OBJECT, p.nextToken()); p.skipChildren(); assertEquals(JsonToken.END_OBJECT, p.getCurrentToken()); assertNull(p.nextToken()); } }
// You are a professional Java test case writer, please create a test case named `testTokensSingleMatchWithPath` for the issue `JacksonCore-330`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-330 // // ## Issue-Title: // FilteringParserDelegate seems to miss last closing END_OBJECT // // ## Issue-Description: // (note: adding a failing test for this case) // // // Looks like with settings like: // // // // ``` // JsonParser p = new FilteringParserDelegate(p0, // new NameMatchFilter("value"), // true, // includePath // false // multipleMatches // ); // ``` // // and input // // // // ``` // { // "a":123, // "array":[1,2], // "ob": { // "value0":2, // "value":3, // "value2":4 // }, // "b":true // } // ``` // // output will be like: // // // // ``` // {"ob":{"value":3} // ``` // // (note the missing trailing `}` for closing `END_OBJECT`) // // // // @SuppressWarnings("resource") public void testTokensSingleMatchWithPath() throws Exception {
117
21
64
src/test/java/com/fasterxml/jackson/core/filter/TokenVerifyingParserFiltering330Test.java
src/test/java
```markdown ## Issue-ID: JacksonCore-330 ## Issue-Title: FilteringParserDelegate seems to miss last closing END_OBJECT ## Issue-Description: (note: adding a failing test for this case) Looks like with settings like: ``` JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); ``` and input ``` { "a":123, "array":[1,2], "ob": { "value0":2, "value":3, "value2":4 }, "b":true } ``` output will be like: ``` {"ob":{"value":3} ``` (note the missing trailing `}` for closing `END_OBJECT`) ``` You are a professional Java test case writer, please create a test case named `testTokensSingleMatchWithPath` for the issue `JacksonCore-330`, utilizing the provided issue report information and the following function signature. ```java @SuppressWarnings("resource") public void testTokensSingleMatchWithPath() throws Exception { ```
64
[ "com.fasterxml.jackson.core.filter.FilteringParserDelegate" ]
28b79e0076fe1770f142c14476b41d8a293693d11fc512d08a46c4ae66f117d7
@SuppressWarnings("resource") public void testTokensSingleMatchWithPath() throws Exception
// You are a professional Java test case writer, please create a test case named `testTokensSingleMatchWithPath` for the issue `JacksonCore-330`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-330 // // ## Issue-Title: // FilteringParserDelegate seems to miss last closing END_OBJECT // // ## Issue-Description: // (note: adding a failing test for this case) // // // Looks like with settings like: // // // // ``` // JsonParser p = new FilteringParserDelegate(p0, // new NameMatchFilter("value"), // true, // includePath // false // multipleMatches // ); // ``` // // and input // // // // ``` // { // "a":123, // "array":[1,2], // "ob": { // "value0":2, // "value":3, // "value2":4 // }, // "b":true // } // ``` // // output will be like: // // // // ``` // {"ob":{"value":3} // ``` // // (note the missing trailing `}` for closing `END_OBJECT`) // // // //
JacksonCore
package com.fasterxml.jackson.core.filter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.filter.FilteringParserDelegate; import com.fasterxml.jackson.core.filter.TokenFilter; // Tests for [core#330] public class TokenVerifyingParserFiltering330Test extends BaseTest { static class NameMatchFilter extends TokenFilter { private final Set<String> _names; public NameMatchFilter(String... names) { _names = new HashSet<String>(Arrays.asList(names)); } @Override public TokenFilter includeElement(int index) { return this; } @Override public TokenFilter includeProperty(String name) { if (_names.contains(name)) { return TokenFilter.INCLUDE_ALL; } return this; } @Override protected boolean _includeScalar() { return false; } } /* /********************************************************** /* Test methods /********************************************************** */ private final JsonFactory JSON_F = new JsonFactory(); private final String SIMPLE = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}"); @SuppressWarnings("resource") public void testBasicSingleMatchFilteringWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); // {'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true} String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); } @SuppressWarnings("resource") public void testTokensSingleMatchWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); assertFalse(p.hasCurrentToken()); assertNull(p.getCurrentToken()); assertEquals(JsonTokenId.ID_NO_TOKEN, p.getCurrentTokenId()); assertFalse(p.isExpectedStartObjectToken()); assertFalse(p.isExpectedStartArrayToken()); // {'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true} // String result = readAndWrite(JSON_F, p); // assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertEquals(JsonToken.START_OBJECT, p.getCurrentToken()); assertTrue(p.isExpectedStartObjectToken()); assertFalse(p.isExpectedStartArrayToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(JsonToken.FIELD_NAME, p.getCurrentToken()); assertEquals("ob", p.getCurrentName()); // assertEquals("ob", p.getText()); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertEquals("ob", p.getCurrentName()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("value", p.getCurrentName()); assertEquals("value", p.getText()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertEquals(JsonToken.VALUE_NUMBER_INT, p.getCurrentToken()); assertEquals(NumberType.INT, p.getNumberType()); assertEquals(3, p.getIntValue()); assertEquals("value", p.getCurrentName()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertEquals(JsonToken.END_OBJECT, p.getCurrentToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertEquals(JsonToken.END_OBJECT, p.getCurrentToken()); p.clearCurrentToken(); assertNull(p.getCurrentToken()); p.close(); } @SuppressWarnings("resource") public void testSkippingForSingleWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); // assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); assertToken(JsonToken.START_OBJECT, p.nextToken()); p.skipChildren(); assertEquals(JsonToken.END_OBJECT, p.getCurrentToken()); assertNull(p.nextToken()); } }
@Test public void testMath288() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(10.0, solution.getValue(), .0000001); }
org.apache.commons.math.optimization.linear.SimplexSolverTest::testMath288
src/test/java/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
73
src/test/java/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
testMath288
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.optimization.linear; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.linear.ArrayRealVector; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.OptimizationException; import org.apache.commons.math.optimization.RealPointValuePair; import org.junit.Test; public class SimplexSolverTest { @Test public void testMath272() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(0.0, solution.getPoint()[0], .0000001); assertEquals(1.0, solution.getPoint()[1], .0000001); assertEquals(1.0, solution.getPoint()[2], .0000001); assertEquals(3.0, solution.getValue(), .0000001); } @Test public void testMath286() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.2, 0.3 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 23.0)); RealPointValuePair solution = new SimplexSolver().optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(6.9, solution.getValue(), .0000001); } @Test public void testMath288() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(10.0, solution.getValue(), .0000001); } @Test public void testSimplexSolver() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 7); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(57.0, solution.getValue(), 0.0); } @Test public void testSingleVariableAndConstraint() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(10.0, solution.getPoint()[0], 0.0); assertEquals(30.0, solution.getValue(), 0.0); } /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(50.0, solution.getValue(), 0.0); } @Test public void testMinimization() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false); assertEquals(4.0, solution.getPoint()[0], 0.0); assertEquals(0.0, solution.getPoint()[1], 0.0); assertEquals(-13.0, solution.getValue(), 0.0); } @Test public void testSolutionWithNegativeDecisionVariable() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(-2.0, solution.getPoint()[0], 0.0); assertEquals(8.0, solution.getPoint()[1], 0.0); assertEquals(12.0, solution.getValue(), 0.0); } @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test public void testRestrictVariablesToNonNegative() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); assertEquals(480.419243986254, solution.getPoint()[1], .0000001); assertEquals(0.0, solution.getPoint()[2], .0000001); assertEquals(0.0, solution.getPoint()[3], .0000001); assertEquals(0.0, solution.getPoint()[4], .0000001); assertEquals(1438556.7491409, solution.getValue(), .0000001); } @Test public void testEpsilon() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(1.0, solution.getPoint()[0], 0.0); assertEquals(1.0, solution.getPoint()[1], 0.0); assertEquals(0.0, solution.getPoint()[2], 0.0); assertEquals(15.0, solution.getValue(), 0.0); } @Test public void testTrivialModel() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(0, solution.getValue(), .0000001); } @Test public void testLargeModel() throws OptimizationException { double[] objective = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(7518.0, solution.getValue(), .0000001); } /** * Converts a test string to a {@link LinearConstraint}. * Ex: x0 + x1 + x2 + x3 - x12 = 0 */ private LinearConstraint equationFromString(int numCoefficients, String s) { Relationship relationship; if (s.contains(">=")) { relationship = Relationship.GEQ; } else if (s.contains("<=")) { relationship = Relationship.LEQ; } else if (s.contains("=")) { relationship = Relationship.EQ; } else { throw new IllegalArgumentException(); } String[] equationParts = s.split("[>|<]?="); double rhs = Double.parseDouble(equationParts[1].trim()); RealVector lhs = new ArrayRealVector(numCoefficients); String left = equationParts[0].replaceAll(" ?x", ""); String[] coefficients = left.split(" "); for (String coefficient : coefficients) { double value = coefficient.charAt(0) == '-' ? -1 : 1; int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim()); lhs.setEntry(index, value); } return new LinearConstraint(lhs, relationship, rhs); } }
// You are a professional Java test case writer, please create a test case named `testMath288` for the issue `Math-MATH-288`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-288 // // ## Issue-Title: // SimplexSolver not working as expected 2 // // ## Issue-Description: // // SimplexSolver didn't find the optimal solution. // // // Program for Lpsolve: // // ===================== // // /\* Objective function \*/ // // max: 7 a 3 b; // // // /\* Constraints \*/ // // R1: +3 a -5 c <= 0; // // R2: +2 a -5 d <= 0; // // R3: +2 b -5 c <= 0; // // R4: +3 b -5 d <= 0; // // R5: +3 a +2 b <= 5; // // R6: +2 a +3 b <= 5; // // // /\* Variable bounds \*/ // // a <= 1; // // b <= 1; // // ===================== // // Results(correct): a = 1, b = 1, value = 10 // // // Program for SimplexSolve: // // ===================== // // LinearObjectiveFunction kritFcia = new LinearObjectiveFunction(new double[] // // // {7, 3, 0, 0} // , 0); // // Collection<LinearConstraint> podmienky = new ArrayList<LinearConstraint>(); // // podmienky.add(new LinearConstraint(new double[] // // // {1, 0, 0, 0} // , Relationship.LEQ, 1)); // // podmienky.add(new LinearConstraint(new double[] // // // {0, 1, 0, 0} // , Relationship.LEQ, 1)); // // podmienky.add(new LinearConstraint(new double[] // // // {3, 0, -5, 0} // , Relationship.LEQ, 0)); // // podmienky.add(new LinearConstraint(new double[] // // // {2, 0, 0, -5} // , Relationship.LEQ, 0)); // // podmienky.add(new LinearConstraint(new double[] // // // {0, 2, -5, 0} // , Relationship.LEQ, 0)); // // podmienky.add(new LinearConstraint(new double[] // // // {0, 3, 0, -5} // , Relationship.LEQ, 0)); // // podmienky.add(new LinearConstraint(new double[] // // // {3, 2, 0, 0} // , Relationship.LEQ, 5)); // // podmienky.add(new LinearConstraint(new double[] // // // {2, 3, 0, 0} // , Relationship.LEQ, 5)); // // SimplexSolver solver = new SimplexSolver(); // // RealPointValuePair result = solver.optimize(kritFcia, podmienky, GoalType.MAXIMIZE, true); // // ===================== // // Results(incorrect): a = 1, b = 0.5, value = 8.5 // // // P.S. I used the latest software from the repository (including [~~MATH-286~~](https://issues.apache.org/jira/browse/MATH-286 "SimplexSolver not working as expected?") fix). // // // // // @Test public void testMath288() throws OptimizationException {
73
82
60
src/test/java/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-288 ## Issue-Title: SimplexSolver not working as expected 2 ## Issue-Description: SimplexSolver didn't find the optimal solution. Program for Lpsolve: ===================== /\* Objective function \*/ max: 7 a 3 b; /\* Constraints \*/ R1: +3 a -5 c <= 0; R2: +2 a -5 d <= 0; R3: +2 b -5 c <= 0; R4: +3 b -5 d <= 0; R5: +3 a +2 b <= 5; R6: +2 a +3 b <= 5; /\* Variable bounds \*/ a <= 1; b <= 1; ===================== Results(correct): a = 1, b = 1, value = 10 Program for SimplexSolve: ===================== LinearObjectiveFunction kritFcia = new LinearObjectiveFunction(new double[] {7, 3, 0, 0} , 0); Collection<LinearConstraint> podmienky = new ArrayList<LinearConstraint>(); podmienky.add(new LinearConstraint(new double[] {1, 0, 0, 0} , Relationship.LEQ, 1)); podmienky.add(new LinearConstraint(new double[] {0, 1, 0, 0} , Relationship.LEQ, 1)); podmienky.add(new LinearConstraint(new double[] {3, 0, -5, 0} , Relationship.LEQ, 0)); podmienky.add(new LinearConstraint(new double[] {2, 0, 0, -5} , Relationship.LEQ, 0)); podmienky.add(new LinearConstraint(new double[] {0, 2, -5, 0} , Relationship.LEQ, 0)); podmienky.add(new LinearConstraint(new double[] {0, 3, 0, -5} , Relationship.LEQ, 0)); podmienky.add(new LinearConstraint(new double[] {3, 2, 0, 0} , Relationship.LEQ, 5)); podmienky.add(new LinearConstraint(new double[] {2, 3, 0, 0} , Relationship.LEQ, 5)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair result = solver.optimize(kritFcia, podmienky, GoalType.MAXIMIZE, true); ===================== Results(incorrect): a = 1, b = 0.5, value = 8.5 P.S. I used the latest software from the repository (including [~~MATH-286~~](https://issues.apache.org/jira/browse/MATH-286 "SimplexSolver not working as expected?") fix). ``` You are a professional Java test case writer, please create a test case named `testMath288` for the issue `Math-MATH-288`, utilizing the provided issue report information and the following function signature. ```java @Test public void testMath288() throws OptimizationException { ```
60
[ "org.apache.commons.math.optimization.linear.SimplexSolver" ]
28f4977fb9075e3935a5ccce1360d2cd68d45e9922f4c151444f2fce7ae3f399
@Test public void testMath288() throws OptimizationException
// You are a professional Java test case writer, please create a test case named `testMath288` for the issue `Math-MATH-288`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-288 // // ## Issue-Title: // SimplexSolver not working as expected 2 // // ## Issue-Description: // // SimplexSolver didn't find the optimal solution. // // // Program for Lpsolve: // // ===================== // // /\* Objective function \*/ // // max: 7 a 3 b; // // // /\* Constraints \*/ // // R1: +3 a -5 c <= 0; // // R2: +2 a -5 d <= 0; // // R3: +2 b -5 c <= 0; // // R4: +3 b -5 d <= 0; // // R5: +3 a +2 b <= 5; // // R6: +2 a +3 b <= 5; // // // /\* Variable bounds \*/ // // a <= 1; // // b <= 1; // // ===================== // // Results(correct): a = 1, b = 1, value = 10 // // // Program for SimplexSolve: // // ===================== // // LinearObjectiveFunction kritFcia = new LinearObjectiveFunction(new double[] // // // {7, 3, 0, 0} // , 0); // // Collection<LinearConstraint> podmienky = new ArrayList<LinearConstraint>(); // // podmienky.add(new LinearConstraint(new double[] // // // {1, 0, 0, 0} // , Relationship.LEQ, 1)); // // podmienky.add(new LinearConstraint(new double[] // // // {0, 1, 0, 0} // , Relationship.LEQ, 1)); // // podmienky.add(new LinearConstraint(new double[] // // // {3, 0, -5, 0} // , Relationship.LEQ, 0)); // // podmienky.add(new LinearConstraint(new double[] // // // {2, 0, 0, -5} // , Relationship.LEQ, 0)); // // podmienky.add(new LinearConstraint(new double[] // // // {0, 2, -5, 0} // , Relationship.LEQ, 0)); // // podmienky.add(new LinearConstraint(new double[] // // // {0, 3, 0, -5} // , Relationship.LEQ, 0)); // // podmienky.add(new LinearConstraint(new double[] // // // {3, 2, 0, 0} // , Relationship.LEQ, 5)); // // podmienky.add(new LinearConstraint(new double[] // // // {2, 3, 0, 0} // , Relationship.LEQ, 5)); // // SimplexSolver solver = new SimplexSolver(); // // RealPointValuePair result = solver.optimize(kritFcia, podmienky, GoalType.MAXIMIZE, true); // // ===================== // // Results(incorrect): a = 1, b = 0.5, value = 8.5 // // // P.S. I used the latest software from the repository (including [~~MATH-286~~](https://issues.apache.org/jira/browse/MATH-286 "SimplexSolver not working as expected?") fix). // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.optimization.linear; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.linear.ArrayRealVector; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.OptimizationException; import org.apache.commons.math.optimization.RealPointValuePair; import org.junit.Test; public class SimplexSolverTest { @Test public void testMath272() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(0.0, solution.getPoint()[0], .0000001); assertEquals(1.0, solution.getPoint()[1], .0000001); assertEquals(1.0, solution.getPoint()[2], .0000001); assertEquals(3.0, solution.getValue(), .0000001); } @Test public void testMath286() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.2, 0.3 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 23.0)); RealPointValuePair solution = new SimplexSolver().optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(6.9, solution.getValue(), .0000001); } @Test public void testMath288() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(10.0, solution.getValue(), .0000001); } @Test public void testSimplexSolver() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 7); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(57.0, solution.getValue(), 0.0); } @Test public void testSingleVariableAndConstraint() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(10.0, solution.getPoint()[0], 0.0); assertEquals(30.0, solution.getValue(), 0.0); } /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(50.0, solution.getValue(), 0.0); } @Test public void testMinimization() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false); assertEquals(4.0, solution.getPoint()[0], 0.0); assertEquals(0.0, solution.getPoint()[1], 0.0); assertEquals(-13.0, solution.getValue(), 0.0); } @Test public void testSolutionWithNegativeDecisionVariable() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(-2.0, solution.getPoint()[0], 0.0); assertEquals(8.0, solution.getPoint()[1], 0.0); assertEquals(12.0, solution.getValue(), 0.0); } @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test public void testRestrictVariablesToNonNegative() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); assertEquals(480.419243986254, solution.getPoint()[1], .0000001); assertEquals(0.0, solution.getPoint()[2], .0000001); assertEquals(0.0, solution.getPoint()[3], .0000001); assertEquals(0.0, solution.getPoint()[4], .0000001); assertEquals(1438556.7491409, solution.getValue(), .0000001); } @Test public void testEpsilon() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(1.0, solution.getPoint()[0], 0.0); assertEquals(1.0, solution.getPoint()[1], 0.0); assertEquals(0.0, solution.getPoint()[2], 0.0); assertEquals(15.0, solution.getValue(), 0.0); } @Test public void testTrivialModel() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(0, solution.getValue(), .0000001); } @Test public void testLargeModel() throws OptimizationException { double[] objective = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(7518.0, solution.getValue(), .0000001); } /** * Converts a test string to a {@link LinearConstraint}. * Ex: x0 + x1 + x2 + x3 - x12 = 0 */ private LinearConstraint equationFromString(int numCoefficients, String s) { Relationship relationship; if (s.contains(">=")) { relationship = Relationship.GEQ; } else if (s.contains("<=")) { relationship = Relationship.LEQ; } else if (s.contains("=")) { relationship = Relationship.EQ; } else { throw new IllegalArgumentException(); } String[] equationParts = s.split("[>|<]?="); double rhs = Double.parseDouble(equationParts[1].trim()); RealVector lhs = new ArrayRealVector(numCoefficients); String left = equationParts[0].replaceAll(" ?x", ""); String[] coefficients = left.split(" "); for (String coefficient : coefficients) { double value = coefficient.charAt(0) == '-' ? -1 : 1; int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim()); lhs.setEntry(index, value); } return new LinearConstraint(lhs, relationship, rhs); } }
public void testNullCommentEqualsEmptyComment() { ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); ZipArchiveEntry entry2 = new ZipArchiveEntry("foo"); ZipArchiveEntry entry3 = new ZipArchiveEntry("foo"); entry1.setComment(null); entry2.setComment(""); entry3.setComment("bar"); assertEquals(entry1, entry2); assertFalse(entry1.equals(entry3)); assertFalse(entry2.equals(entry3)); }
org.apache.commons.compress.archivers.zip.ZipArchiveEntryTest::testNullCommentEqualsEmptyComment
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java
252
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java
testNullCommentEqualsEmptyComment
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import java.util.zip.ZipEntry; import junit.framework.TestCase; /** * JUnit 3 testcases for org.apache.commons.compress.archivers.zip.ZipEntry. * */ public class ZipArchiveEntryTest extends TestCase { public ZipArchiveEntryTest(String name) { super(name); } /** * test handling of extra fields */ public void testExtraFields() { AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); byte[] data1 = ze.getExtra(); ZipExtraField[] result = ze.getExtraFields(); assertEquals("first pass", 2, result.length); assertSame(a, result[0]); assertSame(u, result[1]); UnrecognizedExtraField u2 = new UnrecognizedExtraField(); u2.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u2.setLocalFileDataData(new byte[] {1}); ze.addExtraField(u2); byte[] data2 = ze.getExtra(); result = ze.getExtraFields(); assertEquals("second pass", 2, result.length); assertSame(a, result[0]); assertSame(u2, result[1]); assertEquals("length second pass", data1.length+1, data2.length); UnrecognizedExtraField u3 = new UnrecognizedExtraField(); u3.setHeaderId(new ZipShort(2)); u3.setLocalFileDataData(new byte[] {1}); ze.addExtraField(u3); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); ze.removeExtraField(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); byte[] data3 = ze.getExtra(); result = ze.getExtraFields(); assertEquals("fourth pass", 2, result.length); assertSame(a, result[0]); assertSame(u3, result[1]); assertEquals("length fourth pass", data2.length, data3.length); try { ze.removeExtraField(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); fail("should be no such element"); } catch (java.util.NoSuchElementException nse) { } } /** * test handling of extra fields via central directory */ public void testExtraFieldMerging() { AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); // merge // Header-ID 1 + length 1 + one byte of data byte[] b = ExtraFieldUtilsTest.UNRECOGNIZED_HEADER.getBytes(); ze.setCentralDirectoryExtra(new byte[] {b[0], b[1], 1, 0, 127}); ZipExtraField[] result = ze.getExtraFields(); assertEquals("first pass", 2, result.length); assertSame(a, result[0]); assertEquals(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER, result[1].getHeaderId()); assertEquals(new ZipShort(0), result[1].getLocalFileDataLength()); assertEquals(new ZipShort(1), result[1].getCentralDirectoryLength()); // add new // Header-ID 2 + length 0 ze.setCentralDirectoryExtra(new byte[] {2, 0, 0, 0}); result = ze.getExtraFields(); assertEquals("second pass", 3, result.length); // merge // Header-ID 2 + length 1 + one byte of data ze.setExtra(new byte[] {2, 0, 1, 0, 127}); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); assertSame(a, result[0]); assertEquals(new ZipShort(2), result[2].getHeaderId()); assertEquals(new ZipShort(1), result[2].getLocalFileDataLength()); assertEquals(new ZipShort(0), result[2].getCentralDirectoryLength()); } /** * test handling of extra fields */ public void testAddAsFirstExtraField() { AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); byte[] data1 = ze.getExtra(); UnrecognizedExtraField u2 = new UnrecognizedExtraField(); u2.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u2.setLocalFileDataData(new byte[] {1}); ze.addAsFirstExtraField(u2); byte[] data2 = ze.getExtra(); ZipExtraField[] result = ze.getExtraFields(); assertEquals("second pass", 2, result.length); assertSame(u2, result[0]); assertSame(a, result[1]); assertEquals("length second pass", data1.length + 1, data2.length); UnrecognizedExtraField u3 = new UnrecognizedExtraField(); u3.setHeaderId(new ZipShort(2)); u3.setLocalFileDataData(new byte[] {1}); ze.addAsFirstExtraField(u3); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); assertSame(u3, result[0]); assertSame(u2, result[1]); assertSame(a, result[2]); } public void testUnixMode() { ZipArchiveEntry ze = new ZipArchiveEntry("foo"); assertEquals(0, ze.getPlatform()); ze.setUnixMode(0755); assertEquals(3, ze.getPlatform()); assertEquals(0755, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0, ze.getExternalAttributes() & 0xFFFF); ze.setUnixMode(0444); assertEquals(3, ze.getPlatform()); assertEquals(0444, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(1, ze.getExternalAttributes() & 0xFFFF); ze = new ZipArchiveEntry("foo/"); assertEquals(0, ze.getPlatform()); ze.setUnixMode(0777); assertEquals(3, ze.getPlatform()); assertEquals(0777, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0x10, ze.getExternalAttributes() & 0xFFFF); ze.setUnixMode(0577); assertEquals(3, ze.getPlatform()); assertEquals(0577, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0x11, ze.getExternalAttributes() & 0xFFFF); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-93" * >COMPRESS-93</a>. */ public void testCompressionMethod() { ZipArchiveOutputStream zos = new ZipArchiveOutputStream((java.io.OutputStream) null); ZipArchiveEntry entry = new ZipArchiveEntry("foo"); assertEquals(-1, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.STORED); assertEquals(ZipEntry.STORED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.DEFLATED); assertEquals(ZipEntry.DEFLATED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); // Test the unsupported "imploded" compression method (6) entry.setMethod(6); assertEquals(6, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-94" * >COMPRESS-94</a>. */ public void testNotEquals() { ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); ZipArchiveEntry entry2 = new ZipArchiveEntry("bar"); assertFalse(entry1.equals(entry2)); } /** * Tests comment's influence on equals comparisons. * @see https://issues.apache.org/jira/browse/COMPRESS-187 */ public void testNullCommentEqualsEmptyComment() { ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); ZipArchiveEntry entry2 = new ZipArchiveEntry("foo"); ZipArchiveEntry entry3 = new ZipArchiveEntry("foo"); entry1.setComment(null); entry2.setComment(""); entry3.setComment("bar"); assertEquals(entry1, entry2); assertFalse(entry1.equals(entry3)); assertFalse(entry2.equals(entry3)); } }
// You are a professional Java test case writer, please create a test case named `testNullCommentEqualsEmptyComment` for the issue `Compress-COMPRESS-187`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-187 // // ## Issue-Title: // ZipArchiveInputStream and ZipFile don't produce equals ZipArchiveEntry instances // // ## Issue-Description: // // I'm trying to use a ZipArchiveEntry coming from ZipArchiveInputStream that I stored somwhere for later with a ZipFile and it does not work. // // // The reason is that it can't find the ZipArchiveEntry in the ZipFile entries map. It is exactly the same zip file but both entries are not equals so the Map#get fail. // // // As far as I can see the main difference is that comment is null in ZipArchiveInputStream while it's en empty string in ZipFile. I looked at ZipArchiveInputStream and it looks like the comment (whatever it is) is simply not parsed while I can find some code related to the comment at the end of ZIipFile#readCentralDirectoryEntry. // // // Note that java.util.zip does not have this issue. Did not checked what they do but the zip entries are equals. // // // // // public void testNullCommentEqualsEmptyComment() {
252
/** * Tests comment's influence on equals comparisons. * @see https://issues.apache.org/jira/browse/COMPRESS-187 */
15
242
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-187 ## Issue-Title: ZipArchiveInputStream and ZipFile don't produce equals ZipArchiveEntry instances ## Issue-Description: I'm trying to use a ZipArchiveEntry coming from ZipArchiveInputStream that I stored somwhere for later with a ZipFile and it does not work. The reason is that it can't find the ZipArchiveEntry in the ZipFile entries map. It is exactly the same zip file but both entries are not equals so the Map#get fail. As far as I can see the main difference is that comment is null in ZipArchiveInputStream while it's en empty string in ZipFile. I looked at ZipArchiveInputStream and it looks like the comment (whatever it is) is simply not parsed while I can find some code related to the comment at the end of ZIipFile#readCentralDirectoryEntry. Note that java.util.zip does not have this issue. Did not checked what they do but the zip entries are equals. ``` You are a professional Java test case writer, please create a test case named `testNullCommentEqualsEmptyComment` for the issue `Compress-COMPRESS-187`, utilizing the provided issue report information and the following function signature. ```java public void testNullCommentEqualsEmptyComment() { ```
242
[ "org.apache.commons.compress.archivers.zip.ZipArchiveEntry" ]
2a28f9a7db5afb47ea6f8908ec3dbac04732487006712a04c79563debd125361
public void testNullCommentEqualsEmptyComment()
// You are a professional Java test case writer, please create a test case named `testNullCommentEqualsEmptyComment` for the issue `Compress-COMPRESS-187`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-187 // // ## Issue-Title: // ZipArchiveInputStream and ZipFile don't produce equals ZipArchiveEntry instances // // ## Issue-Description: // // I'm trying to use a ZipArchiveEntry coming from ZipArchiveInputStream that I stored somwhere for later with a ZipFile and it does not work. // // // The reason is that it can't find the ZipArchiveEntry in the ZipFile entries map. It is exactly the same zip file but both entries are not equals so the Map#get fail. // // // As far as I can see the main difference is that comment is null in ZipArchiveInputStream while it's en empty string in ZipFile. I looked at ZipArchiveInputStream and it looks like the comment (whatever it is) is simply not parsed while I can find some code related to the comment at the end of ZIipFile#readCentralDirectoryEntry. // // // Note that java.util.zip does not have this issue. Did not checked what they do but the zip entries are equals. // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import java.util.zip.ZipEntry; import junit.framework.TestCase; /** * JUnit 3 testcases for org.apache.commons.compress.archivers.zip.ZipEntry. * */ public class ZipArchiveEntryTest extends TestCase { public ZipArchiveEntryTest(String name) { super(name); } /** * test handling of extra fields */ public void testExtraFields() { AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); byte[] data1 = ze.getExtra(); ZipExtraField[] result = ze.getExtraFields(); assertEquals("first pass", 2, result.length); assertSame(a, result[0]); assertSame(u, result[1]); UnrecognizedExtraField u2 = new UnrecognizedExtraField(); u2.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u2.setLocalFileDataData(new byte[] {1}); ze.addExtraField(u2); byte[] data2 = ze.getExtra(); result = ze.getExtraFields(); assertEquals("second pass", 2, result.length); assertSame(a, result[0]); assertSame(u2, result[1]); assertEquals("length second pass", data1.length+1, data2.length); UnrecognizedExtraField u3 = new UnrecognizedExtraField(); u3.setHeaderId(new ZipShort(2)); u3.setLocalFileDataData(new byte[] {1}); ze.addExtraField(u3); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); ze.removeExtraField(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); byte[] data3 = ze.getExtra(); result = ze.getExtraFields(); assertEquals("fourth pass", 2, result.length); assertSame(a, result[0]); assertSame(u3, result[1]); assertEquals("length fourth pass", data2.length, data3.length); try { ze.removeExtraField(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); fail("should be no such element"); } catch (java.util.NoSuchElementException nse) { } } /** * test handling of extra fields via central directory */ public void testExtraFieldMerging() { AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); // merge // Header-ID 1 + length 1 + one byte of data byte[] b = ExtraFieldUtilsTest.UNRECOGNIZED_HEADER.getBytes(); ze.setCentralDirectoryExtra(new byte[] {b[0], b[1], 1, 0, 127}); ZipExtraField[] result = ze.getExtraFields(); assertEquals("first pass", 2, result.length); assertSame(a, result[0]); assertEquals(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER, result[1].getHeaderId()); assertEquals(new ZipShort(0), result[1].getLocalFileDataLength()); assertEquals(new ZipShort(1), result[1].getCentralDirectoryLength()); // add new // Header-ID 2 + length 0 ze.setCentralDirectoryExtra(new byte[] {2, 0, 0, 0}); result = ze.getExtraFields(); assertEquals("second pass", 3, result.length); // merge // Header-ID 2 + length 1 + one byte of data ze.setExtra(new byte[] {2, 0, 1, 0, 127}); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); assertSame(a, result[0]); assertEquals(new ZipShort(2), result[2].getHeaderId()); assertEquals(new ZipShort(1), result[2].getLocalFileDataLength()); assertEquals(new ZipShort(0), result[2].getCentralDirectoryLength()); } /** * test handling of extra fields */ public void testAddAsFirstExtraField() { AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); byte[] data1 = ze.getExtra(); UnrecognizedExtraField u2 = new UnrecognizedExtraField(); u2.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u2.setLocalFileDataData(new byte[] {1}); ze.addAsFirstExtraField(u2); byte[] data2 = ze.getExtra(); ZipExtraField[] result = ze.getExtraFields(); assertEquals("second pass", 2, result.length); assertSame(u2, result[0]); assertSame(a, result[1]); assertEquals("length second pass", data1.length + 1, data2.length); UnrecognizedExtraField u3 = new UnrecognizedExtraField(); u3.setHeaderId(new ZipShort(2)); u3.setLocalFileDataData(new byte[] {1}); ze.addAsFirstExtraField(u3); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); assertSame(u3, result[0]); assertSame(u2, result[1]); assertSame(a, result[2]); } public void testUnixMode() { ZipArchiveEntry ze = new ZipArchiveEntry("foo"); assertEquals(0, ze.getPlatform()); ze.setUnixMode(0755); assertEquals(3, ze.getPlatform()); assertEquals(0755, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0, ze.getExternalAttributes() & 0xFFFF); ze.setUnixMode(0444); assertEquals(3, ze.getPlatform()); assertEquals(0444, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(1, ze.getExternalAttributes() & 0xFFFF); ze = new ZipArchiveEntry("foo/"); assertEquals(0, ze.getPlatform()); ze.setUnixMode(0777); assertEquals(3, ze.getPlatform()); assertEquals(0777, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0x10, ze.getExternalAttributes() & 0xFFFF); ze.setUnixMode(0577); assertEquals(3, ze.getPlatform()); assertEquals(0577, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0x11, ze.getExternalAttributes() & 0xFFFF); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-93" * >COMPRESS-93</a>. */ public void testCompressionMethod() { ZipArchiveOutputStream zos = new ZipArchiveOutputStream((java.io.OutputStream) null); ZipArchiveEntry entry = new ZipArchiveEntry("foo"); assertEquals(-1, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.STORED); assertEquals(ZipEntry.STORED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.DEFLATED); assertEquals(ZipEntry.DEFLATED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); // Test the unsupported "imploded" compression method (6) entry.setMethod(6); assertEquals(6, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-94" * >COMPRESS-94</a>. */ public void testNotEquals() { ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); ZipArchiveEntry entry2 = new ZipArchiveEntry("bar"); assertFalse(entry1.equals(entry2)); } /** * Tests comment's influence on equals comparisons. * @see https://issues.apache.org/jira/browse/COMPRESS-187 */ public void testNullCommentEqualsEmptyComment() { ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); ZipArchiveEntry entry2 = new ZipArchiveEntry("foo"); ZipArchiveEntry entry3 = new ZipArchiveEntry("foo"); entry1.setComment(null); entry2.setComment(""); entry3.setComment("bar"); assertEquals(entry1, entry2); assertFalse(entry1.equals(entry3)); assertFalse(entry2.equals(entry3)); } }
public void testNoInlineDeletedProperties() { testSameLocal( "var foo = {bar:1};" + "delete foo.bar;" + "return foo.bar;"); }
com.google.javascript.jscomp.InlineObjectLiteralsTest::testNoInlineDeletedProperties
test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java
355
test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java
testNoInlineDeletedProperties
/* * Copyright 2011 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Verifies that valid candidates for object literals are inlined as * expected, and invalid candidates are not touched. * */ public class InlineObjectLiteralsTest extends CompilerTestCase { public InlineObjectLiteralsTest() { enableNormalize(); } @Override public void setUp() { super.enableLineNumberCheck(true); } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new InlineObjectLiterals( compiler, compiler.getUniqueNameIdSupplier()); } // Test object literal -> variable inlining public void testObject0() { // Don't mess with global variables, that is the job of CollapseProperties. testSame("var a = {x:1}; f(a.x);"); } public void testObject1() { testLocal("var a = {x:x(), y:y()}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0=x();" + "var JSCompiler_object_inline_y_1=y();" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y_1);"); } public void testObject1a() { testLocal("var a; a = {x:x, y:y}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "(JSCompiler_object_inline_x_0=x," + "JSCompiler_object_inline_y_1=y, true);" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y_1);"); } public void testObject2() { testLocal("var a = {y:y}; a.x = z; f(a.x, a.y);", "var JSCompiler_object_inline_y_0 = y;" + "var JSCompiler_object_inline_x_1;" + "JSCompiler_object_inline_x_1=z;" + "f(JSCompiler_object_inline_x_1, JSCompiler_object_inline_y_0);"); } public void testObject3() { // Inlining the 'y' would cause the 'this' to be different in the // target function. testSameLocal("var a = {y:y,x:x}; a.y(); f(a.x);"); testSameLocal("var a; a = {y:y,x:x}; a.y(); f(a.x);"); } public void testObject4() { // Object literal is escaped. testSameLocal("var a = {y:y}; a.x = z; f(a.x, a.y); g(a);"); testSameLocal("var a; a = {y:y}; a.x = z; f(a.x, a.y); g(a);"); } public void testObject5() { testLocal("var a = {x:x, y:y}; var b = {a:a}; f(b.a.x, b.a.y);", "var a = {x:x, y:y};" + "var JSCompiler_object_inline_a_0=a;" + "f(JSCompiler_object_inline_a_0.x, JSCompiler_object_inline_a_0.y);"); } public void testObject6() { testLocal("for (var i = 0; i < 5; i++) { var a = {i:i,x:x}; f(a.i, a.x); }", "for (var i = 0; i < 5; i++) {" + " var JSCompiler_object_inline_i_0=i;" + " var JSCompiler_object_inline_x_1=x;" + " f(JSCompiler_object_inline_i_0,JSCompiler_object_inline_x_1)" + "}"); testLocal("if (c) { var a = {i:i,x:x}; f(a.i, a.x); }", "if (c) {" + " var JSCompiler_object_inline_i_0=i;" + " var JSCompiler_object_inline_x_1=x;" + " f(JSCompiler_object_inline_i_0,JSCompiler_object_inline_x_1)" + "}"); } public void testObject7() { testLocal("var a = {x:x, y:f()}; g(a.x);", "var JSCompiler_object_inline_x_0=x;" + "var JSCompiler_object_inline_y_1=f();" + "g(JSCompiler_object_inline_x_0)"); } public void testObject8() { testSameLocal("var a = {x:x,y:y}; var b = {x:y}; f((c?a:b).x);"); testLocal("var a; if(c) { a={x:x, y:y}; } else { a={x:y}; } f(a.x);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "if(c) JSCompiler_object_inline_x_0=x," + " JSCompiler_object_inline_y_1=y," + " true;" + "else JSCompiler_object_inline_x_0=y," + " JSCompiler_object_inline_y_1=void 0," + " true;" + "f(JSCompiler_object_inline_x_0)"); testLocal("var a = {x:x,y:y}; var b = {x:y}; c ? f(a.x) : f(b.x);", "var JSCompiler_object_inline_x_0 = x; " + "var JSCompiler_object_inline_y_1 = y; " + "var JSCompiler_object_inline_x_2 = y; " + "c ? f(JSCompiler_object_inline_x_0):f(JSCompiler_object_inline_x_2)"); } public void testObject9() { // There is a call, so no inlining testSameLocal("function f(a,b) {" + " var x = {a:a,b:b}; x.a(); return x.b;" + "}"); testLocal("function f(a,b) {" + " var x = {a:a,b:b}; g(x.a); x = {a:a,b:2}; return x.b;" + "}", "function f(a,b) {" + " var JSCompiler_object_inline_a_0 = a;" + " var JSCompiler_object_inline_b_1 = b;" + " g(JSCompiler_object_inline_a_0);" + " JSCompiler_object_inline_a_0 = a," + " JSCompiler_object_inline_b_1=2," + " true;" + " return JSCompiler_object_inline_b_1" + "}"); testLocal("function f(a,b) { " + " var x = {a:a,b:b}; g(x.a); x.b = x.c = 2; return x.b; " + "}", "function f(a,b) { " + " var JSCompiler_object_inline_a_0=a;" + " var JSCompiler_object_inline_b_1=b; " + " var JSCompiler_object_inline_c_2;" + " g(JSCompiler_object_inline_a_0);" + " JSCompiler_object_inline_b_1=JSCompiler_object_inline_c_2=2;" + " return JSCompiler_object_inline_b_1" + "}"); } public void testObject10() { testLocal("var x; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b);", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var b = f();" + "JSCompiler_object_inline_a_0=a,JSCompiler_object_inline_b_1=b,true;" + "if(JSCompiler_object_inline_a_0) g(JSCompiler_object_inline_b_1)"); testLocal("var x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c", "var x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c"); testLocal("var x; var b = f(); x = {a:a, b:b}; x.c = c; if(x.a) g(x.b) + x.c", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var b = f();" + "JSCompiler_object_inline_a_0 = a,JSCompiler_object_inline_b_1 = b, " + " JSCompiler_object_inline_c_2=void 0,true;" + "JSCompiler_object_inline_c_2 = c;" + "if (JSCompiler_object_inline_a_0)" + " g(JSCompiler_object_inline_b_1) + JSCompiler_object_inline_c_2;"); testLocal("var x = {a:a}; if (b) x={b:b}; f(x.a||x.b);", "var JSCompiler_object_inline_a_0 = a;" + "var JSCompiler_object_inline_b_1;" + "if(b) JSCompiler_object_inline_b_1 = b," + " JSCompiler_object_inline_a_0 = void 0," + " true;" + "f(JSCompiler_object_inline_a_0 || JSCompiler_object_inline_b_1)"); testLocal("var x; var y = 5; x = {a:a, b:b, c:c}; if (b) x={b:b}; f(x.a||x.b);", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var y=5;" + "JSCompiler_object_inline_a_0=a," + "JSCompiler_object_inline_b_1=b," + "JSCompiler_object_inline_c_2=c," + "true;" + "if (b) JSCompiler_object_inline_b_1=b," + " JSCompiler_object_inline_a_0=void 0," + " JSCompiler_object_inline_c_2=void 0," + " true;" + "f(JSCompiler_object_inline_a_0||JSCompiler_object_inline_b_1)"); } public void testObject11() { testSameLocal("var x = {a:b}; (x = {a:a}).c = 5; f(x.a);"); testSameLocal("var x = {a:a}; f(x[a]); g(x[a]);"); } public void testObject12() { testLocal("var a; a = {x:1, y:2}; f(a.x, a.y2);", "var a; a = {x:1, y:2}; f(a.x, a.y2);"); } public void testObject13() { testSameLocal("var x = {a:1, b:2}; x = {a:3, b:x.a};"); } public void testObject14() { testSameLocal("var x = {a:1}; if ('a' in x) { f(); }"); testSameLocal("var x = {a:1}; for (var y in x) { f(y); }"); } public void testObject15() { testSameLocal("x = x || {}; f(x.a);"); } public void testObject16() { testLocal("function f(e) { bar(); x = {a: foo()}; var x; print(x.a); }", "function f(e) { " + " var JSCompiler_object_inline_a_0;" + " bar();" + " JSCompiler_object_inline_a_0 = foo(), true;" + " print(JSCompiler_object_inline_a_0);" + "}"); } public void testObject17() { // Note: Some day, with careful analysis, these two uses could be // disambiguated, and the second assignment could be inlined. testSameLocal( "var a = {a: function(){}};" + "a.a();" + "a = {a1: 100};" + "print(a.a1);"); } public void testObject18() { testSameLocal("var a,b; b=a={x:x, y:y}; f(b.x);"); } public void testObject19() { testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; } else { b=a={x:y}; } f(b.x);"); } public void testObject20() { testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; } else { b=a={x:y}; } f(a.x);"); } public void testObject21() { testSameLocal("var a,b; b=a={x:x, y:y};"); testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; }" + "else { b=a={x:y}; } f(a.x); f(b.x)"); testSameLocal("var a, b; if(c) { if (a={x:x, y:y}) f(); } " + "else { b=a={x:y}; } f(a.x);"); testSameLocal("var a,b; b = (a = {x:x, y:x});"); testSameLocal("var a,b; a = {x:x, y:x}; b = a"); testSameLocal("var a,b; a = {x:x, y:x}; b = x || a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y && a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y ? a : a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y , a"); testSameLocal("b = x || (a = {x:1, y:2});"); } public void testObject22() { testLocal("while(1) { var a = {y:1}; if (b) a.x = 2; f(a.y, a.x);}", "for(;1;){" + " var JSCompiler_object_inline_y_0=1;" + " var JSCompiler_object_inline_x_1;" + " if(b) JSCompiler_object_inline_x_1=2;" + " f(JSCompiler_object_inline_y_0,JSCompiler_object_inline_x_1)" + "}"); testLocal("var a; while (1) { f(a.x, a.y); a = {x:1, y:1};}", "var a; while (1) { f(a.x, a.y); a = {x:1, y:1};}"); } public void testObject23() { testLocal("function f() {\n" + " var templateData = {\n" + " linkIds: {\n" + " CHROME: 'cl',\n" + " DISMISS: 'd'\n" + " }\n" + " };\n" + " var html = templateData.linkIds.CHROME \n" + " + \":\" + templateData.linkIds.DISMISS;\n" + "}", "function f(){" + "var JSCompiler_object_inline_CHROME_1='cl';" + "var JSCompiler_object_inline_DISMISS_2='d';" + "var html=JSCompiler_object_inline_CHROME_1 +" + " ':' +JSCompiler_object_inline_DISMISS_2}"); } public void testObject24() { testLocal("function f() {\n" + " var linkIds = {\n" + " CHROME: 1,\n" + " };\n" + " var g = function () {var o = {a: linkIds};}\n" + "}", "function f(){var linkIds={CHROME:1};" + "var g=function(){var JSCompiler_object_inline_a_0=linkIds}}"); } public void testObject25() { testLocal("var a = {x:f(), y:g()}; a = {y:g(), x:f()}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0=f();" + "var JSCompiler_object_inline_y_1=g();" + "JSCompiler_object_inline_y_1=g()," + " JSCompiler_object_inline_x_0=f()," + " true;" + "f(JSCompiler_object_inline_x_0,JSCompiler_object_inline_y_1)"); } public void testObject26() { testLocal("var a = {}; a.b = function() {}; new a.b.c", "var JSCompiler_object_inline_b_0;" + "JSCompiler_object_inline_b_0=function(){};" + "new JSCompiler_object_inline_b_0.c"); } public void testBug545() { testLocal("var a = {}", ""); testLocal("var a; a = {}", "true"); } public void testIssue724() { testSameLocal( "var getType; getType = {};" + "return functionToCheck && " + " getType.toString.apply(functionToCheck) === " + " '[object Function]';"); } public void testNoInlineDeletedProperties() { testSameLocal( "var foo = {bar:1};" + "delete foo.bar;" + "return foo.bar;"); } private final String LOCAL_PREFIX = "function local(){"; private final String LOCAL_POSTFIX = "}"; private void testLocal(String code, String result) { test(LOCAL_PREFIX + code + LOCAL_POSTFIX, LOCAL_PREFIX + result + LOCAL_POSTFIX); } private void testSameLocal(String code) { testLocal(code, code); } }
// You are a professional Java test case writer, please create a test case named `testNoInlineDeletedProperties` for the issue `Closure-851`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-851 // // ## Issue-Title: // Compiler ignores 'delete' statements, can break functionality. // // ## Issue-Description: // When the compiler rewrites internally-referenced object variables to non-object variables, as in the example below, it ignores 'delete' statements. These delete statements work as expected with the objects originally written, but don't function the same when the variables are no longer object properties. See: // // (function(arg) { // var foo = {}; // // foo.bar = arg; // // console.log(foo.bar); // // delete foo.bar; // // console.log(foo.bar); // })(); // // Compiles to (simple setting): // (function(a){console.log(a);delete a;console.log(a)})(); // // Perhaps the compiler needs to look for these delete statements and change them to setting the rewritten variable to undefined instead. // // public void testNoInlineDeletedProperties() {
355
5
350
test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java
test
```markdown ## Issue-ID: Closure-851 ## Issue-Title: Compiler ignores 'delete' statements, can break functionality. ## Issue-Description: When the compiler rewrites internally-referenced object variables to non-object variables, as in the example below, it ignores 'delete' statements. These delete statements work as expected with the objects originally written, but don't function the same when the variables are no longer object properties. See: (function(arg) { var foo = {}; foo.bar = arg; console.log(foo.bar); delete foo.bar; console.log(foo.bar); })(); Compiles to (simple setting): (function(a){console.log(a);delete a;console.log(a)})(); Perhaps the compiler needs to look for these delete statements and change them to setting the rewritten variable to undefined instead. ``` You are a professional Java test case writer, please create a test case named `testNoInlineDeletedProperties` for the issue `Closure-851`, utilizing the provided issue report information and the following function signature. ```java public void testNoInlineDeletedProperties() { ```
350
[ "com.google.javascript.jscomp.InlineObjectLiterals" ]
2a7d0885682151baefb02b0462350cc54e033dae81c9a0eb2d9ce2241130d4f2
public void testNoInlineDeletedProperties()
// You are a professional Java test case writer, please create a test case named `testNoInlineDeletedProperties` for the issue `Closure-851`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-851 // // ## Issue-Title: // Compiler ignores 'delete' statements, can break functionality. // // ## Issue-Description: // When the compiler rewrites internally-referenced object variables to non-object variables, as in the example below, it ignores 'delete' statements. These delete statements work as expected with the objects originally written, but don't function the same when the variables are no longer object properties. See: // // (function(arg) { // var foo = {}; // // foo.bar = arg; // // console.log(foo.bar); // // delete foo.bar; // // console.log(foo.bar); // })(); // // Compiles to (simple setting): // (function(a){console.log(a);delete a;console.log(a)})(); // // Perhaps the compiler needs to look for these delete statements and change them to setting the rewritten variable to undefined instead. // //
Closure
/* * Copyright 2011 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Verifies that valid candidates for object literals are inlined as * expected, and invalid candidates are not touched. * */ public class InlineObjectLiteralsTest extends CompilerTestCase { public InlineObjectLiteralsTest() { enableNormalize(); } @Override public void setUp() { super.enableLineNumberCheck(true); } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new InlineObjectLiterals( compiler, compiler.getUniqueNameIdSupplier()); } // Test object literal -> variable inlining public void testObject0() { // Don't mess with global variables, that is the job of CollapseProperties. testSame("var a = {x:1}; f(a.x);"); } public void testObject1() { testLocal("var a = {x:x(), y:y()}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0=x();" + "var JSCompiler_object_inline_y_1=y();" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y_1);"); } public void testObject1a() { testLocal("var a; a = {x:x, y:y}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "(JSCompiler_object_inline_x_0=x," + "JSCompiler_object_inline_y_1=y, true);" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y_1);"); } public void testObject2() { testLocal("var a = {y:y}; a.x = z; f(a.x, a.y);", "var JSCompiler_object_inline_y_0 = y;" + "var JSCompiler_object_inline_x_1;" + "JSCompiler_object_inline_x_1=z;" + "f(JSCompiler_object_inline_x_1, JSCompiler_object_inline_y_0);"); } public void testObject3() { // Inlining the 'y' would cause the 'this' to be different in the // target function. testSameLocal("var a = {y:y,x:x}; a.y(); f(a.x);"); testSameLocal("var a; a = {y:y,x:x}; a.y(); f(a.x);"); } public void testObject4() { // Object literal is escaped. testSameLocal("var a = {y:y}; a.x = z; f(a.x, a.y); g(a);"); testSameLocal("var a; a = {y:y}; a.x = z; f(a.x, a.y); g(a);"); } public void testObject5() { testLocal("var a = {x:x, y:y}; var b = {a:a}; f(b.a.x, b.a.y);", "var a = {x:x, y:y};" + "var JSCompiler_object_inline_a_0=a;" + "f(JSCompiler_object_inline_a_0.x, JSCompiler_object_inline_a_0.y);"); } public void testObject6() { testLocal("for (var i = 0; i < 5; i++) { var a = {i:i,x:x}; f(a.i, a.x); }", "for (var i = 0; i < 5; i++) {" + " var JSCompiler_object_inline_i_0=i;" + " var JSCompiler_object_inline_x_1=x;" + " f(JSCompiler_object_inline_i_0,JSCompiler_object_inline_x_1)" + "}"); testLocal("if (c) { var a = {i:i,x:x}; f(a.i, a.x); }", "if (c) {" + " var JSCompiler_object_inline_i_0=i;" + " var JSCompiler_object_inline_x_1=x;" + " f(JSCompiler_object_inline_i_0,JSCompiler_object_inline_x_1)" + "}"); } public void testObject7() { testLocal("var a = {x:x, y:f()}; g(a.x);", "var JSCompiler_object_inline_x_0=x;" + "var JSCompiler_object_inline_y_1=f();" + "g(JSCompiler_object_inline_x_0)"); } public void testObject8() { testSameLocal("var a = {x:x,y:y}; var b = {x:y}; f((c?a:b).x);"); testLocal("var a; if(c) { a={x:x, y:y}; } else { a={x:y}; } f(a.x);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "if(c) JSCompiler_object_inline_x_0=x," + " JSCompiler_object_inline_y_1=y," + " true;" + "else JSCompiler_object_inline_x_0=y," + " JSCompiler_object_inline_y_1=void 0," + " true;" + "f(JSCompiler_object_inline_x_0)"); testLocal("var a = {x:x,y:y}; var b = {x:y}; c ? f(a.x) : f(b.x);", "var JSCompiler_object_inline_x_0 = x; " + "var JSCompiler_object_inline_y_1 = y; " + "var JSCompiler_object_inline_x_2 = y; " + "c ? f(JSCompiler_object_inline_x_0):f(JSCompiler_object_inline_x_2)"); } public void testObject9() { // There is a call, so no inlining testSameLocal("function f(a,b) {" + " var x = {a:a,b:b}; x.a(); return x.b;" + "}"); testLocal("function f(a,b) {" + " var x = {a:a,b:b}; g(x.a); x = {a:a,b:2}; return x.b;" + "}", "function f(a,b) {" + " var JSCompiler_object_inline_a_0 = a;" + " var JSCompiler_object_inline_b_1 = b;" + " g(JSCompiler_object_inline_a_0);" + " JSCompiler_object_inline_a_0 = a," + " JSCompiler_object_inline_b_1=2," + " true;" + " return JSCompiler_object_inline_b_1" + "}"); testLocal("function f(a,b) { " + " var x = {a:a,b:b}; g(x.a); x.b = x.c = 2; return x.b; " + "}", "function f(a,b) { " + " var JSCompiler_object_inline_a_0=a;" + " var JSCompiler_object_inline_b_1=b; " + " var JSCompiler_object_inline_c_2;" + " g(JSCompiler_object_inline_a_0);" + " JSCompiler_object_inline_b_1=JSCompiler_object_inline_c_2=2;" + " return JSCompiler_object_inline_b_1" + "}"); } public void testObject10() { testLocal("var x; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b);", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var b = f();" + "JSCompiler_object_inline_a_0=a,JSCompiler_object_inline_b_1=b,true;" + "if(JSCompiler_object_inline_a_0) g(JSCompiler_object_inline_b_1)"); testLocal("var x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c", "var x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c"); testLocal("var x; var b = f(); x = {a:a, b:b}; x.c = c; if(x.a) g(x.b) + x.c", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var b = f();" + "JSCompiler_object_inline_a_0 = a,JSCompiler_object_inline_b_1 = b, " + " JSCompiler_object_inline_c_2=void 0,true;" + "JSCompiler_object_inline_c_2 = c;" + "if (JSCompiler_object_inline_a_0)" + " g(JSCompiler_object_inline_b_1) + JSCompiler_object_inline_c_2;"); testLocal("var x = {a:a}; if (b) x={b:b}; f(x.a||x.b);", "var JSCompiler_object_inline_a_0 = a;" + "var JSCompiler_object_inline_b_1;" + "if(b) JSCompiler_object_inline_b_1 = b," + " JSCompiler_object_inline_a_0 = void 0," + " true;" + "f(JSCompiler_object_inline_a_0 || JSCompiler_object_inline_b_1)"); testLocal("var x; var y = 5; x = {a:a, b:b, c:c}; if (b) x={b:b}; f(x.a||x.b);", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var y=5;" + "JSCompiler_object_inline_a_0=a," + "JSCompiler_object_inline_b_1=b," + "JSCompiler_object_inline_c_2=c," + "true;" + "if (b) JSCompiler_object_inline_b_1=b," + " JSCompiler_object_inline_a_0=void 0," + " JSCompiler_object_inline_c_2=void 0," + " true;" + "f(JSCompiler_object_inline_a_0||JSCompiler_object_inline_b_1)"); } public void testObject11() { testSameLocal("var x = {a:b}; (x = {a:a}).c = 5; f(x.a);"); testSameLocal("var x = {a:a}; f(x[a]); g(x[a]);"); } public void testObject12() { testLocal("var a; a = {x:1, y:2}; f(a.x, a.y2);", "var a; a = {x:1, y:2}; f(a.x, a.y2);"); } public void testObject13() { testSameLocal("var x = {a:1, b:2}; x = {a:3, b:x.a};"); } public void testObject14() { testSameLocal("var x = {a:1}; if ('a' in x) { f(); }"); testSameLocal("var x = {a:1}; for (var y in x) { f(y); }"); } public void testObject15() { testSameLocal("x = x || {}; f(x.a);"); } public void testObject16() { testLocal("function f(e) { bar(); x = {a: foo()}; var x; print(x.a); }", "function f(e) { " + " var JSCompiler_object_inline_a_0;" + " bar();" + " JSCompiler_object_inline_a_0 = foo(), true;" + " print(JSCompiler_object_inline_a_0);" + "}"); } public void testObject17() { // Note: Some day, with careful analysis, these two uses could be // disambiguated, and the second assignment could be inlined. testSameLocal( "var a = {a: function(){}};" + "a.a();" + "a = {a1: 100};" + "print(a.a1);"); } public void testObject18() { testSameLocal("var a,b; b=a={x:x, y:y}; f(b.x);"); } public void testObject19() { testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; } else { b=a={x:y}; } f(b.x);"); } public void testObject20() { testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; } else { b=a={x:y}; } f(a.x);"); } public void testObject21() { testSameLocal("var a,b; b=a={x:x, y:y};"); testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; }" + "else { b=a={x:y}; } f(a.x); f(b.x)"); testSameLocal("var a, b; if(c) { if (a={x:x, y:y}) f(); } " + "else { b=a={x:y}; } f(a.x);"); testSameLocal("var a,b; b = (a = {x:x, y:x});"); testSameLocal("var a,b; a = {x:x, y:x}; b = a"); testSameLocal("var a,b; a = {x:x, y:x}; b = x || a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y && a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y ? a : a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y , a"); testSameLocal("b = x || (a = {x:1, y:2});"); } public void testObject22() { testLocal("while(1) { var a = {y:1}; if (b) a.x = 2; f(a.y, a.x);}", "for(;1;){" + " var JSCompiler_object_inline_y_0=1;" + " var JSCompiler_object_inline_x_1;" + " if(b) JSCompiler_object_inline_x_1=2;" + " f(JSCompiler_object_inline_y_0,JSCompiler_object_inline_x_1)" + "}"); testLocal("var a; while (1) { f(a.x, a.y); a = {x:1, y:1};}", "var a; while (1) { f(a.x, a.y); a = {x:1, y:1};}"); } public void testObject23() { testLocal("function f() {\n" + " var templateData = {\n" + " linkIds: {\n" + " CHROME: 'cl',\n" + " DISMISS: 'd'\n" + " }\n" + " };\n" + " var html = templateData.linkIds.CHROME \n" + " + \":\" + templateData.linkIds.DISMISS;\n" + "}", "function f(){" + "var JSCompiler_object_inline_CHROME_1='cl';" + "var JSCompiler_object_inline_DISMISS_2='d';" + "var html=JSCompiler_object_inline_CHROME_1 +" + " ':' +JSCompiler_object_inline_DISMISS_2}"); } public void testObject24() { testLocal("function f() {\n" + " var linkIds = {\n" + " CHROME: 1,\n" + " };\n" + " var g = function () {var o = {a: linkIds};}\n" + "}", "function f(){var linkIds={CHROME:1};" + "var g=function(){var JSCompiler_object_inline_a_0=linkIds}}"); } public void testObject25() { testLocal("var a = {x:f(), y:g()}; a = {y:g(), x:f()}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0=f();" + "var JSCompiler_object_inline_y_1=g();" + "JSCompiler_object_inline_y_1=g()," + " JSCompiler_object_inline_x_0=f()," + " true;" + "f(JSCompiler_object_inline_x_0,JSCompiler_object_inline_y_1)"); } public void testObject26() { testLocal("var a = {}; a.b = function() {}; new a.b.c", "var JSCompiler_object_inline_b_0;" + "JSCompiler_object_inline_b_0=function(){};" + "new JSCompiler_object_inline_b_0.c"); } public void testBug545() { testLocal("var a = {}", ""); testLocal("var a; a = {}", "true"); } public void testIssue724() { testSameLocal( "var getType; getType = {};" + "return functionToCheck && " + " getType.toString.apply(functionToCheck) === " + " '[object Function]';"); } public void testNoInlineDeletedProperties() { testSameLocal( "var foo = {bar:1};" + "delete foo.bar;" + "return foo.bar;"); } private final String LOCAL_PREFIX = "function local(){"; private final String LOCAL_POSTFIX = "}"; private void testLocal(String code, String result) { test(LOCAL_PREFIX + code + LOCAL_POSTFIX, LOCAL_PREFIX + result + LOCAL_POSTFIX); } private void testSameLocal(String code) { testLocal(code, code); } }
@Test public void survivesBlankLinesInPaxHeader() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-355.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("package/package.json", entry.getName()); assertNull(is.getNextTarEntry()); } finally { is.close(); } }
org.apache.commons.compress.archivers.tar.TarArchiveInputStreamTest::survivesBlankLinesInPaxHeader
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
313
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
survivesBlankLinesInPaxHeader
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.tar; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.apache.commons.compress.AbstractTestCase.mkdir; import static org.apache.commons.compress.AbstractTestCase.rmdir; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.Date; import java.util.Map; import java.util.TimeZone; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.utils.CharsetNames; import org.apache.commons.compress.utils.IOUtils; import org.junit.Test; public class TarArchiveInputStreamTest { @Test public void readSimplePaxHeader() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("1321711775.972059463", headers.get("atime")); tais.close(); } @Test public void secondEntryWinsWhenPaxHeaderContainsDuplicateKey() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n11 foo=baz\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("baz", headers.get("foo")); tais.close(); } @Test public void paxHeaderEntryWithEmptyValueRemovesKey() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n7 foo=\n" .getBytes(CharsetNames.UTF_8))); assertEquals(0, headers.size()); tais.close(); } @Test public void readPaxHeaderWithEmbeddedNewline() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("line1\nline2\nand3", headers.get("comment")); tais.close(); } @Test public void readNonAsciiPaxHeader() throws Exception { final String ae = "\u00e4"; final String line = "11 path="+ ae + "\n"; assertEquals(11, line.getBytes(CharsetNames.UTF_8).length); final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals(ae, headers.get("path")); tais.close(); } @Test public void workaroundForBrokenTimeHeader() throws Exception { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(getFile("simple-aix-native-tar.tar"))); TarArchiveEntry tae = in.getNextTarEntry(); tae = in.getNextTarEntry(); assertEquals("sample/link-to-txt-file.lnk", tae.getName()); assertEquals(new Date(0), tae.getLastModifiedDate()); assertTrue(tae.isSymbolicLink()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } } @Test public void datePriorToEpochInGNUFormat() throws Exception { datePriorToEpoch("preepoch-star.tar"); } @Test public void datePriorToEpochInPAXFormat() throws Exception { datePriorToEpoch("preepoch-posix.tar"); } private void datePriorToEpoch(final String archive) throws Exception { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(getFile(archive))); final TarArchiveEntry tae = in.getNextTarEntry(); assertEquals("foo", tae.getName()); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.set(1969, 11, 31, 23, 59, 59); cal.set(Calendar.MILLISECOND, 0); assertEquals(cal.getTime(), tae.getLastModifiedDate()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } } @Test public void testCompress197() throws Exception { final TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar"); try { TarArchiveEntry entry = tar.getNextTarEntry(); while (entry != null) { entry = tar.getNextTarEntry(); } } catch (final IOException e) { fail("COMPRESS-197: " + e.getMessage()); } finally { tar.close(); } } @Test public void shouldUseSpecifiedEncodingWhenReadingGNULongNames() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final String encoding = CharsetNames.UTF_16; final String name = "1234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789" + "01234567890\u00e4"; final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos, encoding); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry t = new TarArchiveEntry(name); t.setSize(1); tos.putArchiveEntry(t); tos.write(30); tos.closeArchiveEntry(); tos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); final TarArchiveInputStream tis = new TarArchiveInputStream(bis, encoding); t = tis.getNextTarEntry(); assertEquals(name, t.getName()); tis.close(); } @Test public void shouldConsumeArchiveCompletely() throws Exception { final InputStream is = TarArchiveInputStreamTest.class .getResourceAsStream("/archive_with_trailer.tar"); final TarArchiveInputStream tar = new TarArchiveInputStream(is); while (tar.getNextTarEntry() != null) { // just consume the archive } final byte[] expected = new byte[] { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n' }; final byte[] actual = new byte[expected.length]; is.read(actual); assertArrayEquals(expected, actual); tar.close(); } @Test public void readsArchiveCompletely_COMPRESS245() throws Exception { final InputStream is = TarArchiveInputStreamTest.class .getResourceAsStream("/COMPRESS-245.tar.gz"); try { final InputStream gin = new GZIPInputStream(is); final TarArchiveInputStream tar = new TarArchiveInputStream(gin); int count = 0; TarArchiveEntry entry = tar.getNextTarEntry(); while (entry != null) { count++; entry = tar.getNextTarEntry(); } assertEquals(31, count); tar.close(); } catch (final IOException e) { fail("COMPRESS-245: " + e.getMessage()); } finally { is.close(); } } @Test(expected = IOException.class) public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception { final File dir = mkdir("COMPRESS-279"); final TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar"); FileOutputStream out = null; try { TarArchiveEntry entry = is.getNextTarEntry(); int count = 0; while (entry != null) { out = new FileOutputStream(new File(dir, String.valueOf(count))); IOUtils.copy(is, out); out.close(); out = null; count++; entry = is.getNextTarEntry(); } } finally { is.close(); if (out != null) { out.close(); } rmdir(dir); } } @Test public void shouldReadBigGid() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos); tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); TarArchiveEntry t = new TarArchiveEntry("name"); t.setGroupId(4294967294l); t.setSize(1); tos.putArchiveEntry(t); tos.write(30); tos.closeArchiveEntry(); tos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); final TarArchiveInputStream tis = new TarArchiveInputStream(bis); t = tis.getNextTarEntry(); assertEquals(4294967294l, t.getLongGroupId()); tis.close(); } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-324" */ @Test public void shouldReadGNULongNameEntryWithWrongName() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-324.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890.txt", entry.getName()); } finally { is.close(); } } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-355" */ @Test public void survivesBlankLinesInPaxHeader() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-355.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("package/package.json", entry.getName()); assertNull(is.getNextTarEntry()); } finally { is.close(); } } private TarArchiveInputStream getTestStream(final String name) { return new TarArchiveInputStream( TarArchiveInputStreamTest.class.getResourceAsStream(name)); } }
// You are a professional Java test case writer, please create a test case named `survivesBlankLinesInPaxHeader` for the issue `Compress-COMPRESS-355`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-355 // // ## Issue-Title: // Parsing PAX headers fails with NegativeArraySizeException // // ## Issue-Description: // // The TarArchiveInputStream.parsePaxHeaders method fails with a NegativeArraySizeException when there is an empty line at the end of the headers. // // // The inner loop starts reading the length, but it gets a newline (10) and ends up subtracting '0' (48) from it; the result is a negative length that blows up an attempt to allocate the rest array. // // // I would say that a check to see if ch is less the '0' and break the loop if it is. // // // I used npm pack aws-sdk@2.2.16 to generate a tarball with this issue. // // // // // @Test public void survivesBlankLinesInPaxHeader() throws Exception {
313
/** * @link "https://issues.apache.org/jira/browse/COMPRESS-355" */
37
303
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-355 ## Issue-Title: Parsing PAX headers fails with NegativeArraySizeException ## Issue-Description: The TarArchiveInputStream.parsePaxHeaders method fails with a NegativeArraySizeException when there is an empty line at the end of the headers. The inner loop starts reading the length, but it gets a newline (10) and ends up subtracting '0' (48) from it; the result is a negative length that blows up an attempt to allocate the rest array. I would say that a check to see if ch is less the '0' and break the loop if it is. I used npm pack aws-sdk@2.2.16 to generate a tarball with this issue. ``` You are a professional Java test case writer, please create a test case named `survivesBlankLinesInPaxHeader` for the issue `Compress-COMPRESS-355`, utilizing the provided issue report information and the following function signature. ```java @Test public void survivesBlankLinesInPaxHeader() throws Exception { ```
303
[ "org.apache.commons.compress.archivers.tar.TarArchiveInputStream" ]
2a821ddae469c8d04c524ea3a83eab5940f91705b47262803bd0662867789631
@Test public void survivesBlankLinesInPaxHeader() throws Exception
// You are a professional Java test case writer, please create a test case named `survivesBlankLinesInPaxHeader` for the issue `Compress-COMPRESS-355`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-355 // // ## Issue-Title: // Parsing PAX headers fails with NegativeArraySizeException // // ## Issue-Description: // // The TarArchiveInputStream.parsePaxHeaders method fails with a NegativeArraySizeException when there is an empty line at the end of the headers. // // // The inner loop starts reading the length, but it gets a newline (10) and ends up subtracting '0' (48) from it; the result is a negative length that blows up an attempt to allocate the rest array. // // // I would say that a check to see if ch is less the '0' and break the loop if it is. // // // I used npm pack aws-sdk@2.2.16 to generate a tarball with this issue. // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.tar; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.apache.commons.compress.AbstractTestCase.mkdir; import static org.apache.commons.compress.AbstractTestCase.rmdir; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.Date; import java.util.Map; import java.util.TimeZone; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.utils.CharsetNames; import org.apache.commons.compress.utils.IOUtils; import org.junit.Test; public class TarArchiveInputStreamTest { @Test public void readSimplePaxHeader() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("1321711775.972059463", headers.get("atime")); tais.close(); } @Test public void secondEntryWinsWhenPaxHeaderContainsDuplicateKey() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n11 foo=baz\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("baz", headers.get("foo")); tais.close(); } @Test public void paxHeaderEntryWithEmptyValueRemovesKey() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n7 foo=\n" .getBytes(CharsetNames.UTF_8))); assertEquals(0, headers.size()); tais.close(); } @Test public void readPaxHeaderWithEmbeddedNewline() throws Exception { final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n" .getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals("line1\nline2\nand3", headers.get("comment")); tais.close(); } @Test public void readNonAsciiPaxHeader() throws Exception { final String ae = "\u00e4"; final String line = "11 path="+ ae + "\n"; assertEquals(11, line.getBytes(CharsetNames.UTF_8).length); final InputStream is = new ByteArrayInputStream(new byte[1]); final TarArchiveInputStream tais = new TarArchiveInputStream(is); final Map<String, String> headers = tais .parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8))); assertEquals(1, headers.size()); assertEquals(ae, headers.get("path")); tais.close(); } @Test public void workaroundForBrokenTimeHeader() throws Exception { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(getFile("simple-aix-native-tar.tar"))); TarArchiveEntry tae = in.getNextTarEntry(); tae = in.getNextTarEntry(); assertEquals("sample/link-to-txt-file.lnk", tae.getName()); assertEquals(new Date(0), tae.getLastModifiedDate()); assertTrue(tae.isSymbolicLink()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } } @Test public void datePriorToEpochInGNUFormat() throws Exception { datePriorToEpoch("preepoch-star.tar"); } @Test public void datePriorToEpochInPAXFormat() throws Exception { datePriorToEpoch("preepoch-posix.tar"); } private void datePriorToEpoch(final String archive) throws Exception { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(getFile(archive))); final TarArchiveEntry tae = in.getNextTarEntry(); assertEquals("foo", tae.getName()); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.set(1969, 11, 31, 23, 59, 59); cal.set(Calendar.MILLISECOND, 0); assertEquals(cal.getTime(), tae.getLastModifiedDate()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } } @Test public void testCompress197() throws Exception { final TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar"); try { TarArchiveEntry entry = tar.getNextTarEntry(); while (entry != null) { entry = tar.getNextTarEntry(); } } catch (final IOException e) { fail("COMPRESS-197: " + e.getMessage()); } finally { tar.close(); } } @Test public void shouldUseSpecifiedEncodingWhenReadingGNULongNames() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final String encoding = CharsetNames.UTF_16; final String name = "1234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789" + "01234567890\u00e4"; final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos, encoding); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry t = new TarArchiveEntry(name); t.setSize(1); tos.putArchiveEntry(t); tos.write(30); tos.closeArchiveEntry(); tos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); final TarArchiveInputStream tis = new TarArchiveInputStream(bis, encoding); t = tis.getNextTarEntry(); assertEquals(name, t.getName()); tis.close(); } @Test public void shouldConsumeArchiveCompletely() throws Exception { final InputStream is = TarArchiveInputStreamTest.class .getResourceAsStream("/archive_with_trailer.tar"); final TarArchiveInputStream tar = new TarArchiveInputStream(is); while (tar.getNextTarEntry() != null) { // just consume the archive } final byte[] expected = new byte[] { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n' }; final byte[] actual = new byte[expected.length]; is.read(actual); assertArrayEquals(expected, actual); tar.close(); } @Test public void readsArchiveCompletely_COMPRESS245() throws Exception { final InputStream is = TarArchiveInputStreamTest.class .getResourceAsStream("/COMPRESS-245.tar.gz"); try { final InputStream gin = new GZIPInputStream(is); final TarArchiveInputStream tar = new TarArchiveInputStream(gin); int count = 0; TarArchiveEntry entry = tar.getNextTarEntry(); while (entry != null) { count++; entry = tar.getNextTarEntry(); } assertEquals(31, count); tar.close(); } catch (final IOException e) { fail("COMPRESS-245: " + e.getMessage()); } finally { is.close(); } } @Test(expected = IOException.class) public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception { final File dir = mkdir("COMPRESS-279"); final TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar"); FileOutputStream out = null; try { TarArchiveEntry entry = is.getNextTarEntry(); int count = 0; while (entry != null) { out = new FileOutputStream(new File(dir, String.valueOf(count))); IOUtils.copy(is, out); out.close(); out = null; count++; entry = is.getNextTarEntry(); } } finally { is.close(); if (out != null) { out.close(); } rmdir(dir); } } @Test public void shouldReadBigGid() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos); tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); TarArchiveEntry t = new TarArchiveEntry("name"); t.setGroupId(4294967294l); t.setSize(1); tos.putArchiveEntry(t); tos.write(30); tos.closeArchiveEntry(); tos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); final TarArchiveInputStream tis = new TarArchiveInputStream(bis); t = tis.getNextTarEntry(); assertEquals(4294967294l, t.getLongGroupId()); tis.close(); } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-324" */ @Test public void shouldReadGNULongNameEntryWithWrongName() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-324.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890.txt", entry.getName()); } finally { is.close(); } } /** * @link "https://issues.apache.org/jira/browse/COMPRESS-355" */ @Test public void survivesBlankLinesInPaxHeader() throws Exception { final TarArchiveInputStream is = getTestStream("/COMPRESS-355.tar"); try { final TarArchiveEntry entry = is.getNextTarEntry(); assertEquals("package/package.json", entry.getName()); assertNull(is.getNextTarEntry()); } finally { is.close(); } } private TarArchiveInputStream getTestStream(final String name) { return new TarArchiveInputStream( TarArchiveInputStreamTest.class.getResourceAsStream(name)); } }
public void testUnnamedFunctionStatement() { // Statements parseError("function() {};", "unnamed function statement"); parseError("if (true) { function() {}; }", "unnamed function statement"); parse("function f() {};"); // Expressions parse("(function f() {});"); parse("(function () {});"); }
com.google.javascript.jscomp.parsing.ParserTest::testUnnamedFunctionStatement
test/com/google/javascript/jscomp/parsing/ParserTest.java
781
test/com/google/javascript/jscomp/parsing/ParserTest.java
testUnnamedFunctionStatement
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.parsing; import com.google.common.collect.ImmutableList; import com.google.javascript.jscomp.mozilla.rhino.ScriptRuntime; import com.google.javascript.jscomp.testing.TestErrorReporter; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import java.io.IOException; import java.util.logging.Logger; import java.util.List; public class ParserTest extends BaseJSTypeTestCase { private static final String TRAILING_COMMA_MESSAGE = ScriptRuntime.getMessage0("msg.extra.trailing.comma"); private static final String BAD_PROPERTY_MESSAGE = ScriptRuntime.getMessage0("msg.bad.prop"); private static final String MISSING_GT_MESSAGE = com.google.javascript.rhino.ScriptRuntime.getMessage0( "msg.jsdoc.missing.gt"); private boolean es5mode; @Override protected void setUp() throws Exception { super.setUp(); es5mode = false; } public void testLinenoCharnoAssign1() throws Exception { Node assign = parse("a = b").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assign.getType()); assertEquals(1, assign.getLineno()); assertEquals(2, assign.getCharno()); } public void testLinenoCharnoAssign2() throws Exception { Node assign = parse("\n a.g.h.k = 45").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assign.getType()); assertEquals(2, assign.getLineno()); assertEquals(12, assign.getCharno()); } public void testLinenoCharnoCall() throws Exception { Node call = parse("\n foo(123);").getFirstChild().getFirstChild(); assertEquals(Token.CALL, call.getType()); assertEquals(2, call.getLineno()); assertEquals(4, call.getCharno()); } public void testLinenoCharnoGetProp1() throws Exception { Node getprop = parse("\n foo.bar").getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getprop.getType()); assertEquals(2, getprop.getLineno()); assertEquals(1, getprop.getCharno()); Node name = getprop.getFirstChild().getNext(); assertEquals(Token.STRING, name.getType()); assertEquals(2, name.getLineno()); assertEquals(5, name.getCharno()); } public void testLinenoCharnoGetProp2() throws Exception { Node getprop = parse("\n foo.\nbar").getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getprop.getType()); assertEquals(2, getprop.getLineno()); assertEquals(1, getprop.getCharno()); Node name = getprop.getFirstChild().getNext(); assertEquals(Token.STRING, name.getType()); assertEquals(3, name.getLineno()); assertEquals(0, name.getCharno()); } public void testLinenoCharnoGetelem1() throws Exception { Node call = parse("\n foo[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(2, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetelem2() throws Exception { Node call = parse("\n \n foo()[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(3, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetelem3() throws Exception { Node call = parse("\n \n (8 + kl)[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(3, call.getLineno()); assertEquals(2, call.getCharno()); } public void testLinenoCharnoForComparison() throws Exception { Node lt = parse("for (; i < j;){}").getFirstChild().getFirstChild().getNext(); assertEquals(Token.LT, lt.getType()); assertEquals(1, lt.getLineno()); assertEquals(9, lt.getCharno()); } public void testLinenoCharnoHook() throws Exception { Node n = parse("\n a ? 9 : 0").getFirstChild().getFirstChild(); assertEquals(Token.HOOK, n.getType()); assertEquals(2, n.getLineno()); assertEquals(1, n.getCharno()); } public void testLinenoCharnoArrayLiteral() throws Exception { Node n = parse("\n [8, 9]").getFirstChild().getFirstChild(); assertEquals(Token.ARRAYLIT, n.getType()); assertEquals(2, n.getLineno()); assertEquals(2, n.getCharno()); n = n.getFirstChild(); assertEquals(Token.NUMBER, n.getType()); assertEquals(2, n.getLineno()); assertEquals(3, n.getCharno()); n = n.getNext(); assertEquals(Token.NUMBER, n.getType()); assertEquals(2, n.getLineno()); assertEquals(6, n.getCharno()); } public void testLinenoCharnoObjectLiteral() throws Exception { Node n = parse("\n\n var a = {a:0\n,b :1};") .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, n.getType()); assertEquals(3, n.getLineno()); assertEquals(9, n.getCharno()); Node key = n.getFirstChild(); assertEquals(Token.STRING, key.getType()); assertEquals(3, key.getLineno()); assertEquals(10, key.getCharno()); Node value = key.getFirstChild(); assertEquals(Token.NUMBER, value.getType()); assertEquals(3, value.getLineno()); assertEquals(12, value.getCharno()); key = key.getNext(); assertEquals(Token.STRING, key.getType()); assertEquals(4, key.getLineno()); assertEquals(1, key.getCharno()); value = key.getFirstChild(); assertEquals(Token.NUMBER, value.getType()); assertEquals(4, value.getLineno()); assertEquals(4, value.getCharno()); } public void testLinenoCharnoAdd() throws Exception { testLinenoCharnoBinop("+"); } public void testLinenoCharnoSub() throws Exception { testLinenoCharnoBinop("-"); } public void testLinenoCharnoMul() throws Exception { testLinenoCharnoBinop("*"); } public void testLinenoCharnoDiv() throws Exception { testLinenoCharnoBinop("/"); } public void testLinenoCharnoMod() throws Exception { testLinenoCharnoBinop("%"); } public void testLinenoCharnoShift() throws Exception { testLinenoCharnoBinop("<<"); } public void testLinenoCharnoBinaryAnd() throws Exception { testLinenoCharnoBinop("&"); } public void testLinenoCharnoAnd() throws Exception { testLinenoCharnoBinop("&&"); } public void testLinenoCharnoBinaryOr() throws Exception { testLinenoCharnoBinop("|"); } public void testLinenoCharnoOr() throws Exception { testLinenoCharnoBinop("||"); } public void testLinenoCharnoLt() throws Exception { testLinenoCharnoBinop("<"); } public void testLinenoCharnoLe() throws Exception { testLinenoCharnoBinop("<="); } public void testLinenoCharnoGt() throws Exception { testLinenoCharnoBinop(">"); } public void testLinenoCharnoGe() throws Exception { testLinenoCharnoBinop(">="); } private void testLinenoCharnoBinop(String binop) { Node op = parse("var a = 89 " + binop + " 76").getFirstChild(). getFirstChild().getFirstChild(); assertEquals(1, op.getLineno()); assertEquals(11, op.getCharno()); } public void testJSDocAttachment1() { Node varNode = parse("/** @type number */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment2() { Node varNode = parse("/** @type number */var a,b;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); // First NAME Node nameNode1 = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode1.getType()); assertNull(nameNode1.getJSDocInfo()); // Second NAME Node nameNode2 = nameNode1.getNext(); assertEquals(Token.NAME, nameNode2.getType()); assertNull(nameNode2.getJSDocInfo()); } public void testJSDocAttachment3() { Node assignNode = parse( "/** @type number */goog.FOO = 5;").getFirstChild().getFirstChild(); // ASSIGN assertEquals(Token.ASSIGN, assignNode.getType()); JSDocInfo info = assignNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); } public void testJSDocAttachment4() { Node varNode = parse( "var a, /** @define {number} */b = 5;").getFirstChild(); // ASSIGN assertEquals(Token.VAR, varNode.getType()); assertNull(varNode.getJSDocInfo()); // a Node a = varNode.getFirstChild(); assertNull(a.getJSDocInfo()); // b Node b = a.getNext(); JSDocInfo info = b.getJSDocInfo(); assertNotNull(info); assertTrue(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); } public void testJSDocAttachment5() { Node varNode = parse( "var /** @type number */a, /** @define {number} */b = 5;") .getFirstChild(); // ASSIGN assertEquals(Token.VAR, varNode.getType()); assertNull(varNode.getJSDocInfo()); // a Node a = varNode.getFirstChild(); assertNotNull(a.getJSDocInfo()); JSDocInfo info = a.getJSDocInfo(); assertNotNull(info); assertFalse(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); // b Node b = a.getNext(); info = b.getJSDocInfo(); assertNotNull(info); assertTrue(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); } /** * Tests that a JSDoc comment in an unexpected place of the code does not * propagate to following code due to {@link JSDocInfo} aggregation. */ public void testJSDocAttachment6() throws Exception { Node functionNode = parse( "var a = /** @param {number} index */5;" + "/** @return boolean */function f(index){}") .getFirstChild().getNext(); assertEquals(Token.FUNCTION, functionNode.getType()); JSDocInfo info = functionNode.getJSDocInfo(); assertNotNull(info); assertFalse(info.hasParameter("index")); assertTrue(info.hasReturnType()); } public void testJSDocAttachment7() { Node varNode = parse("/** */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment8() { Node varNode = parse("/** x */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment9() { Node varNode = parse("/** \n x */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment10() { Node varNode = parse("/** x\n */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment11() { Node varNode = parse("/** @type {{x : number, 'y' : string, z}} */var a;") .getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(createRecordTypeBuilder(). addProperty("x", NUMBER_TYPE, null). addProperty("y", STRING_TYPE, null). addProperty("z", UNKNOWN_TYPE, null). build(), info.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment12() { Node varNode = parse("var a = {/** @type {Object} */ b: c};") .getFirstChild(); Node objectLitNode = varNode.getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, objectLitNode.getType()); assertNotNull(objectLitNode.getFirstChild().getJSDocInfo()); } public void testJSDocAttachment13() { Node varNode = parse("/** foo */ var a;").getFirstChild(); assertNotNull(varNode.getJSDocInfo()); } public void testJSDocAttachment14() { Node varNode = parse("/** */ var a;").getFirstChild(); assertNull(varNode.getJSDocInfo()); } public void testJSDocAttachment15() { Node varNode = parse("/** \n * \n */ var a;").getFirstChild(); assertNull(varNode.getJSDocInfo()); } public void testIncorrectJSDocDoesNotAlterJSParsing1() throws Exception { assertNodeEquality( parse("var a = [1,2]"), parse("/** @type Array.<number*/var a = [1,2]", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing2() throws Exception { assertNodeEquality( parse("var a = [1,2]"), parse("/** @type {Array.<number}*/var a = [1,2]", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing3() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param {Array.<number} nums */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing4() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @return boolean */" + "C.prototype.say=function(nums) {alert(nums.join(','));};")); } public void testIncorrectJSDocDoesNotAlterJSParsing5() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param boolean this is some string*/" + "C.prototype.say=function(nums) {alert(nums.join(','));};")); } public void testIncorrectJSDocDoesNotAlterJSParsing6() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param {bool!*%E$} */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "expected closing }", "expecting a variable name in a @param tag")); } public void testIncorrectJSDocDoesNotAlterJSParsing7() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @see */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "@see tag missing description")); } public void testIncorrectJSDocDoesNotAlterJSParsing8() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @author */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "@author tag missing author")); } public void testIncorrectJSDocDoesNotAlterJSParsing9() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @someillegaltag */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "illegal use of unknown JSDoc tag \"someillegaltag\";" + " ignoring it")); } public void testUnescapedSlashInRegexpCharClass() throws Exception { // The tokenizer without the fix for this bug throws an error. parse("var foo = /[/]/;"); parse("var foo = /[hi there/]/;"); parse("var foo = /[/yo dude]/;"); parse("var foo = /\\/[@#$/watashi/wa/suteevu/desu]/;"); } private void assertNodeEquality(Node expected, Node found) { String message = expected.checkTreeEquals(found); if (message != null) { fail(message); } } @SuppressWarnings("unchecked") public void testParse() { Node a = Node.newString(Token.NAME, "a"); a.addChildToFront(Node.newString(Token.NAME, "b")); List<ParserResult> testCases = ImmutableList.of( new ParserResult( "3;", createScript(new Node(Token.EXPR_RESULT, Node.newNumber(3.0)))), new ParserResult( "var a = b;", createScript(new Node(Token.VAR, a))), new ParserResult( "\"hell\\\no\\ world\\\n\\\n!\"", createScript(new Node(Token.EXPR_RESULT, Node.newString(Token.STRING, "hello world!"))))); for (ParserResult testCase : testCases) { assertNodeEquality(testCase.node, parse(testCase.code)); } } private Node createScript(Node n) { Node script = new Node(Token.SCRIPT); script.addChildToBack(n); return script; } public void testTrailingCommaWarning1() { parse("var a = ['foo', 'bar'];"); } public void testTrailingCommaWarning2() { parse("var a = ['foo',,'bar'];"); } public void testTrailingCommaWarning3() { parse("var a = ['foo', 'bar',];", TRAILING_COMMA_MESSAGE); } public void testTrailingCommaWarning4() { parse("var a = [,];", TRAILING_COMMA_MESSAGE); } public void testTrailingCommaWarning5() { parse("var a = {'foo': 'bar'};"); } public void testTrailingCommaWarning6() { parse("var a = {'foo': 'bar',};", TRAILING_COMMA_MESSAGE); } public void testTrailingCommaWarning7() { parseError("var a = {,};", BAD_PROPERTY_MESSAGE); } public void testCatchClauseForbidden() { parseError("try { } catch (e if true) {}", "Catch clauses are not supported"); } public void testConstForbidden() { parseError("const x = 3;", "Unsupported syntax: CONST"); } public void testDestructuringAssignForbidden() { parseError("var [x, y] = foo();", "destructuring assignment forbidden"); } public void testDestructuringAssignForbidden2() { parseError("var {x, y} = foo();", "missing : after property id"); } public void testDestructuringAssignForbidden3() { parseError("var {x: x, y: y} = foo();", "destructuring assignment forbidden"); } public void testDestructuringAssignForbidden4() { parseError("[x, y] = foo();", "destructuring assignment forbidden", "invalid assignment target"); } public void testLetForbidden() { parseError("function f() { let (x = 3) { alert(x); }; }", "missing ; before statement", "syntax error"); } public void testYieldForbidden() { parseError("function f() { yield 3; }", "missing ; before statement"); } public void testBracelessFunctionForbidden() { parseError("var sq = function(x) x * x;", "missing { before function body"); } public void testGeneratorsForbidden() { parseError("var i = (x for (x in obj));", "missing ) in parenthetical"); } public void testGettersForbidden1() { parseError("var x = {get foo() { return 3; }};", "getters are not supported in Internet Explorer"); } public void testGettersForbidden2() { parseError("var x = {get foo bar() { return 3; }};", "invalid property id"); } public void testGettersForbidden3() { parseError("var x = {a getter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testGettersForbidden4() { parseError("var x = {\"a\" getter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testGettersForbidden5() { parseError("var x = {a: 2, get foo() { return 3; }};", "getters are not supported in Internet Explorer"); } public void testSettersForbidden() { parseError("var x = {set foo() { return 3; }};", "setters are not supported in Internet Explorer"); } public void testSettersForbidden2() { parseError("var x = {a setter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testFileOverviewJSDoc1() { Node n = parse("/** @fileoverview Hi mom! */ function Foo() {}"); assertEquals(Token.FUNCTION, n.getFirstChild().getType()); assertTrue(n.getJSDocInfo() != null); assertNull(n.getFirstChild().getJSDocInfo()); assertEquals("Hi mom!", n.getJSDocInfo().getFileOverview()); } public void testFileOverviewJSDocDoesNotHoseParsing() { assertEquals( Token.FUNCTION, parse("/** @fileoverview Hi mom! \n */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview Hi mom! \n * * * */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview \n * x */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview \n * x \n */ function Foo() {}") .getFirstChild().getType()); } public void testFileOverviewJSDoc2() { Node n = parse("/** @fileoverview Hi mom! */ " + "/** @constructor */ function Foo() {}"); assertTrue(n.getJSDocInfo() != null); assertEquals("Hi mom!", n.getJSDocInfo().getFileOverview()); assertTrue(n.getFirstChild().getJSDocInfo() != null); assertFalse(n.getFirstChild().getJSDocInfo().hasFileOverview()); assertTrue(n.getFirstChild().getJSDocInfo().isConstructor()); } public void testObjectLiteralDoc1() { Node n = parse("var x = {/** @type {number} */ 1: 2};"); Node objectLit = n.getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, objectLit.getType()); Node number = objectLit.getFirstChild(); assertEquals(Token.NUMBER, number.getType()); assertNotNull(number.getJSDocInfo()); } public void testDuplicatedParam() { parse("function foo(x, x) {}", "Duplicate parameter name \"x\"."); } public void testGetter() { this.es5mode = false; parseError("var x = {get a(){}};", "getters are not supported in Internet Explorer"); this.es5mode = true; parse("var x = {get a(){}};"); parseError("var x = {get a(b){}};", "getters may not have parameters"); } public void testSetter() { this.es5mode = false; parseError("var x = {set a(x){}};", "setters are not supported in Internet Explorer"); this.es5mode = true; parse("var x = {set a(x){}};"); parseError("var x = {set a(){}};", "setters must have exactly one parameter"); } public void testLamestWarningEver() { // This used to be a warning. parse("var x = /** @type {undefined} */ (y);"); parse("var x = /** @type {void} */ (y);"); } public void testUnfinishedComment() { parseError("/** this is a comment ", "unterminated comment"); } public void testParseBlockDescription() { Node n = parse("/** This is a variable. */ var x;"); Node var = n.getFirstChild(); assertNotNull(var.getJSDocInfo()); assertEquals("This is a variable.", var.getJSDocInfo().getBlockDescription()); } public void testUnnamedFunctionStatement() { // Statements parseError("function() {};", "unnamed function statement"); parseError("if (true) { function() {}; }", "unnamed function statement"); parse("function f() {};"); // Expressions parse("(function f() {});"); parse("(function () {});"); } private void parseError(String string, String... errors) { TestErrorReporter testErrorReporter = new TestErrorReporter(errors, null); Node script = null; try { script = ParserRunner.parse( "input", string, ParserRunner.createConfig(true, es5mode, false), testErrorReporter, Logger.getAnonymousLogger()); } catch (IOException e) { throw new RuntimeException(e); } // verifying that all warnings were seen assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); } private Node parse(String string, String... warnings) { TestErrorReporter testErrorReporter = new TestErrorReporter(null, warnings); Node script = null; try { script = ParserRunner.parse( "input", string, ParserRunner.createConfig(true, es5mode, false), testErrorReporter, Logger.getAnonymousLogger()); } catch (IOException e) { throw new RuntimeException(e); } // verifying that all warnings were seen assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; } private static class ParserResult { private final String code; private final Node node; private ParserResult(String code, Node node) { this.code = code; this.node = node; } } }
// You are a professional Java test case writer, please create a test case named `testUnnamedFunctionStatement` for the issue `Closure-251`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-251 // // ## Issue-Title: // An unnamed function statement statements should generate a parse error // // ## Issue-Description: // An unnamed function statement statements should generate a parse error, but it does not, for example: // // function () {}; // // Note: Unnamed function expression are legal: // // (function(){}); // // public void testUnnamedFunctionStatement() {
781
81
773
test/com/google/javascript/jscomp/parsing/ParserTest.java
test
```markdown ## Issue-ID: Closure-251 ## Issue-Title: An unnamed function statement statements should generate a parse error ## Issue-Description: An unnamed function statement statements should generate a parse error, but it does not, for example: function () {}; Note: Unnamed function expression are legal: (function(){}); ``` You are a professional Java test case writer, please create a test case named `testUnnamedFunctionStatement` for the issue `Closure-251`, utilizing the provided issue report information and the following function signature. ```java public void testUnnamedFunctionStatement() { ```
773
[ "com.google.javascript.jscomp.parsing.IRFactory" ]
2afaabc62f10edb58cb2b2597ab9840a7284d1e017bd1944b2c812bf77e33789
public void testUnnamedFunctionStatement()
// You are a professional Java test case writer, please create a test case named `testUnnamedFunctionStatement` for the issue `Closure-251`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-251 // // ## Issue-Title: // An unnamed function statement statements should generate a parse error // // ## Issue-Description: // An unnamed function statement statements should generate a parse error, but it does not, for example: // // function () {}; // // Note: Unnamed function expression are legal: // // (function(){}); // //
Closure
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.parsing; import com.google.common.collect.ImmutableList; import com.google.javascript.jscomp.mozilla.rhino.ScriptRuntime; import com.google.javascript.jscomp.testing.TestErrorReporter; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import java.io.IOException; import java.util.logging.Logger; import java.util.List; public class ParserTest extends BaseJSTypeTestCase { private static final String TRAILING_COMMA_MESSAGE = ScriptRuntime.getMessage0("msg.extra.trailing.comma"); private static final String BAD_PROPERTY_MESSAGE = ScriptRuntime.getMessage0("msg.bad.prop"); private static final String MISSING_GT_MESSAGE = com.google.javascript.rhino.ScriptRuntime.getMessage0( "msg.jsdoc.missing.gt"); private boolean es5mode; @Override protected void setUp() throws Exception { super.setUp(); es5mode = false; } public void testLinenoCharnoAssign1() throws Exception { Node assign = parse("a = b").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assign.getType()); assertEquals(1, assign.getLineno()); assertEquals(2, assign.getCharno()); } public void testLinenoCharnoAssign2() throws Exception { Node assign = parse("\n a.g.h.k = 45").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assign.getType()); assertEquals(2, assign.getLineno()); assertEquals(12, assign.getCharno()); } public void testLinenoCharnoCall() throws Exception { Node call = parse("\n foo(123);").getFirstChild().getFirstChild(); assertEquals(Token.CALL, call.getType()); assertEquals(2, call.getLineno()); assertEquals(4, call.getCharno()); } public void testLinenoCharnoGetProp1() throws Exception { Node getprop = parse("\n foo.bar").getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getprop.getType()); assertEquals(2, getprop.getLineno()); assertEquals(1, getprop.getCharno()); Node name = getprop.getFirstChild().getNext(); assertEquals(Token.STRING, name.getType()); assertEquals(2, name.getLineno()); assertEquals(5, name.getCharno()); } public void testLinenoCharnoGetProp2() throws Exception { Node getprop = parse("\n foo.\nbar").getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getprop.getType()); assertEquals(2, getprop.getLineno()); assertEquals(1, getprop.getCharno()); Node name = getprop.getFirstChild().getNext(); assertEquals(Token.STRING, name.getType()); assertEquals(3, name.getLineno()); assertEquals(0, name.getCharno()); } public void testLinenoCharnoGetelem1() throws Exception { Node call = parse("\n foo[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(2, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetelem2() throws Exception { Node call = parse("\n \n foo()[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(3, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetelem3() throws Exception { Node call = parse("\n \n (8 + kl)[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(3, call.getLineno()); assertEquals(2, call.getCharno()); } public void testLinenoCharnoForComparison() throws Exception { Node lt = parse("for (; i < j;){}").getFirstChild().getFirstChild().getNext(); assertEquals(Token.LT, lt.getType()); assertEquals(1, lt.getLineno()); assertEquals(9, lt.getCharno()); } public void testLinenoCharnoHook() throws Exception { Node n = parse("\n a ? 9 : 0").getFirstChild().getFirstChild(); assertEquals(Token.HOOK, n.getType()); assertEquals(2, n.getLineno()); assertEquals(1, n.getCharno()); } public void testLinenoCharnoArrayLiteral() throws Exception { Node n = parse("\n [8, 9]").getFirstChild().getFirstChild(); assertEquals(Token.ARRAYLIT, n.getType()); assertEquals(2, n.getLineno()); assertEquals(2, n.getCharno()); n = n.getFirstChild(); assertEquals(Token.NUMBER, n.getType()); assertEquals(2, n.getLineno()); assertEquals(3, n.getCharno()); n = n.getNext(); assertEquals(Token.NUMBER, n.getType()); assertEquals(2, n.getLineno()); assertEquals(6, n.getCharno()); } public void testLinenoCharnoObjectLiteral() throws Exception { Node n = parse("\n\n var a = {a:0\n,b :1};") .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, n.getType()); assertEquals(3, n.getLineno()); assertEquals(9, n.getCharno()); Node key = n.getFirstChild(); assertEquals(Token.STRING, key.getType()); assertEquals(3, key.getLineno()); assertEquals(10, key.getCharno()); Node value = key.getFirstChild(); assertEquals(Token.NUMBER, value.getType()); assertEquals(3, value.getLineno()); assertEquals(12, value.getCharno()); key = key.getNext(); assertEquals(Token.STRING, key.getType()); assertEquals(4, key.getLineno()); assertEquals(1, key.getCharno()); value = key.getFirstChild(); assertEquals(Token.NUMBER, value.getType()); assertEquals(4, value.getLineno()); assertEquals(4, value.getCharno()); } public void testLinenoCharnoAdd() throws Exception { testLinenoCharnoBinop("+"); } public void testLinenoCharnoSub() throws Exception { testLinenoCharnoBinop("-"); } public void testLinenoCharnoMul() throws Exception { testLinenoCharnoBinop("*"); } public void testLinenoCharnoDiv() throws Exception { testLinenoCharnoBinop("/"); } public void testLinenoCharnoMod() throws Exception { testLinenoCharnoBinop("%"); } public void testLinenoCharnoShift() throws Exception { testLinenoCharnoBinop("<<"); } public void testLinenoCharnoBinaryAnd() throws Exception { testLinenoCharnoBinop("&"); } public void testLinenoCharnoAnd() throws Exception { testLinenoCharnoBinop("&&"); } public void testLinenoCharnoBinaryOr() throws Exception { testLinenoCharnoBinop("|"); } public void testLinenoCharnoOr() throws Exception { testLinenoCharnoBinop("||"); } public void testLinenoCharnoLt() throws Exception { testLinenoCharnoBinop("<"); } public void testLinenoCharnoLe() throws Exception { testLinenoCharnoBinop("<="); } public void testLinenoCharnoGt() throws Exception { testLinenoCharnoBinop(">"); } public void testLinenoCharnoGe() throws Exception { testLinenoCharnoBinop(">="); } private void testLinenoCharnoBinop(String binop) { Node op = parse("var a = 89 " + binop + " 76").getFirstChild(). getFirstChild().getFirstChild(); assertEquals(1, op.getLineno()); assertEquals(11, op.getCharno()); } public void testJSDocAttachment1() { Node varNode = parse("/** @type number */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment2() { Node varNode = parse("/** @type number */var a,b;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); // First NAME Node nameNode1 = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode1.getType()); assertNull(nameNode1.getJSDocInfo()); // Second NAME Node nameNode2 = nameNode1.getNext(); assertEquals(Token.NAME, nameNode2.getType()); assertNull(nameNode2.getJSDocInfo()); } public void testJSDocAttachment3() { Node assignNode = parse( "/** @type number */goog.FOO = 5;").getFirstChild().getFirstChild(); // ASSIGN assertEquals(Token.ASSIGN, assignNode.getType()); JSDocInfo info = assignNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); } public void testJSDocAttachment4() { Node varNode = parse( "var a, /** @define {number} */b = 5;").getFirstChild(); // ASSIGN assertEquals(Token.VAR, varNode.getType()); assertNull(varNode.getJSDocInfo()); // a Node a = varNode.getFirstChild(); assertNull(a.getJSDocInfo()); // b Node b = a.getNext(); JSDocInfo info = b.getJSDocInfo(); assertNotNull(info); assertTrue(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); } public void testJSDocAttachment5() { Node varNode = parse( "var /** @type number */a, /** @define {number} */b = 5;") .getFirstChild(); // ASSIGN assertEquals(Token.VAR, varNode.getType()); assertNull(varNode.getJSDocInfo()); // a Node a = varNode.getFirstChild(); assertNotNull(a.getJSDocInfo()); JSDocInfo info = a.getJSDocInfo(); assertNotNull(info); assertFalse(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); // b Node b = a.getNext(); info = b.getJSDocInfo(); assertNotNull(info); assertTrue(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); } /** * Tests that a JSDoc comment in an unexpected place of the code does not * propagate to following code due to {@link JSDocInfo} aggregation. */ public void testJSDocAttachment6() throws Exception { Node functionNode = parse( "var a = /** @param {number} index */5;" + "/** @return boolean */function f(index){}") .getFirstChild().getNext(); assertEquals(Token.FUNCTION, functionNode.getType()); JSDocInfo info = functionNode.getJSDocInfo(); assertNotNull(info); assertFalse(info.hasParameter("index")); assertTrue(info.hasReturnType()); } public void testJSDocAttachment7() { Node varNode = parse("/** */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment8() { Node varNode = parse("/** x */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment9() { Node varNode = parse("/** \n x */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment10() { Node varNode = parse("/** x\n */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment11() { Node varNode = parse("/** @type {{x : number, 'y' : string, z}} */var a;") .getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(createRecordTypeBuilder(). addProperty("x", NUMBER_TYPE, null). addProperty("y", STRING_TYPE, null). addProperty("z", UNKNOWN_TYPE, null). build(), info.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment12() { Node varNode = parse("var a = {/** @type {Object} */ b: c};") .getFirstChild(); Node objectLitNode = varNode.getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, objectLitNode.getType()); assertNotNull(objectLitNode.getFirstChild().getJSDocInfo()); } public void testJSDocAttachment13() { Node varNode = parse("/** foo */ var a;").getFirstChild(); assertNotNull(varNode.getJSDocInfo()); } public void testJSDocAttachment14() { Node varNode = parse("/** */ var a;").getFirstChild(); assertNull(varNode.getJSDocInfo()); } public void testJSDocAttachment15() { Node varNode = parse("/** \n * \n */ var a;").getFirstChild(); assertNull(varNode.getJSDocInfo()); } public void testIncorrectJSDocDoesNotAlterJSParsing1() throws Exception { assertNodeEquality( parse("var a = [1,2]"), parse("/** @type Array.<number*/var a = [1,2]", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing2() throws Exception { assertNodeEquality( parse("var a = [1,2]"), parse("/** @type {Array.<number}*/var a = [1,2]", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing3() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param {Array.<number} nums */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing4() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @return boolean */" + "C.prototype.say=function(nums) {alert(nums.join(','));};")); } public void testIncorrectJSDocDoesNotAlterJSParsing5() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param boolean this is some string*/" + "C.prototype.say=function(nums) {alert(nums.join(','));};")); } public void testIncorrectJSDocDoesNotAlterJSParsing6() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param {bool!*%E$} */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "expected closing }", "expecting a variable name in a @param tag")); } public void testIncorrectJSDocDoesNotAlterJSParsing7() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @see */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "@see tag missing description")); } public void testIncorrectJSDocDoesNotAlterJSParsing8() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @author */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "@author tag missing author")); } public void testIncorrectJSDocDoesNotAlterJSParsing9() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @someillegaltag */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "illegal use of unknown JSDoc tag \"someillegaltag\";" + " ignoring it")); } public void testUnescapedSlashInRegexpCharClass() throws Exception { // The tokenizer without the fix for this bug throws an error. parse("var foo = /[/]/;"); parse("var foo = /[hi there/]/;"); parse("var foo = /[/yo dude]/;"); parse("var foo = /\\/[@#$/watashi/wa/suteevu/desu]/;"); } private void assertNodeEquality(Node expected, Node found) { String message = expected.checkTreeEquals(found); if (message != null) { fail(message); } } @SuppressWarnings("unchecked") public void testParse() { Node a = Node.newString(Token.NAME, "a"); a.addChildToFront(Node.newString(Token.NAME, "b")); List<ParserResult> testCases = ImmutableList.of( new ParserResult( "3;", createScript(new Node(Token.EXPR_RESULT, Node.newNumber(3.0)))), new ParserResult( "var a = b;", createScript(new Node(Token.VAR, a))), new ParserResult( "\"hell\\\no\\ world\\\n\\\n!\"", createScript(new Node(Token.EXPR_RESULT, Node.newString(Token.STRING, "hello world!"))))); for (ParserResult testCase : testCases) { assertNodeEquality(testCase.node, parse(testCase.code)); } } private Node createScript(Node n) { Node script = new Node(Token.SCRIPT); script.addChildToBack(n); return script; } public void testTrailingCommaWarning1() { parse("var a = ['foo', 'bar'];"); } public void testTrailingCommaWarning2() { parse("var a = ['foo',,'bar'];"); } public void testTrailingCommaWarning3() { parse("var a = ['foo', 'bar',];", TRAILING_COMMA_MESSAGE); } public void testTrailingCommaWarning4() { parse("var a = [,];", TRAILING_COMMA_MESSAGE); } public void testTrailingCommaWarning5() { parse("var a = {'foo': 'bar'};"); } public void testTrailingCommaWarning6() { parse("var a = {'foo': 'bar',};", TRAILING_COMMA_MESSAGE); } public void testTrailingCommaWarning7() { parseError("var a = {,};", BAD_PROPERTY_MESSAGE); } public void testCatchClauseForbidden() { parseError("try { } catch (e if true) {}", "Catch clauses are not supported"); } public void testConstForbidden() { parseError("const x = 3;", "Unsupported syntax: CONST"); } public void testDestructuringAssignForbidden() { parseError("var [x, y] = foo();", "destructuring assignment forbidden"); } public void testDestructuringAssignForbidden2() { parseError("var {x, y} = foo();", "missing : after property id"); } public void testDestructuringAssignForbidden3() { parseError("var {x: x, y: y} = foo();", "destructuring assignment forbidden"); } public void testDestructuringAssignForbidden4() { parseError("[x, y] = foo();", "destructuring assignment forbidden", "invalid assignment target"); } public void testLetForbidden() { parseError("function f() { let (x = 3) { alert(x); }; }", "missing ; before statement", "syntax error"); } public void testYieldForbidden() { parseError("function f() { yield 3; }", "missing ; before statement"); } public void testBracelessFunctionForbidden() { parseError("var sq = function(x) x * x;", "missing { before function body"); } public void testGeneratorsForbidden() { parseError("var i = (x for (x in obj));", "missing ) in parenthetical"); } public void testGettersForbidden1() { parseError("var x = {get foo() { return 3; }};", "getters are not supported in Internet Explorer"); } public void testGettersForbidden2() { parseError("var x = {get foo bar() { return 3; }};", "invalid property id"); } public void testGettersForbidden3() { parseError("var x = {a getter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testGettersForbidden4() { parseError("var x = {\"a\" getter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testGettersForbidden5() { parseError("var x = {a: 2, get foo() { return 3; }};", "getters are not supported in Internet Explorer"); } public void testSettersForbidden() { parseError("var x = {set foo() { return 3; }};", "setters are not supported in Internet Explorer"); } public void testSettersForbidden2() { parseError("var x = {a setter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testFileOverviewJSDoc1() { Node n = parse("/** @fileoverview Hi mom! */ function Foo() {}"); assertEquals(Token.FUNCTION, n.getFirstChild().getType()); assertTrue(n.getJSDocInfo() != null); assertNull(n.getFirstChild().getJSDocInfo()); assertEquals("Hi mom!", n.getJSDocInfo().getFileOverview()); } public void testFileOverviewJSDocDoesNotHoseParsing() { assertEquals( Token.FUNCTION, parse("/** @fileoverview Hi mom! \n */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview Hi mom! \n * * * */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview \n * x */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview \n * x \n */ function Foo() {}") .getFirstChild().getType()); } public void testFileOverviewJSDoc2() { Node n = parse("/** @fileoverview Hi mom! */ " + "/** @constructor */ function Foo() {}"); assertTrue(n.getJSDocInfo() != null); assertEquals("Hi mom!", n.getJSDocInfo().getFileOverview()); assertTrue(n.getFirstChild().getJSDocInfo() != null); assertFalse(n.getFirstChild().getJSDocInfo().hasFileOverview()); assertTrue(n.getFirstChild().getJSDocInfo().isConstructor()); } public void testObjectLiteralDoc1() { Node n = parse("var x = {/** @type {number} */ 1: 2};"); Node objectLit = n.getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, objectLit.getType()); Node number = objectLit.getFirstChild(); assertEquals(Token.NUMBER, number.getType()); assertNotNull(number.getJSDocInfo()); } public void testDuplicatedParam() { parse("function foo(x, x) {}", "Duplicate parameter name \"x\"."); } public void testGetter() { this.es5mode = false; parseError("var x = {get a(){}};", "getters are not supported in Internet Explorer"); this.es5mode = true; parse("var x = {get a(){}};"); parseError("var x = {get a(b){}};", "getters may not have parameters"); } public void testSetter() { this.es5mode = false; parseError("var x = {set a(x){}};", "setters are not supported in Internet Explorer"); this.es5mode = true; parse("var x = {set a(x){}};"); parseError("var x = {set a(){}};", "setters must have exactly one parameter"); } public void testLamestWarningEver() { // This used to be a warning. parse("var x = /** @type {undefined} */ (y);"); parse("var x = /** @type {void} */ (y);"); } public void testUnfinishedComment() { parseError("/** this is a comment ", "unterminated comment"); } public void testParseBlockDescription() { Node n = parse("/** This is a variable. */ var x;"); Node var = n.getFirstChild(); assertNotNull(var.getJSDocInfo()); assertEquals("This is a variable.", var.getJSDocInfo().getBlockDescription()); } public void testUnnamedFunctionStatement() { // Statements parseError("function() {};", "unnamed function statement"); parseError("if (true) { function() {}; }", "unnamed function statement"); parse("function f() {};"); // Expressions parse("(function f() {});"); parse("(function () {});"); } private void parseError(String string, String... errors) { TestErrorReporter testErrorReporter = new TestErrorReporter(errors, null); Node script = null; try { script = ParserRunner.parse( "input", string, ParserRunner.createConfig(true, es5mode, false), testErrorReporter, Logger.getAnonymousLogger()); } catch (IOException e) { throw new RuntimeException(e); } // verifying that all warnings were seen assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); } private Node parse(String string, String... warnings) { TestErrorReporter testErrorReporter = new TestErrorReporter(null, warnings); Node script = null; try { script = ParserRunner.parse( "input", string, ParserRunner.createConfig(true, es5mode, false), testErrorReporter, Logger.getAnonymousLogger()); } catch (IOException e) { throw new RuntimeException(e); } // verifying that all warnings were seen assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; } private static class ParserResult { private final String code; private final Node node; private ParserResult(String code, Node node) { this.code = code; this.node = node; } } }
@Test(expected=TooManyEvaluationsException.class) public void testIssue631() { final UnivariateRealFunction f = new UnivariateRealFunction() { /** {@inheritDoc} */ public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; final UnivariateRealSolver solver = new RegulaFalsiSolver(); final double root = solver.solve(3624, f, 1, 10); Assert.assertEquals(3.4341896575482003, root, 1e-15); }
org.apache.commons.math.analysis.solvers.RegulaFalsiSolverTest::testIssue631
src/test/java/org/apache/commons/math/analysis/solvers/RegulaFalsiSolverTest.java
55
src/test/java/org/apache/commons/math/analysis/solvers/RegulaFalsiSolverTest.java
testIssue631
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.solvers; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.exception.TooManyEvaluationsException; import org.junit.Test; import org.junit.Assert; /** * Test case for {@link RegulaFalsiSolver Regula Falsi} solver. * * @version $Id$ */ public final class RegulaFalsiSolverTest extends BaseSecantSolverAbstractTest { /** {@inheritDoc} */ protected UnivariateRealSolver getSolver() { return new RegulaFalsiSolver(); } /** {@inheritDoc} */ protected int[] getQuinticEvalCounts() { // While the Regula Falsi method guarantees convergence, convergence // may be extremely slow. The last test case does not converge within // even a million iterations. As such, it was disabled. return new int[] {3, 7, 8, 19, 18, 11, 67, 55, 288, 151, -1}; } @Test(expected=TooManyEvaluationsException.class) public void testIssue631() { final UnivariateRealFunction f = new UnivariateRealFunction() { /** {@inheritDoc} */ public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; final UnivariateRealSolver solver = new RegulaFalsiSolver(); final double root = solver.solve(3624, f, 1, 10); Assert.assertEquals(3.4341896575482003, root, 1e-15); } }
// You are a professional Java test case writer, please create a test case named `testIssue631` for the issue `Math-MATH-631`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-631 // // ## Issue-Title: // "RegulaFalsiSolver" failure // // ## Issue-Description: // // The following unit test: // // // // // ``` // @Test // public void testBug() { // final UnivariateRealFunction f = new UnivariateRealFunction() { // @Override // public double value(double x) { // return Math.exp(x) - Math.pow(Math.PI, 3.0); // } // }; // // UnivariateRealSolver solver = new RegulaFalsiSolver(); // double root = solver.solve(100, f, 1, 10); // } // // ``` // // // fails with // // // // // ``` // illegal state: maximal count (100) exceeded: evaluations // // ``` // // // Using "PegasusSolver", the answer is found after 17 evaluations. // // // // // @Test(expected=TooManyEvaluationsException.class) public void testIssue631() {
55
50
43
src/test/java/org/apache/commons/math/analysis/solvers/RegulaFalsiSolverTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-631 ## Issue-Title: "RegulaFalsiSolver" failure ## Issue-Description: The following unit test: ``` @Test public void testBug() { final UnivariateRealFunction f = new UnivariateRealFunction() { @Override public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; UnivariateRealSolver solver = new RegulaFalsiSolver(); double root = solver.solve(100, f, 1, 10); } ``` fails with ``` illegal state: maximal count (100) exceeded: evaluations ``` Using "PegasusSolver", the answer is found after 17 evaluations. ``` You are a professional Java test case writer, please create a test case named `testIssue631` for the issue `Math-MATH-631`, utilizing the provided issue report information and the following function signature. ```java @Test(expected=TooManyEvaluationsException.class) public void testIssue631() { ```
43
[ "org.apache.commons.math.analysis.solvers.BaseSecantSolver" ]
2b1591dc177aeaa4fe01f19febd23a25f69aa1edc5d0a1cfd4d5d6fb0eeffee9
@Test(expected=TooManyEvaluationsException.class) public void testIssue631()
// You are a professional Java test case writer, please create a test case named `testIssue631` for the issue `Math-MATH-631`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-631 // // ## Issue-Title: // "RegulaFalsiSolver" failure // // ## Issue-Description: // // The following unit test: // // // // // ``` // @Test // public void testBug() { // final UnivariateRealFunction f = new UnivariateRealFunction() { // @Override // public double value(double x) { // return Math.exp(x) - Math.pow(Math.PI, 3.0); // } // }; // // UnivariateRealSolver solver = new RegulaFalsiSolver(); // double root = solver.solve(100, f, 1, 10); // } // // ``` // // // fails with // // // // // ``` // illegal state: maximal count (100) exceeded: evaluations // // ``` // // // Using "PegasusSolver", the answer is found after 17 evaluations. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.solvers; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.exception.TooManyEvaluationsException; import org.junit.Test; import org.junit.Assert; /** * Test case for {@link RegulaFalsiSolver Regula Falsi} solver. * * @version $Id$ */ public final class RegulaFalsiSolverTest extends BaseSecantSolverAbstractTest { /** {@inheritDoc} */ protected UnivariateRealSolver getSolver() { return new RegulaFalsiSolver(); } /** {@inheritDoc} */ protected int[] getQuinticEvalCounts() { // While the Regula Falsi method guarantees convergence, convergence // may be extremely slow. The last test case does not converge within // even a million iterations. As such, it was disabled. return new int[] {3, 7, 8, 19, 18, 11, 67, 55, 288, 151, -1}; } @Test(expected=TooManyEvaluationsException.class) public void testIssue631() { final UnivariateRealFunction f = new UnivariateRealFunction() { /** {@inheritDoc} */ public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; final UnivariateRealSolver solver = new RegulaFalsiSolver(); final double root = solver.solve(3624, f, 1, 10); Assert.assertEquals(3.4341896575482003, root, 1e-15); } }
public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); }
com.google.javascript.jscomp.TypeCheckTest::testBackwardsTypedefUse1
test/com/google/javascript/jscomp/TypeCheckTest.java
2,614
test/com/google/javascript/jscomp/TypeCheckTest.java
testBackwardsTypedefUse1
/* * Copyright 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, new DefaultCodingConvention()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ foo()--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck7() throws Exception { testTypes("function foo() {delete 'abc';}", TypeCheck.BAD_DELETE); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Parse error. variable length argument must be " + "last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return number */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return string */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return string */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return boolean */" + "function f(b) { if (u()) { b = null; } return b; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return string */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return number*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateLocalVarDecl() throws Exception { testTypes( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", "variable x redefined with type string, " + "original definition at [testcode]:2 with type number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (this:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { /** TODO(user): This is not exactly correct yet. The var itself is nullable. */ testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE). restrictByNotNullOrUndefined().toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (this:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (this:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testTypes("/** @enum */var a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum9() throws Exception { testTypes( "var goog = {};" + "/** @enum */goog.a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|Array)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Array|Date|null)"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (this:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Parse error. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Parse error. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Parse error. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Parse error. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "goog.asserts = {};" + "/** @return {*} */ goog.asserts.assert = function(x) { return x; };" + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return number */goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return number */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return number*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return !Date */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return number */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return boolean*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) { " + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return number */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Parse error. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Parse error. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a runtime cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {boolean} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/* @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (this:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return Array */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return string */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return string */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Parse error. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes("/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n"); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface2() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Parse error. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { // To better support third-party code, we do not warn when // there are no braces around an unknown type name. testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }" + "f(3);", null); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testMalformedOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testMalformedOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @typedef {boolean} */ goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testDuplicateOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @constructor */ goog.Bar = function() {};" + "/** @type {number} */ goog.Bar = goog.typedef", "variable goog.Bar redefined with type number, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testOldTypeDef1() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testOldTypeDef3() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ var Bar = goog.typedef;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number|Array.<goog.Bar>} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // ok, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (AB|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Parse error. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Parse error. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Parse error. expected closing }", "Parse error. missing object name in @lends tag")); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() {});", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format(), true); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format(), true); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format(), true); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testFunctionLiteralUndefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals(descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput("[testcode]").getAstRoot(compiler); Node externsNode = compiler.getInput("[externs]").getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testBackwardsTypedefUse1` for the issue `Closure-268`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-268 // // ## Issue-Title: // resolveTypes: jstype.UnionType cannot be cast to jstype.ObjectType // // ## Issue-Description: // **What steps will reproduce the problem?** // // 1. Compile a bunch of JavaScript files that I can't release with these options: ['--create\_name\_map\_files', 'true', '--jscomp\_warning', 'missingProperties', '--jscomp\_warning', 'undefinedVars', '--jscomp\_warning', 'checkTypes', '--warning\_level', 'VERBOSE', '--summary\_detail\_level', '3', '--process\_closure\_primitives', 'true', '--jscomp\_error', 'strictModuleDepCheck', '--jscomp\_error', 'invalidCasts', '--logging\_level', 'ALL', '--compilation\_level', 'ADVANCED\_OPTIMIZATIONS'] // // 2. During this pass: // // Oct 26, 2010 12:09:38 AM com.google.javascript.jscomp.PhaseOptimizer$NamedPass process // INFO: resolveTypes // // , compilation terminates with: // // java.lang.RuntimeException: java.lang.ClassCastException: com.google.javascript.rhino.jstype.UnionType cannot be cast to com.google.javascript.rhino.jstype.ObjectType // at com.google.javascript.jscomp.Compiler.runInCompilerThread(Unknown Source) // at com.google.javascript.jscomp.Compiler.compile(Unknown Source) // at com.google.javascript.jscomp.Compiler.compile(Unknown Source) // at com.google.javascript.jscomp.AbstractCommandLineRunner.doRun(Unknown Source) // at com.google.javascript.jscomp.AbstractCommandLineRunner.run(Unknown Source) // at com.google.javascript.jscomp.CommandLineRunner.main(Unknown Source) // Caused by: java.lang.ClassCastException: com.google.javascript.rhino.jstype.UnionType cannot be cast to com.google.javascript.rhino.jstype.ObjectType // at com.google.javascript.rhino.jstype.FunctionType.resolveInternal(Unknown Source) // at com.google.javascript.rhino.jstype.JSType.resolve(Unknown Source) // at com.google.javascript.jscomp.TypedScopeCreator$DeferredSetType.resolve(Unknown Source) // at com.google.javascript.jscomp.TypedScopeCreator$AbstractScopeBuilder.resolveTypes(Unknown Source) // at com.google.javascript.jscomp.TypedScopeCreator.createScope(Unknown Source) // at com.google.javascript.jscomp.MemoizedScopeCreator.createScope(Unknown Source) // at com.google.javascript.jscomp.DefaultPassConfig$GlobalTypeResolver.process(Unknown Source) // at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(Unknown Source) // at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(Unknown Source) // at com.google.javascript.jscomp.PhaseOptimizer.process(Unknown Source) // at com.google.javascript.jscomp.Compiler.check(Unknown Source) // at com.google.javascript.jscomp.Compiler.compileInternal(Unknown Source) // at com.google.javascript.jscomp.Compiler.access$000(Unknown Source) // at com.google.javascript.jscomp.Compiler$1.call(Unknown Source) // at com.google.javascript.jscomp.Compiler$1.call(Unknown Source) // at com.google.javascript.jscomp.Compiler$2.run(Unknown Source) // at java.lang.Thread.run(Thread.java:662) // // // **What version of the product are you using? On what operating system?** // // I'm using Closure Compiler r506. The problem first appeared in r482. // // public void testBackwardsTypedefUse1() throws Exception {
2,614
152
2,608
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-268 ## Issue-Title: resolveTypes: jstype.UnionType cannot be cast to jstype.ObjectType ## Issue-Description: **What steps will reproduce the problem?** 1. Compile a bunch of JavaScript files that I can't release with these options: ['--create\_name\_map\_files', 'true', '--jscomp\_warning', 'missingProperties', '--jscomp\_warning', 'undefinedVars', '--jscomp\_warning', 'checkTypes', '--warning\_level', 'VERBOSE', '--summary\_detail\_level', '3', '--process\_closure\_primitives', 'true', '--jscomp\_error', 'strictModuleDepCheck', '--jscomp\_error', 'invalidCasts', '--logging\_level', 'ALL', '--compilation\_level', 'ADVANCED\_OPTIMIZATIONS'] 2. During this pass: Oct 26, 2010 12:09:38 AM com.google.javascript.jscomp.PhaseOptimizer$NamedPass process INFO: resolveTypes , compilation terminates with: java.lang.RuntimeException: java.lang.ClassCastException: com.google.javascript.rhino.jstype.UnionType cannot be cast to com.google.javascript.rhino.jstype.ObjectType at com.google.javascript.jscomp.Compiler.runInCompilerThread(Unknown Source) at com.google.javascript.jscomp.Compiler.compile(Unknown Source) at com.google.javascript.jscomp.Compiler.compile(Unknown Source) at com.google.javascript.jscomp.AbstractCommandLineRunner.doRun(Unknown Source) at com.google.javascript.jscomp.AbstractCommandLineRunner.run(Unknown Source) at com.google.javascript.jscomp.CommandLineRunner.main(Unknown Source) Caused by: java.lang.ClassCastException: com.google.javascript.rhino.jstype.UnionType cannot be cast to com.google.javascript.rhino.jstype.ObjectType at com.google.javascript.rhino.jstype.FunctionType.resolveInternal(Unknown Source) at com.google.javascript.rhino.jstype.JSType.resolve(Unknown Source) at com.google.javascript.jscomp.TypedScopeCreator$DeferredSetType.resolve(Unknown Source) at com.google.javascript.jscomp.TypedScopeCreator$AbstractScopeBuilder.resolveTypes(Unknown Source) at com.google.javascript.jscomp.TypedScopeCreator.createScope(Unknown Source) at com.google.javascript.jscomp.MemoizedScopeCreator.createScope(Unknown Source) at com.google.javascript.jscomp.DefaultPassConfig$GlobalTypeResolver.process(Unknown Source) at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(Unknown Source) at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(Unknown Source) at com.google.javascript.jscomp.PhaseOptimizer.process(Unknown Source) at com.google.javascript.jscomp.Compiler.check(Unknown Source) at com.google.javascript.jscomp.Compiler.compileInternal(Unknown Source) at com.google.javascript.jscomp.Compiler.access$000(Unknown Source) at com.google.javascript.jscomp.Compiler$1.call(Unknown Source) at com.google.javascript.jscomp.Compiler$1.call(Unknown Source) at com.google.javascript.jscomp.Compiler$2.run(Unknown Source) at java.lang.Thread.run(Thread.java:662) **What version of the product are you using? On what operating system?** I'm using Closure Compiler r506. The problem first appeared in r482. ``` You are a professional Java test case writer, please create a test case named `testBackwardsTypedefUse1` for the issue `Closure-268`, utilizing the provided issue report information and the following function signature. ```java public void testBackwardsTypedefUse1() throws Exception { ```
2,608
[ "com.google.javascript.rhino.jstype.FunctionType" ]
2bb981fe5fc7851af800c7bb4c8784a13043f36f373e65ebfa2e7a12f7297ffd
public void testBackwardsTypedefUse1() throws Exception
// You are a professional Java test case writer, please create a test case named `testBackwardsTypedefUse1` for the issue `Closure-268`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-268 // // ## Issue-Title: // resolveTypes: jstype.UnionType cannot be cast to jstype.ObjectType // // ## Issue-Description: // **What steps will reproduce the problem?** // // 1. Compile a bunch of JavaScript files that I can't release with these options: ['--create\_name\_map\_files', 'true', '--jscomp\_warning', 'missingProperties', '--jscomp\_warning', 'undefinedVars', '--jscomp\_warning', 'checkTypes', '--warning\_level', 'VERBOSE', '--summary\_detail\_level', '3', '--process\_closure\_primitives', 'true', '--jscomp\_error', 'strictModuleDepCheck', '--jscomp\_error', 'invalidCasts', '--logging\_level', 'ALL', '--compilation\_level', 'ADVANCED\_OPTIMIZATIONS'] // // 2. During this pass: // // Oct 26, 2010 12:09:38 AM com.google.javascript.jscomp.PhaseOptimizer$NamedPass process // INFO: resolveTypes // // , compilation terminates with: // // java.lang.RuntimeException: java.lang.ClassCastException: com.google.javascript.rhino.jstype.UnionType cannot be cast to com.google.javascript.rhino.jstype.ObjectType // at com.google.javascript.jscomp.Compiler.runInCompilerThread(Unknown Source) // at com.google.javascript.jscomp.Compiler.compile(Unknown Source) // at com.google.javascript.jscomp.Compiler.compile(Unknown Source) // at com.google.javascript.jscomp.AbstractCommandLineRunner.doRun(Unknown Source) // at com.google.javascript.jscomp.AbstractCommandLineRunner.run(Unknown Source) // at com.google.javascript.jscomp.CommandLineRunner.main(Unknown Source) // Caused by: java.lang.ClassCastException: com.google.javascript.rhino.jstype.UnionType cannot be cast to com.google.javascript.rhino.jstype.ObjectType // at com.google.javascript.rhino.jstype.FunctionType.resolveInternal(Unknown Source) // at com.google.javascript.rhino.jstype.JSType.resolve(Unknown Source) // at com.google.javascript.jscomp.TypedScopeCreator$DeferredSetType.resolve(Unknown Source) // at com.google.javascript.jscomp.TypedScopeCreator$AbstractScopeBuilder.resolveTypes(Unknown Source) // at com.google.javascript.jscomp.TypedScopeCreator.createScope(Unknown Source) // at com.google.javascript.jscomp.MemoizedScopeCreator.createScope(Unknown Source) // at com.google.javascript.jscomp.DefaultPassConfig$GlobalTypeResolver.process(Unknown Source) // at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(Unknown Source) // at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(Unknown Source) // at com.google.javascript.jscomp.PhaseOptimizer.process(Unknown Source) // at com.google.javascript.jscomp.Compiler.check(Unknown Source) // at com.google.javascript.jscomp.Compiler.compileInternal(Unknown Source) // at com.google.javascript.jscomp.Compiler.access$000(Unknown Source) // at com.google.javascript.jscomp.Compiler$1.call(Unknown Source) // at com.google.javascript.jscomp.Compiler$1.call(Unknown Source) // at com.google.javascript.jscomp.Compiler$2.run(Unknown Source) // at java.lang.Thread.run(Thread.java:662) // // // **What version of the product are you using? On what operating system?** // // I'm using Closure Compiler r506. The problem first appeared in r482. // //
Closure
/* * Copyright 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, new DefaultCodingConvention()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ foo()--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck7() throws Exception { testTypes("function foo() {delete 'abc';}", TypeCheck.BAD_DELETE); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Parse error. variable length argument must be " + "last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return number */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return string */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return string */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return boolean */" + "function f(b) { if (u()) { b = null; } return b; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return string */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return number*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateLocalVarDecl() throws Exception { testTypes( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", "variable x redefined with type string, " + "original definition at [testcode]:2 with type number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (this:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { /** TODO(user): This is not exactly correct yet. The var itself is nullable. */ testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE). restrictByNotNullOrUndefined().toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (this:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (this:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testTypes("/** @enum */var a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum9() throws Exception { testTypes( "var goog = {};" + "/** @enum */goog.a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|Array)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Array|Date|null)"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (this:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Parse error. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Parse error. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Parse error. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Parse error. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "goog.asserts = {};" + "/** @return {*} */ goog.asserts.assert = function(x) { return x; };" + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return number */goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return number */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return number*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return !Date */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return number */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return boolean*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) { " + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return number */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Parse error. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Parse error. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a runtime cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {boolean} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/* @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (this:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return Array */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return string */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return string */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Parse error. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes("/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n"); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface2() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Parse error. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { // To better support third-party code, we do not warn when // there are no braces around an unknown type name. testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }" + "f(3);", null); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testMalformedOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testMalformedOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @typedef {boolean} */ goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testDuplicateOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @constructor */ goog.Bar = function() {};" + "/** @type {number} */ goog.Bar = goog.typedef", "variable goog.Bar redefined with type number, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testOldTypeDef1() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testOldTypeDef3() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ var Bar = goog.typedef;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number|Array.<goog.Bar>} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // ok, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (AB|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Parse error. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Parse error. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Parse error. expected closing }", "Parse error. missing object name in @lends tag")); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() {});", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format(), true); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format(), true); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format(), true); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testFunctionLiteralUndefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals(descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput("[testcode]").getAstRoot(compiler); Node externsNode = compiler.getInput("[externs]").getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
public void testIssue1017() { testSame("x = x.parentNode.parentNode; x = x.parentNode.parentNode;"); }
com.google.javascript.jscomp.ExploitAssignsTest::testIssue1017
test/com/google/javascript/jscomp/ExploitAssignsTest.java
161
test/com/google/javascript/jscomp/ExploitAssignsTest.java
testIssue1017
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Unit tests for {@link ExploitAssigns} * * @author nicksantos@google.com (Nick Santos) * @author acleung@google.com (Alan Leung) */ public class ExploitAssignsTest extends CompilerTestCase { public void testExprExploitationTypes() { test("a = true; b = true", "b = a = true"); test("a = !0; b = !0", "b = a = !0"); test("a = !1; b = !1", "b = a = !1"); test("a = void 0; b = void 0", "b = a = void 0"); test("a = -Infinity; b = -Infinity", "b = a = -Infinity"); } public void testExprExploitationTypes2() { test("a = !0; b = !0", "b = a = !0"); } public void testExprExploitation() { test("a = null; b = null; var c = b", "var c = b = a = null"); test("a = null; b = null", "b = a = null"); test("a = undefined; b = undefined", "b = a = undefined"); test("a = 0; b = 0", "b=a=0"); test("a = 'foo'; b = 'foo'", "b = a = \"foo\""); test("a = c; b = c", "b=a=c"); testSame("a = 0; b = 1"); testSame("a = \"foo\"; b = \"foox\""); test("a = null; a && b;", "(a = null)&&b"); test("a = null; a || b;", "(a = null)||b"); test("a = null; a ? b : c;", "(a = null) ? b : c"); test("a = null; this.foo = null;", "this.foo = a = null"); test("function f(){ a = null; return null; }", "function f(){return a = null}"); test("a = true; if (a) { foo(); }", "if (a = true) { foo() }"); test("a = true; if (a && a) { foo(); }", "if ((a = true) && a) { foo() }"); test("a = false; if (a) { foo(); }", "if (a = false) { foo() }"); test("a = !0; if (a) { foo(); }", "if (a = !0) { foo() }"); test("a = !0; if (a && a) { foo(); }", "if ((a = !0) && a) { foo() }"); test("a = !1; if (a) { foo(); }", "if (a = !1) { foo() }"); testSame("a = this.foo; a();"); test("a = b; b = a;", "b = a = b"); testSame("a = b; a.c = a"); test("this.foo = null; this.bar = null;", "this.bar = this.foo = null"); test("this.foo = null; this.bar = null; this.baz = this.bar", "this.baz = this.bar = this.foo = null"); test("this.foo = null; a = null;", "a = this.foo = null"); test("this.foo = null; a = this.foo;", "a = this.foo = null"); test("a.b.c=null; a=null;", "a = a.b.c = null"); testSame("a = null; a.b.c = null"); test("(a=b).c = null; this.b = null;", "this.b = (a=b).c = null"); testSame("if(x) a = null; else b = a"); } public void testNestedExprExploitation() { test("this.foo = null; this.bar = null; this.baz = null;", "this.baz = this.bar = this.foo = null"); test("a = 3; this.foo = a; this.bar = a; this.baz = 3;", "this.baz = this.bar = this.foo = a = 3"); test("a = 3; this.foo = a; this.bar = this.foo; this.baz = a;", "this.baz = this.bar = this.foo = a = 3"); test("a = 3; this.foo = a; this.bar = 3; this.baz = this.foo;", "this.baz = this.bar = this.foo = a = 3"); test("a = 3; this.foo = a; a = 3; this.bar = 3; " + "a = 3; this.baz = this.foo;", "this.baz = a = this.bar = a = this.foo = a = 3"); test("a = 4; this.foo = a; a = 3; this.bar = 3; " + "a = 3; this.baz = this.foo;", "this.foo = a = 4; a = this.bar = a = 3; this.baz = this.foo"); test("a = 3; this.foo = a; a = 4; this.bar = 3; " + "a = 3; this.baz = this.foo;", "this.foo = a = 3; a = 4; a = this.bar = 3; this.baz = this.foo"); test("a = 3; this.foo = a; a = 3; this.bar = 3; " + "a = 4; this.baz = this.foo;", "this.bar = a = this.foo = a = 3; a = 4; this.baz = this.foo"); } public void testBug1840071() { // Some external properties are implemented as setters. Let's // make sure that we don't collapse them inappropriately. test("a.b = a.x; if (a.x) {}", "if (a.b = a.x) {}"); testSame("a.b = a.x; if (a.b) {}"); test("a.b = a.c = a.x; if (a.x) {}", "if (a.b = a.c = a.x) {}"); testSame("a.b = a.c = a.x; if (a.c) {}"); testSame("a.b = a.c = a.x; if (a.b) {}"); } public void testBug2072343() { testSame("a = a.x;a = a.x"); testSame("a = a.x;b = a.x"); test("b = a.x;a = a.x", "a = b = a.x"); testSame("a.x = a;a = a.x"); testSame("a.b = a.b.x;a.b = a.b.x"); testSame("a.y = a.y.x;b = a.y;c = a.y.x"); test("a = a.x;b = a;c = a.x", "b = a = a.x;c = a.x"); test("b = a.x;a = b;c = a.x", "a = b = a.x;c = a.x"); } public void testBadCollapseIntoCall() { // Can't collapse this, because if we did, 'foo' would be called // in the wrong 'this' context. testSame("this.foo = function() {}; this.foo();"); } public void testBadCollapse() { testSame("this.$e$ = []; this.$b$ = null;"); } public void testIssue1017() { testSame("x = x.parentNode.parentNode; x = x.parentNode.parentNode;"); } @Override protected CompilerPass getProcessor(Compiler compiler) { return new PeepholeOptimizationsPass(compiler,new ExploitAssigns()); } }
// You are a professional Java test case writer, please create a test case named `testIssue1017` for the issue `Closure-1017`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1017 // // ## Issue-Title: // Different output from RestAPI and command line jar // // ## Issue-Description: // When I compile using the jar file from the command line I get a result that is not correct. However, when I test it via the REST API or the Web UI I get a correct output. I've attached a file with the code that we are compiling. // // **What steps will reproduce the problem?** // 1. Compile the attached file with "java -jar compiler.jar --js test.js" // 2. Compile the content of the attached file on http://closure-compiler.appspot.com/home // 3. Compare the output, note how the following part is converted in the two cases: // // "var foreignObject = gfx.parentNode.parentNode; // var parentContainer = foreignObject.parentNode.parentNode;" // // **What is the expected output? What do you see instead?** // The Web UI converts the lines into: if(b){if(a=b.parentNode.parentNode,b=a.parentNode.parentNode,null!==b) // The command line converts it into: var b=a=a.parentNode.parentNode; // The Web UI results in correct code, the other results in code that tries to do "c.appendChild(b)" with c = b (c=a=a.parentNode.parentNode) // // **What version of the product are you using? On what operating system?** // compiler.jar: v20130411-90-g4e19b4e // Mac OSX 10.8.3 // Java: java 1.6.0\_45 // // **Please provide any additional information below.** // We are also using the compiler form within our java code, with the same result. // Web UI was called with: // // ==ClosureCompiler== // // @compilation\_level SIMPLE\_OPTIMIZATIONS // // @output\_file\_name default.js // // ==/ClosureCompiler== // // public void testIssue1017() {
161
124
159
test/com/google/javascript/jscomp/ExploitAssignsTest.java
test
```markdown ## Issue-ID: Closure-1017 ## Issue-Title: Different output from RestAPI and command line jar ## Issue-Description: When I compile using the jar file from the command line I get a result that is not correct. However, when I test it via the REST API or the Web UI I get a correct output. I've attached a file with the code that we are compiling. **What steps will reproduce the problem?** 1. Compile the attached file with "java -jar compiler.jar --js test.js" 2. Compile the content of the attached file on http://closure-compiler.appspot.com/home 3. Compare the output, note how the following part is converted in the two cases: "var foreignObject = gfx.parentNode.parentNode; var parentContainer = foreignObject.parentNode.parentNode;" **What is the expected output? What do you see instead?** The Web UI converts the lines into: if(b){if(a=b.parentNode.parentNode,b=a.parentNode.parentNode,null!==b) The command line converts it into: var b=a=a.parentNode.parentNode; The Web UI results in correct code, the other results in code that tries to do "c.appendChild(b)" with c = b (c=a=a.parentNode.parentNode) **What version of the product are you using? On what operating system?** compiler.jar: v20130411-90-g4e19b4e Mac OSX 10.8.3 Java: java 1.6.0\_45 **Please provide any additional information below.** We are also using the compiler form within our java code, with the same result. Web UI was called with: // ==ClosureCompiler== // @compilation\_level SIMPLE\_OPTIMIZATIONS // @output\_file\_name default.js // ==/ClosureCompiler== ``` You are a professional Java test case writer, please create a test case named `testIssue1017` for the issue `Closure-1017`, utilizing the provided issue report information and the following function signature. ```java public void testIssue1017() { ```
159
[ "com.google.javascript.jscomp.ExploitAssigns" ]
2bc49469aea20518aa60986f6924f15475d1ca003f9bc1e7d800b7ef3589570f
public void testIssue1017()
// You are a professional Java test case writer, please create a test case named `testIssue1017` for the issue `Closure-1017`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1017 // // ## Issue-Title: // Different output from RestAPI and command line jar // // ## Issue-Description: // When I compile using the jar file from the command line I get a result that is not correct. However, when I test it via the REST API or the Web UI I get a correct output. I've attached a file with the code that we are compiling. // // **What steps will reproduce the problem?** // 1. Compile the attached file with "java -jar compiler.jar --js test.js" // 2. Compile the content of the attached file on http://closure-compiler.appspot.com/home // 3. Compare the output, note how the following part is converted in the two cases: // // "var foreignObject = gfx.parentNode.parentNode; // var parentContainer = foreignObject.parentNode.parentNode;" // // **What is the expected output? What do you see instead?** // The Web UI converts the lines into: if(b){if(a=b.parentNode.parentNode,b=a.parentNode.parentNode,null!==b) // The command line converts it into: var b=a=a.parentNode.parentNode; // The Web UI results in correct code, the other results in code that tries to do "c.appendChild(b)" with c = b (c=a=a.parentNode.parentNode) // // **What version of the product are you using? On what operating system?** // compiler.jar: v20130411-90-g4e19b4e // Mac OSX 10.8.3 // Java: java 1.6.0\_45 // // **Please provide any additional information below.** // We are also using the compiler form within our java code, with the same result. // Web UI was called with: // // ==ClosureCompiler== // // @compilation\_level SIMPLE\_OPTIMIZATIONS // // @output\_file\_name default.js // // ==/ClosureCompiler== // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Unit tests for {@link ExploitAssigns} * * @author nicksantos@google.com (Nick Santos) * @author acleung@google.com (Alan Leung) */ public class ExploitAssignsTest extends CompilerTestCase { public void testExprExploitationTypes() { test("a = true; b = true", "b = a = true"); test("a = !0; b = !0", "b = a = !0"); test("a = !1; b = !1", "b = a = !1"); test("a = void 0; b = void 0", "b = a = void 0"); test("a = -Infinity; b = -Infinity", "b = a = -Infinity"); } public void testExprExploitationTypes2() { test("a = !0; b = !0", "b = a = !0"); } public void testExprExploitation() { test("a = null; b = null; var c = b", "var c = b = a = null"); test("a = null; b = null", "b = a = null"); test("a = undefined; b = undefined", "b = a = undefined"); test("a = 0; b = 0", "b=a=0"); test("a = 'foo'; b = 'foo'", "b = a = \"foo\""); test("a = c; b = c", "b=a=c"); testSame("a = 0; b = 1"); testSame("a = \"foo\"; b = \"foox\""); test("a = null; a && b;", "(a = null)&&b"); test("a = null; a || b;", "(a = null)||b"); test("a = null; a ? b : c;", "(a = null) ? b : c"); test("a = null; this.foo = null;", "this.foo = a = null"); test("function f(){ a = null; return null; }", "function f(){return a = null}"); test("a = true; if (a) { foo(); }", "if (a = true) { foo() }"); test("a = true; if (a && a) { foo(); }", "if ((a = true) && a) { foo() }"); test("a = false; if (a) { foo(); }", "if (a = false) { foo() }"); test("a = !0; if (a) { foo(); }", "if (a = !0) { foo() }"); test("a = !0; if (a && a) { foo(); }", "if ((a = !0) && a) { foo() }"); test("a = !1; if (a) { foo(); }", "if (a = !1) { foo() }"); testSame("a = this.foo; a();"); test("a = b; b = a;", "b = a = b"); testSame("a = b; a.c = a"); test("this.foo = null; this.bar = null;", "this.bar = this.foo = null"); test("this.foo = null; this.bar = null; this.baz = this.bar", "this.baz = this.bar = this.foo = null"); test("this.foo = null; a = null;", "a = this.foo = null"); test("this.foo = null; a = this.foo;", "a = this.foo = null"); test("a.b.c=null; a=null;", "a = a.b.c = null"); testSame("a = null; a.b.c = null"); test("(a=b).c = null; this.b = null;", "this.b = (a=b).c = null"); testSame("if(x) a = null; else b = a"); } public void testNestedExprExploitation() { test("this.foo = null; this.bar = null; this.baz = null;", "this.baz = this.bar = this.foo = null"); test("a = 3; this.foo = a; this.bar = a; this.baz = 3;", "this.baz = this.bar = this.foo = a = 3"); test("a = 3; this.foo = a; this.bar = this.foo; this.baz = a;", "this.baz = this.bar = this.foo = a = 3"); test("a = 3; this.foo = a; this.bar = 3; this.baz = this.foo;", "this.baz = this.bar = this.foo = a = 3"); test("a = 3; this.foo = a; a = 3; this.bar = 3; " + "a = 3; this.baz = this.foo;", "this.baz = a = this.bar = a = this.foo = a = 3"); test("a = 4; this.foo = a; a = 3; this.bar = 3; " + "a = 3; this.baz = this.foo;", "this.foo = a = 4; a = this.bar = a = 3; this.baz = this.foo"); test("a = 3; this.foo = a; a = 4; this.bar = 3; " + "a = 3; this.baz = this.foo;", "this.foo = a = 3; a = 4; a = this.bar = 3; this.baz = this.foo"); test("a = 3; this.foo = a; a = 3; this.bar = 3; " + "a = 4; this.baz = this.foo;", "this.bar = a = this.foo = a = 3; a = 4; this.baz = this.foo"); } public void testBug1840071() { // Some external properties are implemented as setters. Let's // make sure that we don't collapse them inappropriately. test("a.b = a.x; if (a.x) {}", "if (a.b = a.x) {}"); testSame("a.b = a.x; if (a.b) {}"); test("a.b = a.c = a.x; if (a.x) {}", "if (a.b = a.c = a.x) {}"); testSame("a.b = a.c = a.x; if (a.c) {}"); testSame("a.b = a.c = a.x; if (a.b) {}"); } public void testBug2072343() { testSame("a = a.x;a = a.x"); testSame("a = a.x;b = a.x"); test("b = a.x;a = a.x", "a = b = a.x"); testSame("a.x = a;a = a.x"); testSame("a.b = a.b.x;a.b = a.b.x"); testSame("a.y = a.y.x;b = a.y;c = a.y.x"); test("a = a.x;b = a;c = a.x", "b = a = a.x;c = a.x"); test("b = a.x;a = b;c = a.x", "a = b = a.x;c = a.x"); } public void testBadCollapseIntoCall() { // Can't collapse this, because if we did, 'foo' would be called // in the wrong 'this' context. testSame("this.foo = function() {}; this.foo();"); } public void testBadCollapse() { testSame("this.$e$ = []; this.$b$ = null;"); } public void testIssue1017() { testSame("x = x.parentNode.parentNode; x = x.parentNode.parentNode;"); } @Override protected CompilerPass getProcessor(Compiler compiler) { return new PeepholeOptimizationsPass(compiler,new ExploitAssigns()); } }
public void testRootBeans() throws Exception { for (Source src : Source.values()) { _testRootBeans(src); } }
com.fasterxml.jackson.databind.seq.ReadValuesTest::testRootBeans
src/test/java/com/fasterxml/jackson/databind/seq/ReadValuesTest.java
50
src/test/java/com/fasterxml/jackson/databind/seq/ReadValuesTest.java
testRootBeans
package com.fasterxml.jackson.databind.seq; import java.io.*; import java.util.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; @SuppressWarnings("resource") public class ReadValuesTest extends BaseMapTest { static class Bean { public int a; @Override public boolean equals(Object o) { if (o == null || o.getClass() != getClass()) return false; Bean other = (Bean) o; return other.a == this.a; } @Override public int hashCode() { return a; } } /* /********************************************************** /* Unit tests; root-level value sequences via Mapper /********************************************************** */ private enum Source { STRING, INPUT_STREAM, READER, BYTE_ARRAY, BYTE_ARRAY_OFFSET ; } private final ObjectMapper MAPPER = new ObjectMapper(); public void testRootBeans() throws Exception { for (Source src : Source.values()) { _testRootBeans(src); } } private <T> MappingIterator<T> _iterator(ObjectReader r, String json, Source srcType) throws IOException { switch (srcType) { case BYTE_ARRAY: return r.readValues(json.getBytes("UTF-8")); case BYTE_ARRAY_OFFSET: { ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(0); out.write(0); out.write(0); out.write(json.getBytes("UTF-8")); out.write(0); out.write(0); out.write(0); byte[] b = out.toByteArray(); return r.readValues(b, 3, b.length-6); } case INPUT_STREAM: return r.readValues(new ByteArrayInputStream(json.getBytes("UTF-8"))); case READER: return r.readValues(new StringReader(json)); case STRING: default: return r.readValues(json); } } private void _testRootBeans(Source srcType) throws Exception { final String JSON = "{\"a\":3}{\"a\":27} "; MappingIterator<Bean> it = _iterator(MAPPER.readerFor(Bean.class), JSON, srcType); MAPPER.readerFor(Bean.class).readValues(JSON); assertNotNull(it.getCurrentLocation()); assertTrue(it.hasNext()); Bean b = it.next(); assertEquals(3, b.a); assertTrue(it.hasNext()); b = it.next(); assertEquals(27, b.a); assertFalse(it.hasNext()); it.close(); // Also, test 'readAll()' it = MAPPER.readerFor(Bean.class).readValues(JSON); List<Bean> all = it.readAll(); assertEquals(2, all.size()); it.close(); it = MAPPER.readerFor(Bean.class).readValues("{\"a\":3}{\"a\":3}"); Set<Bean> set = it.readAll(new HashSet<Bean>()); assertEquals(HashSet.class, set.getClass()); assertEquals(1, set.size()); assertEquals(3, set.iterator().next().a); } public void testRootBeansInArray() throws Exception { final String JSON = "[{\"a\":6}, {\"a\":-7}]"; MappingIterator<Bean> it = MAPPER.readerFor(Bean.class).readValues(JSON); assertNotNull(it.getCurrentLocation()); assertTrue(it.hasNext()); Bean b = it.next(); assertEquals(6, b.a); assertTrue(it.hasNext()); b = it.next(); assertEquals(-7, b.a); assertFalse(it.hasNext()); it.close(); // Also, test 'readAll()' it = MAPPER.readerFor(Bean.class).readValues(JSON); List<Bean> all = it.readAll(); assertEquals(2, all.size()); it.close(); it = MAPPER.readerFor(Bean.class).readValues("[{\"a\":4},{\"a\":4}]"); Set<Bean> set = it.readAll(new HashSet<Bean>()); assertEquals(HashSet.class, set.getClass()); assertEquals(1, set.size()); assertEquals(4, set.iterator().next().a); } public void testRootMaps() throws Exception { final String JSON = "{\"a\":3}{\"a\":27} "; Iterator<Map<?,?>> it = MAPPER.readerFor(Map.class).readValues(JSON); assertNotNull(((MappingIterator<?>) it).getCurrentLocation()); assertTrue(it.hasNext()); Map<?,?> map = it.next(); assertEquals(1, map.size()); assertEquals(Integer.valueOf(3), map.get("a")); assertTrue(it.hasNext()); assertNotNull(((MappingIterator<?>) it).getCurrentLocation()); map = it.next(); assertEquals(1, map.size()); assertEquals(Integer.valueOf(27), map.get("a")); assertFalse(it.hasNext()); } /* /********************************************************** /* Unit tests; root-level value sequences via JsonParser /********************************************************** */ public void testRootBeansWithParser() throws Exception { final String JSON = "{\"a\":3}{\"a\":27} "; JsonParser jp = MAPPER.getFactory().createParser(JSON); Iterator<Bean> it = jp.readValuesAs(Bean.class); assertTrue(it.hasNext()); Bean b = it.next(); assertEquals(3, b.a); assertTrue(it.hasNext()); b = it.next(); assertEquals(27, b.a); assertFalse(it.hasNext()); } public void testRootArraysWithParser() throws Exception { final String JSON = "[1][3]"; JsonParser jp = MAPPER.getFactory().createParser(JSON); // NOTE: We must point JsonParser to the first element; if we tried to // use "managed" accessor, it would try to advance past START_ARRAY. assertToken(JsonToken.START_ARRAY, jp.nextToken()); Iterator<int[]> it = MAPPER.readerFor(int[].class).readValues(jp); assertTrue(it.hasNext()); int[] array = it.next(); assertEquals(1, array.length); assertEquals(1, array[0]); assertTrue(it.hasNext()); array = it.next(); assertEquals(1, array.length); assertEquals(3, array[0]); assertFalse(it.hasNext()); } public void testHasNextWithEndArray() throws Exception { final String JSON = "[1,3]"; JsonParser jp = MAPPER.getFactory().createParser(JSON); // NOTE: We must point JsonParser to the first element; if we tried to // use "managed" accessor, it would try to advance past START_ARRAY. assertToken(JsonToken.START_ARRAY, jp.nextToken()); jp.nextToken(); Iterator<Integer> it = MAPPER.readerFor(Integer.class).readValues(jp); assertTrue(it.hasNext()); int value = it.next(); assertEquals(1, value); assertTrue(it.hasNext()); value = it.next(); assertEquals(3, value); assertFalse(it.hasNext()); assertFalse(it.hasNext()); } public void testHasNextWithEndArrayManagedParser() throws Exception { final String JSON = "[1,3]"; Iterator<Integer> it = MAPPER.readerFor(Integer.class).readValues(JSON); assertTrue(it.hasNext()); int value = it.next(); assertEquals(1, value); assertTrue(it.hasNext()); value = it.next(); assertEquals(3, value); assertFalse(it.hasNext()); assertFalse(it.hasNext()); } /* /********************************************************** /* Unit tests; non-root arrays /********************************************************** */ public void testNonRootBeans() throws Exception { final String JSON = "{\"leaf\":[{\"a\":3},{\"a\":27}]}"; JsonParser jp = MAPPER.getFactory().createParser(JSON); assertToken(JsonToken.START_OBJECT, jp.nextToken()); assertToken(JsonToken.FIELD_NAME, jp.nextToken()); assertToken(JsonToken.START_ARRAY, jp.nextToken()); // can either advance to first START_OBJECT, or clear current token; // explicitly passed JsonParser MUST point to the first token of // the first element assertToken(JsonToken.START_OBJECT, jp.nextToken()); Iterator<Bean> it = MAPPER.readerFor(Bean.class).readValues(jp); assertTrue(it.hasNext()); Bean b = it.next(); assertEquals(3, b.a); assertTrue(it.hasNext()); b = it.next(); assertEquals(27, b.a); assertFalse(it.hasNext()); jp.close(); } public void testNonRootMapsWithParser() throws Exception { final String JSON = "[{\"a\":3},{\"a\":27}]"; JsonParser jp = MAPPER.getFactory().createParser(JSON); assertToken(JsonToken.START_ARRAY, jp.nextToken()); // can either advance to first START_OBJECT, or clear current token; // explicitly passed JsonParser MUST point to the first token of // the first element jp.clearCurrentToken(); Iterator<Map<?,?>> it = MAPPER.readerFor(Map.class).readValues(jp); assertTrue(it.hasNext()); Map<?,?> map = it.next(); assertEquals(1, map.size()); assertEquals(Integer.valueOf(3), map.get("a")); assertTrue(it.hasNext()); map = it.next(); assertEquals(1, map.size()); assertEquals(Integer.valueOf(27), map.get("a")); assertFalse(it.hasNext()); jp.close(); } public void testNonRootMapsWithObjectReader() throws Exception { String JSON = "[{ \"hi\": \"ho\", \"neighbor\": \"Joe\" },\n" +"{\"boy\": \"howdy\", \"huh\": \"what\"}]"; final MappingIterator<Map<String, Object>> iterator = MAPPER .reader() .forType(new TypeReference<Map<String, Object>>(){}) .readValues(JSON); Map<String,Object> map; assertTrue(iterator.hasNext()); map = iterator.nextValue(); assertEquals(2, map.size()); assertTrue(iterator.hasNext()); map = iterator.nextValue(); assertEquals(2, map.size()); assertFalse(iterator.hasNext()); } public void testNonRootArraysUsingParser() throws Exception { final String JSON = "[[1],[3]]"; JsonParser p = MAPPER.getFactory().createParser(JSON); assertToken(JsonToken.START_ARRAY, p.nextToken()); // Important: as of 2.1, START_ARRAY can only be skipped if the // target type is NOT a Collection or array Java type. // So we have to explicitly skip it in this particular case. assertToken(JsonToken.START_ARRAY, p.nextToken()); Iterator<int[]> it = MAPPER.readValues(p, int[].class); assertTrue(it.hasNext()); int[] array = it.next(); assertEquals(1, array.length); assertEquals(1, array[0]); assertTrue(it.hasNext()); array = it.next(); assertEquals(1, array.length); assertEquals(3, array[0]); assertFalse(it.hasNext()); p.close(); } }
// You are a professional Java test case writer, please create a test case named `testRootBeans` for the issue `JacksonDatabind-1362`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1362 // // ## Issue-Title: // ObjectReader.readValues() ignores offset and length when reading an array // // ## Issue-Description: // ObjectReader.readValues ignores offset and length when reading an array. If \_dataFormatReaders it will always use the full array: // // // <https://github.com/FasterXML/jackson-databind/blob/2.7/src/main/java/com/fasterxml/jackson/databind/ObjectReader.java#L1435> // // // // public void testRootBeans() throws Exception {
50
57
45
src/test/java/com/fasterxml/jackson/databind/seq/ReadValuesTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1362 ## Issue-Title: ObjectReader.readValues() ignores offset and length when reading an array ## Issue-Description: ObjectReader.readValues ignores offset and length when reading an array. If \_dataFormatReaders it will always use the full array: <https://github.com/FasterXML/jackson-databind/blob/2.7/src/main/java/com/fasterxml/jackson/databind/ObjectReader.java#L1435> ``` You are a professional Java test case writer, please create a test case named `testRootBeans` for the issue `JacksonDatabind-1362`, utilizing the provided issue report information and the following function signature. ```java public void testRootBeans() throws Exception { ```
45
[ "com.fasterxml.jackson.databind.ObjectReader" ]
2bd123ba79c62252138620d6ee25bf7c4cc445a4c4041dc8e96fe345d80382e3
public void testRootBeans() throws Exception
// You are a professional Java test case writer, please create a test case named `testRootBeans` for the issue `JacksonDatabind-1362`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1362 // // ## Issue-Title: // ObjectReader.readValues() ignores offset and length when reading an array // // ## Issue-Description: // ObjectReader.readValues ignores offset and length when reading an array. If \_dataFormatReaders it will always use the full array: // // // <https://github.com/FasterXML/jackson-databind/blob/2.7/src/main/java/com/fasterxml/jackson/databind/ObjectReader.java#L1435> // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.seq; import java.io.*; import java.util.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; @SuppressWarnings("resource") public class ReadValuesTest extends BaseMapTest { static class Bean { public int a; @Override public boolean equals(Object o) { if (o == null || o.getClass() != getClass()) return false; Bean other = (Bean) o; return other.a == this.a; } @Override public int hashCode() { return a; } } /* /********************************************************** /* Unit tests; root-level value sequences via Mapper /********************************************************** */ private enum Source { STRING, INPUT_STREAM, READER, BYTE_ARRAY, BYTE_ARRAY_OFFSET ; } private final ObjectMapper MAPPER = new ObjectMapper(); public void testRootBeans() throws Exception { for (Source src : Source.values()) { _testRootBeans(src); } } private <T> MappingIterator<T> _iterator(ObjectReader r, String json, Source srcType) throws IOException { switch (srcType) { case BYTE_ARRAY: return r.readValues(json.getBytes("UTF-8")); case BYTE_ARRAY_OFFSET: { ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(0); out.write(0); out.write(0); out.write(json.getBytes("UTF-8")); out.write(0); out.write(0); out.write(0); byte[] b = out.toByteArray(); return r.readValues(b, 3, b.length-6); } case INPUT_STREAM: return r.readValues(new ByteArrayInputStream(json.getBytes("UTF-8"))); case READER: return r.readValues(new StringReader(json)); case STRING: default: return r.readValues(json); } } private void _testRootBeans(Source srcType) throws Exception { final String JSON = "{\"a\":3}{\"a\":27} "; MappingIterator<Bean> it = _iterator(MAPPER.readerFor(Bean.class), JSON, srcType); MAPPER.readerFor(Bean.class).readValues(JSON); assertNotNull(it.getCurrentLocation()); assertTrue(it.hasNext()); Bean b = it.next(); assertEquals(3, b.a); assertTrue(it.hasNext()); b = it.next(); assertEquals(27, b.a); assertFalse(it.hasNext()); it.close(); // Also, test 'readAll()' it = MAPPER.readerFor(Bean.class).readValues(JSON); List<Bean> all = it.readAll(); assertEquals(2, all.size()); it.close(); it = MAPPER.readerFor(Bean.class).readValues("{\"a\":3}{\"a\":3}"); Set<Bean> set = it.readAll(new HashSet<Bean>()); assertEquals(HashSet.class, set.getClass()); assertEquals(1, set.size()); assertEquals(3, set.iterator().next().a); } public void testRootBeansInArray() throws Exception { final String JSON = "[{\"a\":6}, {\"a\":-7}]"; MappingIterator<Bean> it = MAPPER.readerFor(Bean.class).readValues(JSON); assertNotNull(it.getCurrentLocation()); assertTrue(it.hasNext()); Bean b = it.next(); assertEquals(6, b.a); assertTrue(it.hasNext()); b = it.next(); assertEquals(-7, b.a); assertFalse(it.hasNext()); it.close(); // Also, test 'readAll()' it = MAPPER.readerFor(Bean.class).readValues(JSON); List<Bean> all = it.readAll(); assertEquals(2, all.size()); it.close(); it = MAPPER.readerFor(Bean.class).readValues("[{\"a\":4},{\"a\":4}]"); Set<Bean> set = it.readAll(new HashSet<Bean>()); assertEquals(HashSet.class, set.getClass()); assertEquals(1, set.size()); assertEquals(4, set.iterator().next().a); } public void testRootMaps() throws Exception { final String JSON = "{\"a\":3}{\"a\":27} "; Iterator<Map<?,?>> it = MAPPER.readerFor(Map.class).readValues(JSON); assertNotNull(((MappingIterator<?>) it).getCurrentLocation()); assertTrue(it.hasNext()); Map<?,?> map = it.next(); assertEquals(1, map.size()); assertEquals(Integer.valueOf(3), map.get("a")); assertTrue(it.hasNext()); assertNotNull(((MappingIterator<?>) it).getCurrentLocation()); map = it.next(); assertEquals(1, map.size()); assertEquals(Integer.valueOf(27), map.get("a")); assertFalse(it.hasNext()); } /* /********************************************************** /* Unit tests; root-level value sequences via JsonParser /********************************************************** */ public void testRootBeansWithParser() throws Exception { final String JSON = "{\"a\":3}{\"a\":27} "; JsonParser jp = MAPPER.getFactory().createParser(JSON); Iterator<Bean> it = jp.readValuesAs(Bean.class); assertTrue(it.hasNext()); Bean b = it.next(); assertEquals(3, b.a); assertTrue(it.hasNext()); b = it.next(); assertEquals(27, b.a); assertFalse(it.hasNext()); } public void testRootArraysWithParser() throws Exception { final String JSON = "[1][3]"; JsonParser jp = MAPPER.getFactory().createParser(JSON); // NOTE: We must point JsonParser to the first element; if we tried to // use "managed" accessor, it would try to advance past START_ARRAY. assertToken(JsonToken.START_ARRAY, jp.nextToken()); Iterator<int[]> it = MAPPER.readerFor(int[].class).readValues(jp); assertTrue(it.hasNext()); int[] array = it.next(); assertEquals(1, array.length); assertEquals(1, array[0]); assertTrue(it.hasNext()); array = it.next(); assertEquals(1, array.length); assertEquals(3, array[0]); assertFalse(it.hasNext()); } public void testHasNextWithEndArray() throws Exception { final String JSON = "[1,3]"; JsonParser jp = MAPPER.getFactory().createParser(JSON); // NOTE: We must point JsonParser to the first element; if we tried to // use "managed" accessor, it would try to advance past START_ARRAY. assertToken(JsonToken.START_ARRAY, jp.nextToken()); jp.nextToken(); Iterator<Integer> it = MAPPER.readerFor(Integer.class).readValues(jp); assertTrue(it.hasNext()); int value = it.next(); assertEquals(1, value); assertTrue(it.hasNext()); value = it.next(); assertEquals(3, value); assertFalse(it.hasNext()); assertFalse(it.hasNext()); } public void testHasNextWithEndArrayManagedParser() throws Exception { final String JSON = "[1,3]"; Iterator<Integer> it = MAPPER.readerFor(Integer.class).readValues(JSON); assertTrue(it.hasNext()); int value = it.next(); assertEquals(1, value); assertTrue(it.hasNext()); value = it.next(); assertEquals(3, value); assertFalse(it.hasNext()); assertFalse(it.hasNext()); } /* /********************************************************** /* Unit tests; non-root arrays /********************************************************** */ public void testNonRootBeans() throws Exception { final String JSON = "{\"leaf\":[{\"a\":3},{\"a\":27}]}"; JsonParser jp = MAPPER.getFactory().createParser(JSON); assertToken(JsonToken.START_OBJECT, jp.nextToken()); assertToken(JsonToken.FIELD_NAME, jp.nextToken()); assertToken(JsonToken.START_ARRAY, jp.nextToken()); // can either advance to first START_OBJECT, or clear current token; // explicitly passed JsonParser MUST point to the first token of // the first element assertToken(JsonToken.START_OBJECT, jp.nextToken()); Iterator<Bean> it = MAPPER.readerFor(Bean.class).readValues(jp); assertTrue(it.hasNext()); Bean b = it.next(); assertEquals(3, b.a); assertTrue(it.hasNext()); b = it.next(); assertEquals(27, b.a); assertFalse(it.hasNext()); jp.close(); } public void testNonRootMapsWithParser() throws Exception { final String JSON = "[{\"a\":3},{\"a\":27}]"; JsonParser jp = MAPPER.getFactory().createParser(JSON); assertToken(JsonToken.START_ARRAY, jp.nextToken()); // can either advance to first START_OBJECT, or clear current token; // explicitly passed JsonParser MUST point to the first token of // the first element jp.clearCurrentToken(); Iterator<Map<?,?>> it = MAPPER.readerFor(Map.class).readValues(jp); assertTrue(it.hasNext()); Map<?,?> map = it.next(); assertEquals(1, map.size()); assertEquals(Integer.valueOf(3), map.get("a")); assertTrue(it.hasNext()); map = it.next(); assertEquals(1, map.size()); assertEquals(Integer.valueOf(27), map.get("a")); assertFalse(it.hasNext()); jp.close(); } public void testNonRootMapsWithObjectReader() throws Exception { String JSON = "[{ \"hi\": \"ho\", \"neighbor\": \"Joe\" },\n" +"{\"boy\": \"howdy\", \"huh\": \"what\"}]"; final MappingIterator<Map<String, Object>> iterator = MAPPER .reader() .forType(new TypeReference<Map<String, Object>>(){}) .readValues(JSON); Map<String,Object> map; assertTrue(iterator.hasNext()); map = iterator.nextValue(); assertEquals(2, map.size()); assertTrue(iterator.hasNext()); map = iterator.nextValue(); assertEquals(2, map.size()); assertFalse(iterator.hasNext()); } public void testNonRootArraysUsingParser() throws Exception { final String JSON = "[[1],[3]]"; JsonParser p = MAPPER.getFactory().createParser(JSON); assertToken(JsonToken.START_ARRAY, p.nextToken()); // Important: as of 2.1, START_ARRAY can only be skipped if the // target type is NOT a Collection or array Java type. // So we have to explicitly skip it in this particular case. assertToken(JsonToken.START_ARRAY, p.nextToken()); Iterator<int[]> it = MAPPER.readValues(p, int[].class); assertTrue(it.hasNext()); int[] array = it.next(); assertEquals(1, array.length); assertEquals(1, array[0]); assertTrue(it.hasNext()); array = it.next(); assertEquals(1, array.length); assertEquals(3, array[0]); assertFalse(it.hasNext()); p.close(); } }
public void testBug1864222() { TimeSeries s = new TimeSeries("S"); s.add(new Day(19, 8, 2005), 1); s.add(new Day(31, 1, 2006), 1); boolean pass = true; try { s.createCopy(new Day(1, 12, 2005), new Day(18, 1, 2006)); } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); }
org.jfree.data.time.junit.TimeSeriesTests::testBug1864222
tests/org/jfree/data/time/junit/TimeSeriesTests.java
834
tests/org/jfree/data/time/junit/TimeSeriesTests.java
testBug1864222
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * TimeSeriesTests.java * -------------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Nov-2001 : Version 1 (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Added serialization test (DG); * 15-Oct-2003 : Added test for setMaximumItemCount method (DG); * 23-Aug-2004 : Added test that highlights a bug where the addOrUpdate() * method can lead to more than maximumItemCount items in the * dataset (DG); * 24-May-2006 : Added new tests (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * 31-Oct-2007 : New hashCode() test (DG); * 21-Nov-2007 : Added testBug1832432() and testClone2() (DG); * 10-Jan-2008 : Added testBug1864222() (DG); * */ package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; /** * A collection of test cases for the {@link TimeSeries} class. */ public class TimeSeriesTests extends TestCase implements SeriesChangeListener { /** A time series. */ private TimeSeries seriesA; /** A time series. */ private TimeSeries seriesB; /** A time series. */ private TimeSeries seriesC; /** A flag that indicates whether or not a change event was fired. */ private boolean gotSeriesChangeEvent = false; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimeSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimeSeriesTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.seriesA = new TimeSeries("Series A", Year.class); try { this.seriesA.add(new Year(2000), new Integer(102000)); this.seriesA.add(new Year(2001), new Integer(102001)); this.seriesA.add(new Year(2002), new Integer(102002)); this.seriesA.add(new Year(2003), new Integer(102003)); this.seriesA.add(new Year(2004), new Integer(102004)); this.seriesA.add(new Year(2005), new Integer(102005)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesB = new TimeSeries("Series B", Year.class); try { this.seriesB.add(new Year(2006), new Integer(202006)); this.seriesB.add(new Year(2007), new Integer(202007)); this.seriesB.add(new Year(2008), new Integer(202008)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesC = new TimeSeries("Series C", Year.class); try { this.seriesC.add(new Year(1999), new Integer(301999)); this.seriesC.add(new Year(2000), new Integer(302000)); this.seriesC.add(new Year(2002), new Integer(302002)); } catch (SeriesException e) { System.err.println("Problem creating series."); } } /** * Sets the flag to indicate that a {@link SeriesChangeEvent} has been * received. * * @param event the event. */ public void seriesChanged(SeriesChangeEvent event) { this.gotSeriesChangeEvent = true; } /** * Check that cloning works. */ public void testClone() { TimeSeries series = new TimeSeries("Test Series"); RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002); try { series.add(jan1st2002, new Integer(42)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } TimeSeries clone = null; try { clone = (TimeSeries) series.clone(); clone.setKey("Clone Series"); try { clone.update(jan1st2002, new Integer(10)); } catch (SeriesException e) { e.printStackTrace(); } } catch (CloneNotSupportedException e) { assertTrue(false); } int seriesValue = series.getValue(jan1st2002).intValue(); int cloneValue = Integer.MAX_VALUE; if (clone != null) { cloneValue = clone.getValue(jan1st2002).intValue(); } assertEquals(42, seriesValue); assertEquals(10, cloneValue); assertEquals("Test Series", series.getKey()); if (clone != null) { assertEquals("Clone Series", clone.getKey()); } else { assertTrue(false); } } /** * Another test of the clone() method. */ public void testClone2() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2007), 100.0); s1.add(new Year(2008), null); s1.add(new Year(2009), 200.0); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.addOrUpdate(new Year(2009), 300.0); assertFalse(s1.equals(s2)); s1.addOrUpdate(new Year(2009), 300.0); assertTrue(s1.equals(s2)); } /** * Add a value to series A for 1999. It should be added at index 0. */ public void testAddValue() { try { this.seriesA.add(new Year(1999), new Integer(1)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } int value = this.seriesA.getValue(0).intValue(); assertEquals(1, value); } /** * Tests the retrieval of values. */ public void testGetValue() { Number value1 = this.seriesA.getValue(new Year(1999)); assertNull(value1); int value2 = this.seriesA.getValue(new Year(2000)).intValue(); assertEquals(102000, value2); } /** * Tests the deletion of values. */ public void testDelete() { this.seriesA.delete(0, 0); assertEquals(5, this.seriesA.getItemCount()); Number value = this.seriesA.getValue(new Year(2000)); assertNull(value); } /** * Basic tests for the delete() method. */ public void testDelete2() { TimeSeries s1 = new TimeSeries("Series", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.addChangeListener(this); this.gotSeriesChangeEvent = false; s1.delete(new Year(2001)); assertTrue(this.gotSeriesChangeEvent); assertEquals(2, s1.getItemCount()); assertEquals(null, s1.getValue(new Year(2001))); // try deleting a time period that doesn't exist... this.gotSeriesChangeEvent = false; s1.delete(new Year(2006)); assertFalse(this.gotSeriesChangeEvent); // try deleting null try { s1.delete(null); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimeSeries s1 = new TimeSeries("A test", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); TimeSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); s2 = (TimeSeries) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(s1.equals(s2)); } /** * Tests the equals method. */ public void testEquals() { TimeSeries s1 = new TimeSeries("Time Series 1"); TimeSeries s2 = new TimeSeries("Time Series 2"); boolean b1 = s1.equals(s2); assertFalse("b1", b1); s2.setKey("Time Series 1"); boolean b2 = s1.equals(s2); assertTrue("b2", b2); RegularTimePeriod p1 = new Day(); RegularTimePeriod p2 = p1.next(); s1.add(p1, 100.0); s1.add(p2, 200.0); boolean b3 = s1.equals(s2); assertFalse("b3", b3); s2.add(p1, 100.0); s2.add(p2, 200.0); boolean b4 = s1.equals(s2); assertTrue("b4", b4); s1.setMaximumItemCount(100); boolean b5 = s1.equals(s2); assertFalse("b5", b5); s2.setMaximumItemCount(100); boolean b6 = s1.equals(s2); assertTrue("b6", b6); s1.setMaximumItemAge(100); boolean b7 = s1.equals(s2); assertFalse("b7", b7); s2.setMaximumItemAge(100); boolean b8 = s1.equals(s2); assertTrue("b8", b8); } /** * Tests a specific bug report where null arguments in the constructor * cause the equals() method to fail. Fixed for 0.9.21. */ public void testEquals2() { TimeSeries s1 = new TimeSeries("Series", null, null, Day.class); TimeSeries s2 = new TimeSeries("Series", null, null, Day.class); assertTrue(s1.equals(s2)); } /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy a range before the start of the series data... TimeSeries result1 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2002)); assertEquals(0, result1.getItemCount()); // copy a range that includes only the first item in the series... TimeSeries result2 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result2.getItemCount()); // copy a range that begins before and ends in the middle of the // series... TimeSeries result3 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result3.getItemCount()); TimeSeries result4 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result4.getItemCount()); TimeSeries result5 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result5.getItemCount()); TimeSeries result6 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result6.getItemCount()); TimeSeries result7 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result7.getItemCount()); TimeSeries result8 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result8.getItemCount()); TimeSeries result9 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result9.getItemCount()); TimeSeries result10 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(3, result10.getItemCount()); TimeSeries result11 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(3, result11.getItemCount()); TimeSeries result12 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(1, result12.getItemCount()); TimeSeries result13 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(1, result13.getItemCount()); TimeSeries result14 = series.createCopy( new Month(MonthConstants.JANUARY, 2004), new Month(MonthConstants.MARCH, 2004)); assertEquals(0, result14.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Some tests to ensure that the createCopy(int, int) method is * functioning correctly. */ public void testCreateCopy2() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy just the first item... TimeSeries result1 = series.createCopy(0, 0); assertEquals(new Month(1, 2003), result1.getTimePeriod(0)); // copy the first two items... result1 = series.createCopy(0, 1); assertEquals(new Month(2, 2003), result1.getTimePeriod(1)); // copy the middle three items... result1 = series.createCopy(1, 3); assertEquals(new Month(2, 2003), result1.getTimePeriod(0)); assertEquals(new Month(11, 2003), result1.getTimePeriod(2)); // copy the last two items... result1 = series.createCopy(3, 4); assertEquals(new Month(11, 2003), result1.getTimePeriod(0)); assertEquals(new Month(12, 2003), result1.getTimePeriod(1)); // copy the last item... result1 = series.createCopy(4, 4); assertEquals(new Month(12, 2003), result1.getTimePeriod(0)); } catch (CloneNotSupportedException e) { assertTrue(false); } // check negative first argument boolean pass = false; try { /* TimeSeries result = */ series.createCopy(-1, 1); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); // check second argument less than first argument pass = false; try { /* TimeSeries result = */ series.createCopy(1, 0); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); TimeSeries series2 = new TimeSeries("Series 2"); try { TimeSeries series3 = series2.createCopy(99, 999); assertEquals(0, series3.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); assertTrue(s1.getItemCount() == 5); s1.setMaximumItemCount(3); assertTrue(s1.getItemCount() == 3); TimeSeriesDataItem item = s1.getDataItem(0); assertTrue(item.getPeriod().equals(new Year(2002))); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2000), 100.0); assertEquals(1, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 101.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 102.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2002), 103.0); assertEquals(2, s1.getItemCount()); } /** * A test for the bug report 1075255. */ public void testBug1075255() { TimeSeries ts = new TimeSeries("dummy", FixedMillisecond.class); ts.add(new FixedMillisecond(0L), 0.0); TimeSeries ts2 = new TimeSeries("dummy2", FixedMillisecond.class); ts2.add(new FixedMillisecond(0L), 1.0); try { ts.addAndOrUpdate(ts2); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } assertEquals(1, ts.getItemCount()); } /** * A test for bug 1832432. */ public void testBug1832432() { TimeSeries s1 = new TimeSeries("Series"); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); // test independence s1.add(new Day(1, 1, 2007), 100.0); assertFalse(s1.equals(s2)); } /** * Some checks for the getIndex() method. */ public void testGetIndex() { TimeSeries series = new TimeSeries("Series", Month.class); assertEquals(-1, series.getIndex(new Month(1, 2003))); series.add(new Month(1, 2003), 45.0); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(-2, series.getIndex(new Month(2, 2003))); series.add(new Month(3, 2003), 55.0); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-2, series.getIndex(new Month(2, 2003))); assertEquals(1, series.getIndex(new Month(3, 2003))); assertEquals(-3, series.getIndex(new Month(4, 2003))); } /** * Some checks for the getDataItem(int) method. */ public void testGetDataItem1() { TimeSeries series = new TimeSeries("S", Year.class); // can't get anything yet...just an exception boolean pass = false; try { /*TimeSeriesDataItem item =*/ series.getDataItem(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); series.add(new Year(2006), 100.0); TimeSeriesDataItem item = series.getDataItem(0); assertEquals(new Year(2006), item.getPeriod()); pass = false; try { /*item = */series.getDataItem(-1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); pass = false; try { /*item = */series.getDataItem(1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getDataItem(RegularTimePeriod) method. */ public void testGetDataItem2() { TimeSeries series = new TimeSeries("S", Year.class); assertNull(series.getDataItem(new Year(2006))); // try a null argument boolean pass = false; try { /* TimeSeriesDataItem item = */ series.getDataItem(null); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the removeAgedItems() method. */ public void testRemoveAgedItems() { TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with one item series.add(new Year(1999), 1.0); series.setMaximumItemAge(0); this.gotSeriesChangeEvent = false; series.removeAgedItems(true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with two items series.setMaximumItemAge(10); series.add(new Year(2001), 2.0); this.gotSeriesChangeEvent = false; series.setMaximumItemAge(2); assertEquals(2, series.getItemCount()); assertEquals(0, series.getIndex(new Year(1999))); assertFalse(this.gotSeriesChangeEvent); series.setMaximumItemAge(1); assertEquals(1, series.getItemCount()); assertEquals(0, series.getIndex(new Year(2001))); assertTrue(this.gotSeriesChangeEvent); } /** * Some checks for the removeAgedItems(long, boolean) method. */ public void testRemoveAgedItems2() { long y2006 = 1157087372534L; // milliseconds somewhere in 2006 TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test a series with 1 item series.add(new Year(2004), 1.0); series.setMaximumItemAge(1); this.gotSeriesChangeEvent = false; series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); // test a series with two items series.setMaximumItemAge(2); series.add(new Year(2003), 1.0); series.add(new Year(2005), 2.0); assertEquals(2, series.getItemCount()); this.gotSeriesChangeEvent = false; assertEquals(2, series.getItemCount()); series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(2, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(1, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { TimeSeries s1 = new TimeSeries("Test"); TimeSeries s2 = new TimeSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(1, 1, 2007), 500.0); s2.add(new Day(1, 1, 2007), 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(2, 1, 2007), null); s2.add(new Day(2, 1, 2007), null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(5, 1, 2007), 111.0); s2.add(new Day(5, 1, 2007), 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(9, 1, 2007), 1.0); s2.add(new Day(9, 1, 2007), 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } /** * Test for bug report 1864222. */ public void testBug1864222() { TimeSeries s = new TimeSeries("S"); s.add(new Day(19, 8, 2005), 1); s.add(new Day(31, 1, 2006), 1); boolean pass = true; try { s.createCopy(new Day(1, 12, 2005), new Day(18, 1, 2006)); } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); } }
// You are a professional Java test case writer, please create a test case named `testBug1864222` for the issue `Chart-818`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-818 // // ## Issue-Title: // #818 Error on TimeSeries createCopy() method // // // // // // ## Issue-Description: // The test case at the end fails with : // // // java.lang.IllegalArgumentException: Requires start <= end. // // // The problem is in that the int start and end indexes corresponding to given timePeriod are computed incorectly. Here I would expect an empty serie to be returned, not an exception. This is with jfreechart 1.0.7 // // // public class foo { // // static public void main(String args[]) { // // TimeSeries foo = new TimeSeries("foo",Day.class); // // foo.add(new Day(19,4,2005),1); // // foo.add(new Day(25,5,2005),1); // // foo.add(new Day(28,5,2005),1); // // foo.add(new Day(30,5,2005),1); // // foo.add(new Day(1,6,2005),1); // // foo.add(new Day(3,6,2005),1); // // foo.add(new Day(19,8,2005),1); // // foo.add(new Day(31,1,2006),1); // // // // ``` // try \{ // TimeSeries bar = foo.createCopy\(new Day\(1,12,2005\),new Day\(18,1,2006\)\); // \} catch \(CloneNotSupportedException e\) \{ // // e.printStackTrace\(\); // // ``` // // } // // } // // // // public void testBug1864222() {
834
/** * Test for bug report 1864222. */
9
822
tests/org/jfree/data/time/junit/TimeSeriesTests.java
tests
```markdown ## Issue-ID: Chart-818 ## Issue-Title: #818 Error on TimeSeries createCopy() method ## Issue-Description: The test case at the end fails with : java.lang.IllegalArgumentException: Requires start <= end. The problem is in that the int start and end indexes corresponding to given timePeriod are computed incorectly. Here I would expect an empty serie to be returned, not an exception. This is with jfreechart 1.0.7 public class foo { static public void main(String args[]) { TimeSeries foo = new TimeSeries("foo",Day.class); foo.add(new Day(19,4,2005),1); foo.add(new Day(25,5,2005),1); foo.add(new Day(28,5,2005),1); foo.add(new Day(30,5,2005),1); foo.add(new Day(1,6,2005),1); foo.add(new Day(3,6,2005),1); foo.add(new Day(19,8,2005),1); foo.add(new Day(31,1,2006),1); ``` try \{ TimeSeries bar = foo.createCopy\(new Day\(1,12,2005\),new Day\(18,1,2006\)\); \} catch \(CloneNotSupportedException e\) \{ e.printStackTrace\(\); ``` } } ``` You are a professional Java test case writer, please create a test case named `testBug1864222` for the issue `Chart-818`, utilizing the provided issue report information and the following function signature. ```java public void testBug1864222() { ```
822
[ "org.jfree.data.time.TimeSeries" ]
2c5c58b25e1ed2c397339c551257aacde8b6af3fdec9f290867a48a13ee5af2b
public void testBug1864222()
// You are a professional Java test case writer, please create a test case named `testBug1864222` for the issue `Chart-818`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-818 // // ## Issue-Title: // #818 Error on TimeSeries createCopy() method // // // // // // ## Issue-Description: // The test case at the end fails with : // // // java.lang.IllegalArgumentException: Requires start <= end. // // // The problem is in that the int start and end indexes corresponding to given timePeriod are computed incorectly. Here I would expect an empty serie to be returned, not an exception. This is with jfreechart 1.0.7 // // // public class foo { // // static public void main(String args[]) { // // TimeSeries foo = new TimeSeries("foo",Day.class); // // foo.add(new Day(19,4,2005),1); // // foo.add(new Day(25,5,2005),1); // // foo.add(new Day(28,5,2005),1); // // foo.add(new Day(30,5,2005),1); // // foo.add(new Day(1,6,2005),1); // // foo.add(new Day(3,6,2005),1); // // foo.add(new Day(19,8,2005),1); // // foo.add(new Day(31,1,2006),1); // // // // ``` // try \{ // TimeSeries bar = foo.createCopy\(new Day\(1,12,2005\),new Day\(18,1,2006\)\); // \} catch \(CloneNotSupportedException e\) \{ // // e.printStackTrace\(\); // // ``` // // } // // } // // // //
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * TimeSeriesTests.java * -------------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Nov-2001 : Version 1 (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Added serialization test (DG); * 15-Oct-2003 : Added test for setMaximumItemCount method (DG); * 23-Aug-2004 : Added test that highlights a bug where the addOrUpdate() * method can lead to more than maximumItemCount items in the * dataset (DG); * 24-May-2006 : Added new tests (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * 31-Oct-2007 : New hashCode() test (DG); * 21-Nov-2007 : Added testBug1832432() and testClone2() (DG); * 10-Jan-2008 : Added testBug1864222() (DG); * */ package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; /** * A collection of test cases for the {@link TimeSeries} class. */ public class TimeSeriesTests extends TestCase implements SeriesChangeListener { /** A time series. */ private TimeSeries seriesA; /** A time series. */ private TimeSeries seriesB; /** A time series. */ private TimeSeries seriesC; /** A flag that indicates whether or not a change event was fired. */ private boolean gotSeriesChangeEvent = false; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimeSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimeSeriesTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.seriesA = new TimeSeries("Series A", Year.class); try { this.seriesA.add(new Year(2000), new Integer(102000)); this.seriesA.add(new Year(2001), new Integer(102001)); this.seriesA.add(new Year(2002), new Integer(102002)); this.seriesA.add(new Year(2003), new Integer(102003)); this.seriesA.add(new Year(2004), new Integer(102004)); this.seriesA.add(new Year(2005), new Integer(102005)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesB = new TimeSeries("Series B", Year.class); try { this.seriesB.add(new Year(2006), new Integer(202006)); this.seriesB.add(new Year(2007), new Integer(202007)); this.seriesB.add(new Year(2008), new Integer(202008)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesC = new TimeSeries("Series C", Year.class); try { this.seriesC.add(new Year(1999), new Integer(301999)); this.seriesC.add(new Year(2000), new Integer(302000)); this.seriesC.add(new Year(2002), new Integer(302002)); } catch (SeriesException e) { System.err.println("Problem creating series."); } } /** * Sets the flag to indicate that a {@link SeriesChangeEvent} has been * received. * * @param event the event. */ public void seriesChanged(SeriesChangeEvent event) { this.gotSeriesChangeEvent = true; } /** * Check that cloning works. */ public void testClone() { TimeSeries series = new TimeSeries("Test Series"); RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002); try { series.add(jan1st2002, new Integer(42)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } TimeSeries clone = null; try { clone = (TimeSeries) series.clone(); clone.setKey("Clone Series"); try { clone.update(jan1st2002, new Integer(10)); } catch (SeriesException e) { e.printStackTrace(); } } catch (CloneNotSupportedException e) { assertTrue(false); } int seriesValue = series.getValue(jan1st2002).intValue(); int cloneValue = Integer.MAX_VALUE; if (clone != null) { cloneValue = clone.getValue(jan1st2002).intValue(); } assertEquals(42, seriesValue); assertEquals(10, cloneValue); assertEquals("Test Series", series.getKey()); if (clone != null) { assertEquals("Clone Series", clone.getKey()); } else { assertTrue(false); } } /** * Another test of the clone() method. */ public void testClone2() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2007), 100.0); s1.add(new Year(2008), null); s1.add(new Year(2009), 200.0); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.addOrUpdate(new Year(2009), 300.0); assertFalse(s1.equals(s2)); s1.addOrUpdate(new Year(2009), 300.0); assertTrue(s1.equals(s2)); } /** * Add a value to series A for 1999. It should be added at index 0. */ public void testAddValue() { try { this.seriesA.add(new Year(1999), new Integer(1)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } int value = this.seriesA.getValue(0).intValue(); assertEquals(1, value); } /** * Tests the retrieval of values. */ public void testGetValue() { Number value1 = this.seriesA.getValue(new Year(1999)); assertNull(value1); int value2 = this.seriesA.getValue(new Year(2000)).intValue(); assertEquals(102000, value2); } /** * Tests the deletion of values. */ public void testDelete() { this.seriesA.delete(0, 0); assertEquals(5, this.seriesA.getItemCount()); Number value = this.seriesA.getValue(new Year(2000)); assertNull(value); } /** * Basic tests for the delete() method. */ public void testDelete2() { TimeSeries s1 = new TimeSeries("Series", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.addChangeListener(this); this.gotSeriesChangeEvent = false; s1.delete(new Year(2001)); assertTrue(this.gotSeriesChangeEvent); assertEquals(2, s1.getItemCount()); assertEquals(null, s1.getValue(new Year(2001))); // try deleting a time period that doesn't exist... this.gotSeriesChangeEvent = false; s1.delete(new Year(2006)); assertFalse(this.gotSeriesChangeEvent); // try deleting null try { s1.delete(null); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimeSeries s1 = new TimeSeries("A test", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); TimeSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); s2 = (TimeSeries) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(s1.equals(s2)); } /** * Tests the equals method. */ public void testEquals() { TimeSeries s1 = new TimeSeries("Time Series 1"); TimeSeries s2 = new TimeSeries("Time Series 2"); boolean b1 = s1.equals(s2); assertFalse("b1", b1); s2.setKey("Time Series 1"); boolean b2 = s1.equals(s2); assertTrue("b2", b2); RegularTimePeriod p1 = new Day(); RegularTimePeriod p2 = p1.next(); s1.add(p1, 100.0); s1.add(p2, 200.0); boolean b3 = s1.equals(s2); assertFalse("b3", b3); s2.add(p1, 100.0); s2.add(p2, 200.0); boolean b4 = s1.equals(s2); assertTrue("b4", b4); s1.setMaximumItemCount(100); boolean b5 = s1.equals(s2); assertFalse("b5", b5); s2.setMaximumItemCount(100); boolean b6 = s1.equals(s2); assertTrue("b6", b6); s1.setMaximumItemAge(100); boolean b7 = s1.equals(s2); assertFalse("b7", b7); s2.setMaximumItemAge(100); boolean b8 = s1.equals(s2); assertTrue("b8", b8); } /** * Tests a specific bug report where null arguments in the constructor * cause the equals() method to fail. Fixed for 0.9.21. */ public void testEquals2() { TimeSeries s1 = new TimeSeries("Series", null, null, Day.class); TimeSeries s2 = new TimeSeries("Series", null, null, Day.class); assertTrue(s1.equals(s2)); } /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy a range before the start of the series data... TimeSeries result1 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2002)); assertEquals(0, result1.getItemCount()); // copy a range that includes only the first item in the series... TimeSeries result2 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result2.getItemCount()); // copy a range that begins before and ends in the middle of the // series... TimeSeries result3 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result3.getItemCount()); TimeSeries result4 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result4.getItemCount()); TimeSeries result5 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result5.getItemCount()); TimeSeries result6 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result6.getItemCount()); TimeSeries result7 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result7.getItemCount()); TimeSeries result8 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result8.getItemCount()); TimeSeries result9 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result9.getItemCount()); TimeSeries result10 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(3, result10.getItemCount()); TimeSeries result11 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(3, result11.getItemCount()); TimeSeries result12 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(1, result12.getItemCount()); TimeSeries result13 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(1, result13.getItemCount()); TimeSeries result14 = series.createCopy( new Month(MonthConstants.JANUARY, 2004), new Month(MonthConstants.MARCH, 2004)); assertEquals(0, result14.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Some tests to ensure that the createCopy(int, int) method is * functioning correctly. */ public void testCreateCopy2() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy just the first item... TimeSeries result1 = series.createCopy(0, 0); assertEquals(new Month(1, 2003), result1.getTimePeriod(0)); // copy the first two items... result1 = series.createCopy(0, 1); assertEquals(new Month(2, 2003), result1.getTimePeriod(1)); // copy the middle three items... result1 = series.createCopy(1, 3); assertEquals(new Month(2, 2003), result1.getTimePeriod(0)); assertEquals(new Month(11, 2003), result1.getTimePeriod(2)); // copy the last two items... result1 = series.createCopy(3, 4); assertEquals(new Month(11, 2003), result1.getTimePeriod(0)); assertEquals(new Month(12, 2003), result1.getTimePeriod(1)); // copy the last item... result1 = series.createCopy(4, 4); assertEquals(new Month(12, 2003), result1.getTimePeriod(0)); } catch (CloneNotSupportedException e) { assertTrue(false); } // check negative first argument boolean pass = false; try { /* TimeSeries result = */ series.createCopy(-1, 1); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); // check second argument less than first argument pass = false; try { /* TimeSeries result = */ series.createCopy(1, 0); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); TimeSeries series2 = new TimeSeries("Series 2"); try { TimeSeries series3 = series2.createCopy(99, 999); assertEquals(0, series3.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); assertTrue(s1.getItemCount() == 5); s1.setMaximumItemCount(3); assertTrue(s1.getItemCount() == 3); TimeSeriesDataItem item = s1.getDataItem(0); assertTrue(item.getPeriod().equals(new Year(2002))); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2000), 100.0); assertEquals(1, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 101.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 102.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2002), 103.0); assertEquals(2, s1.getItemCount()); } /** * A test for the bug report 1075255. */ public void testBug1075255() { TimeSeries ts = new TimeSeries("dummy", FixedMillisecond.class); ts.add(new FixedMillisecond(0L), 0.0); TimeSeries ts2 = new TimeSeries("dummy2", FixedMillisecond.class); ts2.add(new FixedMillisecond(0L), 1.0); try { ts.addAndOrUpdate(ts2); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } assertEquals(1, ts.getItemCount()); } /** * A test for bug 1832432. */ public void testBug1832432() { TimeSeries s1 = new TimeSeries("Series"); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); // test independence s1.add(new Day(1, 1, 2007), 100.0); assertFalse(s1.equals(s2)); } /** * Some checks for the getIndex() method. */ public void testGetIndex() { TimeSeries series = new TimeSeries("Series", Month.class); assertEquals(-1, series.getIndex(new Month(1, 2003))); series.add(new Month(1, 2003), 45.0); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(-2, series.getIndex(new Month(2, 2003))); series.add(new Month(3, 2003), 55.0); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-2, series.getIndex(new Month(2, 2003))); assertEquals(1, series.getIndex(new Month(3, 2003))); assertEquals(-3, series.getIndex(new Month(4, 2003))); } /** * Some checks for the getDataItem(int) method. */ public void testGetDataItem1() { TimeSeries series = new TimeSeries("S", Year.class); // can't get anything yet...just an exception boolean pass = false; try { /*TimeSeriesDataItem item =*/ series.getDataItem(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); series.add(new Year(2006), 100.0); TimeSeriesDataItem item = series.getDataItem(0); assertEquals(new Year(2006), item.getPeriod()); pass = false; try { /*item = */series.getDataItem(-1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); pass = false; try { /*item = */series.getDataItem(1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getDataItem(RegularTimePeriod) method. */ public void testGetDataItem2() { TimeSeries series = new TimeSeries("S", Year.class); assertNull(series.getDataItem(new Year(2006))); // try a null argument boolean pass = false; try { /* TimeSeriesDataItem item = */ series.getDataItem(null); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the removeAgedItems() method. */ public void testRemoveAgedItems() { TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with one item series.add(new Year(1999), 1.0); series.setMaximumItemAge(0); this.gotSeriesChangeEvent = false; series.removeAgedItems(true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with two items series.setMaximumItemAge(10); series.add(new Year(2001), 2.0); this.gotSeriesChangeEvent = false; series.setMaximumItemAge(2); assertEquals(2, series.getItemCount()); assertEquals(0, series.getIndex(new Year(1999))); assertFalse(this.gotSeriesChangeEvent); series.setMaximumItemAge(1); assertEquals(1, series.getItemCount()); assertEquals(0, series.getIndex(new Year(2001))); assertTrue(this.gotSeriesChangeEvent); } /** * Some checks for the removeAgedItems(long, boolean) method. */ public void testRemoveAgedItems2() { long y2006 = 1157087372534L; // milliseconds somewhere in 2006 TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test a series with 1 item series.add(new Year(2004), 1.0); series.setMaximumItemAge(1); this.gotSeriesChangeEvent = false; series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); // test a series with two items series.setMaximumItemAge(2); series.add(new Year(2003), 1.0); series.add(new Year(2005), 2.0); assertEquals(2, series.getItemCount()); this.gotSeriesChangeEvent = false; assertEquals(2, series.getItemCount()); series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(2, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(1, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { TimeSeries s1 = new TimeSeries("Test"); TimeSeries s2 = new TimeSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(1, 1, 2007), 500.0); s2.add(new Day(1, 1, 2007), 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(2, 1, 2007), null); s2.add(new Day(2, 1, 2007), null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(5, 1, 2007), 111.0); s2.add(new Day(5, 1, 2007), 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(9, 1, 2007), 1.0); s2.add(new Day(9, 1, 2007), 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } /** * Test for bug report 1864222. */ public void testBug1864222() { TimeSeries s = new TimeSeries("S"); s.add(new Day(19, 8, 2005), 1); s.add(new Day(31, 1, 2006), 1); boolean pass = true; try { s.createCopy(new Day(1, 12, 2005), new Day(18, 1, 2006)); } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); } }
public void testMath369() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BisectionSolver(); assertEquals(Math.PI, solver.solve(f, 3.0, 3.2, 3.1), solver.getAbsoluteAccuracy()); }
org.apache.commons.math.analysis.solvers.BisectionSolverTest::testMath369
src/test/java/org/apache/commons/math/analysis/solvers/BisectionSolverTest.java
101
src/test/java/org/apache/commons/math/analysis/solvers/BisectionSolverTest.java
testMath369
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.solvers; import org.apache.commons.math.MathException; import org.apache.commons.math.analysis.QuinticFunction; import org.apache.commons.math.analysis.SinFunction; import org.apache.commons.math.analysis.UnivariateRealFunction; import junit.framework.TestCase; /** * @version $Revision$ $Date$ */ public final class BisectionSolverTest extends TestCase { @Deprecated public void testDeprecated() throws MathException { UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BisectionSolver(f); result = solver.solve(3, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); result = solver.solve(1, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); } public void testSinZero() throws MathException { UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BisectionSolver(); result = solver.solve(f, 3, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); result = solver.solve(f, 1, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); } public void testQuinticZero() throws MathException { UnivariateRealFunction f = new QuinticFunction(); double result; UnivariateRealSolver solver = new BisectionSolver(); result = solver.solve(f, -0.2, 0.2); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = solver.solve(f, -0.1, 0.3); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = solver.solve(f, -0.3, 0.45); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.3, 0.7); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.2, 0.6); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.05, 0.95); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.85, 1.25); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.8, 1.2); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.85, 1.75); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.55, 1.45); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.85, 5); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertEquals(result, solver.getResult(), 0); assertTrue(solver.getIterationCount() > 0); } public void testMath369() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BisectionSolver(); assertEquals(Math.PI, solver.solve(f, 3.0, 3.2, 3.1), solver.getAbsoluteAccuracy()); } /** * */ public void testSetFunctionValueAccuracy(){ double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setFunctionValueAccuracy(expected); assertEquals(expected, solver.getFunctionValueAccuracy(), 1.0e-2); } /** * */ public void testResetFunctionValueAccuracy(){ double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getFunctionValueAccuracy(); solver.setFunctionValueAccuracy(newValue); solver.resetFunctionValueAccuracy(); assertEquals(oldValue, solver.getFunctionValueAccuracy(), 1.0e-2); } /** * */ public void testSetAbsoluteAccuracy(){ double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setAbsoluteAccuracy(expected); assertEquals(expected, solver.getAbsoluteAccuracy(), 1.0e-2); } /** * */ public void testResetAbsoluteAccuracy(){ double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getAbsoluteAccuracy(); solver.setAbsoluteAccuracy(newValue); solver.resetAbsoluteAccuracy(); assertEquals(oldValue, solver.getAbsoluteAccuracy(), 1.0e-2); } /** * */ public void testSetMaximalIterationCount(){ int expected = 100; UnivariateRealSolver solver = new BisectionSolver(); solver.setMaximalIterationCount(expected); assertEquals(expected, solver.getMaximalIterationCount()); } /** * */ public void testResetMaximalIterationCount(){ int newValue = 10000; UnivariateRealSolver solver = new BisectionSolver(); int oldValue = solver.getMaximalIterationCount(); solver.setMaximalIterationCount(newValue); solver.resetMaximalIterationCount(); assertEquals(oldValue, solver.getMaximalIterationCount()); } /** * */ public void testSetRelativeAccuracy(){ double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setRelativeAccuracy(expected); assertEquals(expected, solver.getRelativeAccuracy(), 1.0e-2); } /** * */ public void testResetRelativeAccuracy(){ double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getRelativeAccuracy(); solver.setRelativeAccuracy(newValue); solver.resetRelativeAccuracy(); assertEquals(oldValue, solver.getRelativeAccuracy(), 1.0e-2); } }
// You are a professional Java test case writer, please create a test case named `testMath369` for the issue `Math-MATH-369`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-369 // // ## Issue-Title: // BisectionSolver.solve(final UnivariateRealFunction f, double min, double max, double initial) throws NullPointerException // // ## Issue-Description: // // Method // // // BisectionSolver.solve(final UnivariateRealFunction f, double min, double max, double initial) // // // invokes // // // BisectionSolver.solve(double min, double max) // // // which throws NullPointerException, as member variable // // // UnivariateRealSolverImpl.f // // // is null. // // // Instead the method: // // // BisectionSolver.solve(final UnivariateRealFunction f, double min, double max) // // // should be called. // // // Steps to reproduce: // // // invoke: // // // new BisectionSolver().solve(someUnivariateFunctionImpl, 0.0, 1.0, 0.5); // // // NullPointerException will be thrown. // // // // // public void testMath369() throws Exception {
101
70
97
src/test/java/org/apache/commons/math/analysis/solvers/BisectionSolverTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-369 ## Issue-Title: BisectionSolver.solve(final UnivariateRealFunction f, double min, double max, double initial) throws NullPointerException ## Issue-Description: Method BisectionSolver.solve(final UnivariateRealFunction f, double min, double max, double initial) invokes BisectionSolver.solve(double min, double max) which throws NullPointerException, as member variable UnivariateRealSolverImpl.f is null. Instead the method: BisectionSolver.solve(final UnivariateRealFunction f, double min, double max) should be called. Steps to reproduce: invoke: new BisectionSolver().solve(someUnivariateFunctionImpl, 0.0, 1.0, 0.5); NullPointerException will be thrown. ``` You are a professional Java test case writer, please create a test case named `testMath369` for the issue `Math-MATH-369`, utilizing the provided issue report information and the following function signature. ```java public void testMath369() throws Exception { ```
97
[ "org.apache.commons.math.analysis.solvers.BisectionSolver" ]
2d74eab122b5278c2012a64c9a801d8c9a27951fc1fc2001e8419d988034e5fe
public void testMath369() throws Exception
// You are a professional Java test case writer, please create a test case named `testMath369` for the issue `Math-MATH-369`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-369 // // ## Issue-Title: // BisectionSolver.solve(final UnivariateRealFunction f, double min, double max, double initial) throws NullPointerException // // ## Issue-Description: // // Method // // // BisectionSolver.solve(final UnivariateRealFunction f, double min, double max, double initial) // // // invokes // // // BisectionSolver.solve(double min, double max) // // // which throws NullPointerException, as member variable // // // UnivariateRealSolverImpl.f // // // is null. // // // Instead the method: // // // BisectionSolver.solve(final UnivariateRealFunction f, double min, double max) // // // should be called. // // // Steps to reproduce: // // // invoke: // // // new BisectionSolver().solve(someUnivariateFunctionImpl, 0.0, 1.0, 0.5); // // // NullPointerException will be thrown. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.solvers; import org.apache.commons.math.MathException; import org.apache.commons.math.analysis.QuinticFunction; import org.apache.commons.math.analysis.SinFunction; import org.apache.commons.math.analysis.UnivariateRealFunction; import junit.framework.TestCase; /** * @version $Revision$ $Date$ */ public final class BisectionSolverTest extends TestCase { @Deprecated public void testDeprecated() throws MathException { UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BisectionSolver(f); result = solver.solve(3, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); result = solver.solve(1, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); } public void testSinZero() throws MathException { UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BisectionSolver(); result = solver.solve(f, 3, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); result = solver.solve(f, 1, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); } public void testQuinticZero() throws MathException { UnivariateRealFunction f = new QuinticFunction(); double result; UnivariateRealSolver solver = new BisectionSolver(); result = solver.solve(f, -0.2, 0.2); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = solver.solve(f, -0.1, 0.3); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = solver.solve(f, -0.3, 0.45); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.3, 0.7); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.2, 0.6); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.05, 0.95); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.85, 1.25); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.8, 1.2); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.85, 1.75); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.55, 1.45); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); result = solver.solve(f, 0.85, 5); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertEquals(result, solver.getResult(), 0); assertTrue(solver.getIterationCount() > 0); } public void testMath369() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BisectionSolver(); assertEquals(Math.PI, solver.solve(f, 3.0, 3.2, 3.1), solver.getAbsoluteAccuracy()); } /** * */ public void testSetFunctionValueAccuracy(){ double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setFunctionValueAccuracy(expected); assertEquals(expected, solver.getFunctionValueAccuracy(), 1.0e-2); } /** * */ public void testResetFunctionValueAccuracy(){ double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getFunctionValueAccuracy(); solver.setFunctionValueAccuracy(newValue); solver.resetFunctionValueAccuracy(); assertEquals(oldValue, solver.getFunctionValueAccuracy(), 1.0e-2); } /** * */ public void testSetAbsoluteAccuracy(){ double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setAbsoluteAccuracy(expected); assertEquals(expected, solver.getAbsoluteAccuracy(), 1.0e-2); } /** * */ public void testResetAbsoluteAccuracy(){ double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getAbsoluteAccuracy(); solver.setAbsoluteAccuracy(newValue); solver.resetAbsoluteAccuracy(); assertEquals(oldValue, solver.getAbsoluteAccuracy(), 1.0e-2); } /** * */ public void testSetMaximalIterationCount(){ int expected = 100; UnivariateRealSolver solver = new BisectionSolver(); solver.setMaximalIterationCount(expected); assertEquals(expected, solver.getMaximalIterationCount()); } /** * */ public void testResetMaximalIterationCount(){ int newValue = 10000; UnivariateRealSolver solver = new BisectionSolver(); int oldValue = solver.getMaximalIterationCount(); solver.setMaximalIterationCount(newValue); solver.resetMaximalIterationCount(); assertEquals(oldValue, solver.getMaximalIterationCount()); } /** * */ public void testSetRelativeAccuracy(){ double expected = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); solver.setRelativeAccuracy(expected); assertEquals(expected, solver.getRelativeAccuracy(), 1.0e-2); } /** * */ public void testResetRelativeAccuracy(){ double newValue = 1.0e-2; UnivariateRealSolver solver = new BisectionSolver(); double oldValue = solver.getRelativeAccuracy(); solver.setRelativeAccuracy(newValue); solver.resetRelativeAccuracy(); assertEquals(oldValue, solver.getRelativeAccuracy(), 1.0e-2); } }
public void testIssue1101a() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return modifiyX() + a;} foo(x);", "foo", INLINE_DIRECT); }
com.google.javascript.jscomp.FunctionInjectorTest::testIssue1101a
test/com/google/javascript/jscomp/FunctionInjectorTest.java
1,349
test/com/google/javascript/jscomp/FunctionInjectorTest.java
testIssue1101a
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.FunctionInjector.CanInlineResult; import com.google.javascript.jscomp.FunctionInjector.InliningMode; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.util.List; import java.util.Set; /** * Inline function tests. * @author johnlenz@google.com (John Lenz) */ public class FunctionInjectorTest extends TestCase { static final InliningMode INLINE_DIRECT = InliningMode.DIRECT; static final InliningMode INLINE_BLOCK = InliningMode.BLOCK; private boolean assumeStrictThis = false; private boolean assumeMinimumCapture = false; @Override protected void setUp() throws Exception { super.setUp(); assumeStrictThis = false; } private FunctionInjector getInjector() { Compiler compiler = new Compiler(); return new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), true, assumeStrictThis, assumeMinimumCapture); } public void testIsSimpleFunction1() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){}"))); } public void testIsSimpleFunction2() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return 0;}"))); } public void testIsSimpleFunction3() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return x ? 0 : 1}"))); } public void testIsSimpleFunction4() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return;}"))); } public void testIsSimpleFunction5() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return 0; return 0;}"))); } public void testIsSimpleFunction6() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){var x=true;return x ? 0 : 1}"))); } public void testIsSimpleFunction7() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){if (x) return 0; else return 1}"))); } public void testCanInlineReferenceToFunction1() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction2() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction3() { // NOTE: FoldConstants will convert this to a empty function, // so there is no need to explicitly support it. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return;}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction4() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return;}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction5() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction6() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction7() { // In var initialization. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x=foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction8() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction9() { // In assignment. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction10() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction11() { // In expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction12() { // "foo" is not known to be side-effect free, it might change the value // of "x", so it can't be inlined. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction12b() { // "foo" is not known to be side-effect free, it might change the value // of "x", so it can't be inlined. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunction13() { // // ... if foo is side-effect free we can inline here. // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(){return true;};" + // "var x; x=x+foo();", "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunction14() { // Simple call with parameters helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; foo(x);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction15() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; foo(x);", "foo", INLINE_BLOCK); } // TODO(johnlenz): remove this constant once this has been proven in // production code. static final CanInlineResult NEW_VARS_IN_GLOBAL_SCOPE = CanInlineResult.YES; public void testCanInlineReferenceToFunction16() { // Function "foo" as it contains "var b" which // must be brought into the global scope. helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){var b;return a;}; foo(goo());", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction17() { // This doesn't bring names into the global name space. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a;}; " + "function x() { foo(goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction18() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a;} foo(x++);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction19() { // Parameter has mutable parameter referenced more than once. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo([]);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction20() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo({});", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction21() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo(new Date);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction22() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo(true && new Date);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction23() { // variables to global scope. helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return a;}; foo(x++);", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction24() { // ... this is OK, because it doesn't introduce a new global name. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a;}; " + "function x() { foo(x++); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction25() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a;}; foo(x++);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction26() { helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return a+a;}; foo(x++);", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction27() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a+a;}; " + "function x() { foo(x++); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction28() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; foo(goo());", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction29() { helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return true;}; foo(goo());", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction30() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo(goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction31() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a) {return true;}; " + "function x() {foo.call(this, 1);}", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction32() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.apply(this, [1]); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction33() { // No special handling is required for method calls passing this. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.bar(this, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction34() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction35() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.apply(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction36() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.bar(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction37() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(null, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction38() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(null, goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(null, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction39() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(bar, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction40() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(bar, goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(bar, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction41() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction42() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction43() { // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction44() { assumeStrictThis = false; // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_BLOCK); assumeStrictThis = true; // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction45() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction46() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction47() { // Call with inner function expression and variable decl. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){var a; return function() {return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction48() { // Call with inner function expression and variable decl. // TODO(johnlenz): should we validate no values in scope? helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){var a; return function() {return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction49() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {var a; return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction50() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {var a; return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction51() { // Call with inner function statement. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){function x() {var a; return true;} return x}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression1() { // Call in if condition helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { if (foo(1)) throw 'test'; }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression2() { // Call in return expression helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { return foo(1); }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression3() { // Call in switch expression helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { switch(foo(1)) { default:break; } }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression4() { // Call in hook condition helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {foo(1)?0:1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression5() { // Call in hook side-effect free condition helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {true?foo(1):1 }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression5a() { // Call in hook side-effect free condition helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {true?foo(1):1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression6() { // Call in expression statement "condition" helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {foo(1) && 1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression7() { // Call in expression statement after side-effect free "condition" helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {1 && foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression7a() { // Call in expression statement after side-effect free "condition" helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {1 && foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression8() { // Call in expression statement after side-effect free operator helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression9() { // Call in VAR expression. helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var b = 1 + foo(1)}", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression10() { // Call in assignment expression. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {var b; b += 1 + foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression10a() { // Call in assignment expression. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var b; b += 1 + foo(1) }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression11() { // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression12() { helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var a,b,c; a = b = c = foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression13() { helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var a,b,c; a = b = c = 1 + foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression14() { // ... foo can not be inlined because of possible changes to "c". helperCanInlineReferenceToFunction(CanInlineResult.NO, "var a = {}, b = {}, c;" + "a.test = 'a';" + "b.test = 'b';" + "c = a;" + "function foo(){c = b; return 'foo'};" + "c.test=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression14a() { // ... foo can be inlined despite possible changes to "c". helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "var a = {}, b = {}, c;" + "a.test = 'a';" + "b.test = 'b';" + "c = a;" + "function foo(){c = b; return 'foo'};" + "c.test=foo();", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression15() { // // ... foo can be inlined as it is side-effect free. // helperCanInlineReferenceToFunction(true, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "c.test=foo();", // "foo", INLINE_BLOCK); // } // public void testCanInlineReferenceToFunctionInExpression16() { // // ... foo can not be inlined because of possible side-effects of x() // helperCanInlineReferenceToFunction(false, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "function x(){return c};" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "x().test=foo();", // "foo", INLINE_BLOCK); // } // public void testCanInlineReferenceToFunctionInExpression17() { // // ... foo can be inlined because of x() is side-effect free. // helperCanInlineReferenceToFunction(true, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "/** @nosideeffects */ function x(){return c};" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "x().test=foo();", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression18() { // Call in within a call helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(){return _g();}; " + "function x() {1 + foo()() }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression19() { // ... unless foo is known to be side-effect free, it might actually // change the value of "_g" which would unfortunately change the behavior, // so we can't inline here. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(foo()) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression19a() { // ... unless foo is known to be side-effect free, it might actually // change the value of "_g" which would unfortunately change the behavior, // so we can't inline here. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(foo()) }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression20() { // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(){return a;}; " + // "function x() {1 + _g(foo()) }", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression21() { // Assignments to object are problematic if the call has side-effects, // as the object that is being referred to can change. // Note: This could be changed be inlined if we in some way make "z" // as not escaping from the local scope. helperCanInlineReferenceToFunction(CanInlineResult.NO, "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression21a() { // Assignments to object are problematic if the call has side-effects, // as the object that is being referred to can change. // Note: This could be changed be inlined if we in some way make "z" // as not escaping from the local scope. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression22() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo()) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression22a() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo()) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression23() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo.call(this)) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression23a() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo.call(this)) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInLoop1() { helperCanInlineReferenceToFunction( CanInlineResult.YES, "function foo(){return a;}; " + "while(1) { foo(); }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInLoop2() { // If function contains function, don't inline it into a loop. // TODO(johnlenz): this can be improved by looking to see // if the inner function contains any references to values defined // in the outer function. helperCanInlineReferenceToFunction( CanInlineResult.NO, "function foo(){return function() {};}; " + "while(1) { foo(); }", "foo", INLINE_BLOCK, true); } public void testInline1() { helperInlineReferenceToFunction( "function foo(){}; foo();", "function foo(){}; void 0", "foo", INLINE_DIRECT); } public void testInline2() { helperInlineReferenceToFunction( "function foo(){}; foo();", "function foo(){}; {}", "foo", INLINE_BLOCK); } public void testInline3() { helperInlineReferenceToFunction( "function foo(){return;}; foo();", "function foo(){return;}; {}", "foo", INLINE_BLOCK); } public void testInline4() { helperInlineReferenceToFunction( "function foo(){return true;}; foo();", "function foo(){return true;}; true;", "foo", INLINE_DIRECT); } public void testInline5() { helperInlineReferenceToFunction( "function foo(){return true;}; foo();", "function foo(){return true;}; {true;}", "foo", INLINE_BLOCK); } public void testInline6() { // In var initialization. helperInlineReferenceToFunction( "function foo(){return true;}; var x=foo();", "function foo(){return true;}; var x=true;", "foo", INLINE_DIRECT); } public void testInline7() { helperInlineReferenceToFunction( "function foo(){return true;}; var x=foo();", "function foo(){return true;}; var x;" + "{x=true}", "foo", INLINE_BLOCK); } public void testInline8() { // In assignment. helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=foo();", "function foo(){return true;}; var x; x=true;", "foo", INLINE_DIRECT); } public void testInline9() { helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=foo();", "function foo(){return true;}; var x;{x=true}", "foo", INLINE_BLOCK); } public void testInline10() { // In expression. helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=x+foo();", "function foo(){return true;}; var x; x=x+true;", "foo", INLINE_DIRECT); } public void testInline11() { // Simple call with parameters helperInlineReferenceToFunction( "function foo(a){return true;}; foo(x);", "function foo(a){return true;}; true;", "foo", INLINE_DIRECT); } public void testInline12() { helperInlineReferenceToFunction( "function foo(a){return true;}; foo(x);", "function foo(a){return true;}; {true}", "foo", INLINE_BLOCK); } public void testInline13() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return a;}; " + "function x() { foo(x++); }", "function foo(a){return a;}; " + "function x() {{var a$$inline_0=x++;" + "a$$inline_0}}", "foo", INLINE_BLOCK); } public void testInline14() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(x++);", "function foo(a){return a+a;}; " + "{var a$$inline_0=x++;" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline15() { // Parameter has mutable, references more than once. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(new Date());", "function foo(a){return a+a;}; " + "{var a$$inline_0=new Date();" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline16() { // Parameter is large, references more than once. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(function(){});", "function foo(a){return a+a;}; " + "{var a$$inline_0=function(){};" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline17() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return true;}; foo(goo());", "function foo(a){return true;};" + "{var a$$inline_0=goo();true}", "foo", INLINE_BLOCK); } public void testInline18() { // This doesn't bring names into the global name space. helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "function x() { foo(goo()); }", "function foo(a){var b;return a;}; " + "function x() {{var a$$inline_0=goo();" + "var b$$inline_1;a$$inline_0}}", "foo", INLINE_BLOCK); } public void testInline19() { // Properly alias. helperInlineReferenceToFunction( "var x = 1; var y = 2;" + "function foo(a,b){x = b; y = a;}; " + "function bar() { foo(x,y); }", "var x = 1; var y = 2;" + "function foo(a,b){x = b; y = a;}; " + "function bar() {" + "{var a$$inline_0=x;" + "x = y;" + "y = a$$inline_0;}" + "}", "foo", INLINE_BLOCK); } public void testInline19b() { helperInlineReferenceToFunction( "var x = 1; var y = 2;" + "function foo(a,b){y = a; x = b;}; " + "function bar() { foo(x,y); }", "var x = 1; var y = 2;" + "function foo(a,b){y = a; x = b;}; " + "function bar() {" + "{var b$$inline_1=y;" + "y = x;" + "x = b$$inline_1;}" + "}", "foo", INLINE_BLOCK); } public void testInlineIntoLoop() { helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "for(;1;){ foo(1); }", "function foo(a){var b;return a;}; " + "for(;1;){ {" + "var b$$inline_1=void 0;1}}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "do{ foo(1); } while(1)", "function foo(a){var b;return a;}; " + "do{ {" + "var b$$inline_1=void 0;1}}while(1)", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){for(var b in c)return a;}; " + "for(;1;){ foo(1); }", "function foo(a){var b;for(b in c)return a;}; " + "for(;1;){ {JSCompiler_inline_label_foo_2:{" + "var b$$inline_1=void 0;for(b$$inline_1 in c){" + "1;break JSCompiler_inline_label_foo_2" + "}}}}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction1() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {return true;}}; foo();", "function foo(){return function() {return true;}};" + "(function() {return true;})", "foo", INLINE_DIRECT); } public void testInlineFunctionWithInnerFunction2() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {return true;}}; foo();", "function foo(){return function() {return true;}};" + "{(function() {return true;})}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction3() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {var a; return true;}}; foo();", "function foo(){return function() {var a; return true;}};" + "(function() {var a; return true;});", "foo", INLINE_DIRECT); } public void testInlineFunctionWithInnerFunction4() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {var a; return true;}}; foo();", "function foo(){return function() {var a; return true;}};" + "{(function() {var a$$inline_0; return true;});}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction5() { // Call with inner function statement. helperInlineReferenceToFunction( "function foo(){function x() {var a; return true;} return x}; foo();", "function foo(){function x(){var a;return true}return x};" + "{var x$$inline_0 = function(){" + "var a$$inline_1;return true};x$$inline_0}", "foo", INLINE_BLOCK); } public void testInlineReferenceInExpression1() { // Call in if condition helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { if (foo(1)) throw 'test'; }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "if (JSCompiler_inline_result$$0) throw 'test'; }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression2() { // Call in return expression helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { return foo(1); }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "return JSCompiler_inline_result$$0; }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression3() { // Call in switch expression helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { switch(foo(1)) { default:break; } }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "switch(JSCompiler_inline_result$$0) { default:break; } }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression4() { // Call in hook condition helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1)?0:1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0?0:1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression5() { // Call in expression statement "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1)&&1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0&&1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression6() { // Call in expression statement after side-effect free "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "1 + JSCompiler_inline_result$$0 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression7() { // Call in expression statement "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1) && 1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0&&1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression8() { // Call in expression statement after side-effect free operator helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=true;}" + "1 + JSCompiler_inline_result$$0 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression9() { // Call in VAR expression. helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {var b = 1 + foo(1)}", "function foo(a){return true;}; " + "function x() { " + "var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=true;}" + "var b = 1 + JSCompiler_inline_result$$0 " + "}", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testInlineReferenceInExpression10() { // // Call in assignment expression. // helperInlineReferenceToFunction( // "/** @nosideeffects */ function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "function foo(a){return true;}; " + // "function x() {var b;" + // "{var JSCompiler_inline_result$$0; " + // "JSCompiler_inline_result$$0=true;}" + // "b += 1 + JSCompiler_inline_result$$0 }", // "foo", INLINE_BLOCK); // } public void testInlineReferenceInExpression11() { // Call under label helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {a:foo(1)?0:1 }", "function foo(a){return true;}; " + "function x() {" + " a:{" + " var JSCompiler_inline_result$$0; " + " {JSCompiler_inline_result$$0=true;}" + " JSCompiler_inline_result$$0?0:1 " + " }" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression12() { helperInlineReferenceToFunction( "function foo(a){return true;}" + "function x() { 1?foo(1):1; }", "function foo(a){return true}" + "function x() {" + " if(1) {" + " {true;}" + " } else {" + " 1;" + " }" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression13() { helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { goo() + (1?foo(1):1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_temp_const$$0=goo();" + "var JSCompiler_temp$$1;" + "if(1) {" + " {JSCompiler_temp$$1=true;} " + "} else {" + " JSCompiler_temp$$1=1;" + "}" + "JSCompiler_temp_const$$0 + JSCompiler_temp$$1" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression14() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression15() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo.call(this,1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression16() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z[bar()] = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$1=z;" + "var JSCompiler_temp_const$$0=bar();" + "var JSCompiler_inline_result$$2;" + "{" + "z= {};" + "JSCompiler_inline_result$$2 = true;" + "}" + "JSCompiler_temp_const$$1[JSCompiler_temp_const$$0] = " + "JSCompiler_inline_result$$2;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression17() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.y.x.gack = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z.y.x;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineWithinCalls1() { // Call in within a call helperInlineReferenceToFunction( "function foo(){return _g;}; " + "function x() {1 + foo()() }", "function foo(){return _g;}; " + "function x() { var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=_g;}" + "1 + JSCompiler_inline_result$$0() }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testInlineWithinCalls2() { // helperInlineReferenceToFunction( // "/** @nosideeffects */ function foo(){return true;}; " + // "function x() {1 + _g(foo()) }", // "function foo(){return true;}; " + // "function x() { {var JSCompiler_inline_result$$0; " + // "JSCompiler_inline_result$$0=true;}" + // "1 + _g(JSCompiler_inline_result$$0) }", // "foo", INLINE_BLOCK, true); // } public void testInlineAssignmentToConstant() { // Call in within a call helperInlineReferenceToFunction( "function foo(){return _g;}; " + "function x(){var CONSTANT_RESULT = foo(); }", "function foo(){return _g;}; " + "function x() {" + " var JSCompiler_inline_result$$0;" + " {JSCompiler_inline_result$$0=_g;}" + " var CONSTANT_RESULT = JSCompiler_inline_result$$0;" + "}", "foo", INLINE_BLOCK, true); } public void testBug1897706() { helperInlineReferenceToFunction( "function foo(a){}; foo(x())", "function foo(a){}; {var a$$inline_0=x()}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){bar()}; foo(x())", "function foo(a){bar()}; {var a$$inline_0=x();bar()}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a,b){bar()}; foo(x(),y())", "function foo(a,b){bar()};" + "{var a$$inline_0=x();var b$$inline_1=y();bar()}", "foo", INLINE_BLOCK); } public void testIssue1101a() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return modifiyX() + a;} foo(x);", "foo", INLINE_DIRECT); } public void testIssue1101b() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return (x.prop = 2),a;} foo(x.prop);", "foo", INLINE_DIRECT); } /** * Test case * * var a = {}, b = {} * a.test = "a", b.test = "b" * c = a; * foo() { c=b; return "a" } * c.teste * */ public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode) { helperCanInlineReferenceToFunction( expectedResult, code, fnName, mode, false); } public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode, boolean allowDecomposition) { final Compiler compiler = new Compiler(); final FunctionInjector injector = new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), allowDecomposition, assumeStrictThis, assumeMinimumCapture); final Node tree = parse(compiler, code); final Node fnNode = findFunction(tree, fnName); final Set<String> unsafe = FunctionArgumentInjector.findModifiedParameters(fnNode); // can-inline tester Method tester = new Method() { @Override public boolean call(NodeTraversal t, Node n, Node parent) { CanInlineResult result = injector.canInlineReferenceToFunction( t, n, fnNode, unsafe, mode, NodeUtil.referencesThis(fnNode), NodeUtil.containsFunction(NodeUtil.getFunctionBody(fnNode))); assertEquals(expectedResult, result); return true; } }; compiler.resetUniqueNameId(); TestCallback test = new TestCallback(fnName, tester); NodeTraversal.traverse(compiler, tree, test); } public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode) { helperInlineReferenceToFunction( code, expectedResult, fnName, mode, false); } private void validateSourceInfo(Compiler compiler, Node subtree) { (new LineNumberCheck(compiler)).setCheckSubTree(subtree); // Source information problems are reported as compiler errors. if (compiler.getErrorCount() != 0) { String msg = "Error encountered: "; for (JSError err : compiler.getErrors()) { msg += err.toString() + "\n"; } assertTrue(msg, compiler.getErrorCount() == 0); } } public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode, final boolean decompose) { final Compiler compiler = new Compiler(); final FunctionInjector injector = new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), decompose, assumeStrictThis, assumeMinimumCapture); List<SourceFile> externsInputs = Lists.newArrayList( SourceFile.fromCode("externs", "")); CompilerOptions options = new CompilerOptions(); options.setCodingConvention(new GoogleCodingConvention()); compiler.init(externsInputs, Lists.newArrayList( SourceFile.fromCode("code", code)), options); Node parseRoot = compiler.parseInputs(); Node externsRoot = parseRoot.getFirstChild(); final Node tree = parseRoot.getLastChild(); assertNotNull(tree); assertTrue(tree != externsRoot); final Node expectedRoot = parseExpected(new Compiler(), expectedResult); Node mainRoot = tree; MarkNoSideEffectCalls mark = new MarkNoSideEffectCalls(compiler); mark.process(externsRoot, mainRoot); Normalize normalize = new Normalize(compiler, false); normalize.process(externsRoot, mainRoot); compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED); final Node fnNode = findFunction(tree, fnName); assertNotNull(fnNode); final Set<String> unsafe = FunctionArgumentInjector.findModifiedParameters(fnNode); assertNotNull(fnNode); // inline tester Method tester = new Method() { @Override public boolean call(NodeTraversal t, Node n, Node parent) { CanInlineResult canInline = injector.canInlineReferenceToFunction( t, n, fnNode, unsafe, mode, NodeUtil.referencesThis(fnNode), NodeUtil.containsFunction(NodeUtil.getFunctionBody(fnNode))); assertTrue("canInlineReferenceToFunction should not be CAN_NOT_INLINE", CanInlineResult.NO != canInline); if (decompose) { assertTrue("canInlineReferenceToFunction " + "should be CAN_INLINE_AFTER_DECOMPOSITION", CanInlineResult.AFTER_PREPARATION == canInline); Set<String> knownConstants = Sets.newHashSet(); injector.setKnownConstants(knownConstants); injector.maybePrepareCall(n); assertTrue("canInlineReferenceToFunction " + "should be CAN_INLINE", CanInlineResult.YES != canInline); } Node result = injector.inline(n, fnName, fnNode, mode); validateSourceInfo(compiler, result); String explanation = expectedRoot.checkTreeEquals(tree.getFirstChild()); assertNull("\nExpected: " + toSource(expectedRoot) + "\nResult: " + toSource(tree.getFirstChild()) + "\n" + explanation, explanation); return true; } }; compiler.resetUniqueNameId(); TestCallback test = new TestCallback(fnName, tester); NodeTraversal.traverse(compiler, tree, test); } interface Method { boolean call(NodeTraversal t, Node n, Node parent); } class TestCallback implements Callback { private final String callname; private final Method method; private boolean complete = false; TestCallback(String callname, Method method) { this.callname = callname; this.method = method; } @Override public boolean shouldTraverse( NodeTraversal nodeTraversal, Node n, Node parent) { return !complete; } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isCall()) { Node callee; if (NodeUtil.isGet(n.getFirstChild())) { callee = n.getFirstChild().getFirstChild(); } else { callee = n.getFirstChild(); } if (callee.isName() && callee.getString().equals(callname)) { complete = method.call(t, n, parent); } } if (parent == null) { assertTrue(complete); } } } private static Node findFunction(Node n, String name) { if (n.isFunction()) { if (n.getFirstChild().getString().equals(name)) { return n; } } for (Node c : n.children()) { Node result = findFunction(c, name); if (result != null) { return result; } } return null; } private static Node prep(String js) { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); return n.getFirstChild(); } private static Node parse(Compiler compiler, String js) { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); return n; } private static Node parseExpected(Compiler compiler, String js) { Node n = compiler.parseTestCode(js); String message = "Unexpected errors: "; JSError[] errs = compiler.getErrors(); for (int i = 0; i < errs.length; i++){ message += "\n" + errs[i].toString(); } assertEquals(message, 0, compiler.getErrorCount()); return n; } private static String toSource(Node n) { return new CodePrinter.Builder(n) .setPrettyPrint(false) .setLineBreak(false) .setSourceMap(null) .build(); } }
// You are a professional Java test case writer, please create a test case named `testIssue1101a` for the issue `Closure-1101`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1101 // // ## Issue-Title: // Erroneous optimization in ADVANCED_OPTIMIZATIONS mode // // ## Issue-Description: // **What steps will reproduce the problem?** // // 1. Create a file input.js with the following "minimal" test case: // // window["anchor"] = function (obj, modifiesProp) { // return (function (saved) { // return modifiesProp(obj) + saved; // })(obj["prop"]); // } // // 2. Compile it with: // // java -jar .../build/compiler.jar \ // --compilation\_level ADVANCED\_OPTIMIZATIONS \ // --warning\_level VERBOSE \ // --externs window.js \ // --js input.js \ // --js\_output\_file output.js // // 3. That's all! // // What is the expected output? // // window.foo=function(a,b){var HOLD=a.prop;return b(a)+HOLD}; // // What do you see instead? // // window.foo=function(a,b){return b(a)+a.prop}; // // Note how this is semantically very different if modifiesProp/b (whose // semantics are unknown to the compiler) side-effects a.prop. // // The evaluation order of + is well-defined in EcmaScript 5, but even // then, this happens even if one substitutes the , (comma) operator. // // **What version of the product are you using? On what operating system?** // // Git HEAD // // commit 4a62ee4bca02169dd77a6f26ed64a624b3f05f95 // Author: Chad Killingsworth <chadkillingsworth@missouristate.edu> // Date: Wed Sep 25 14:52:28 2013 -0500 // // Add history.state to html5 externs // // on Linux. // // public void testIssue1101a() {
1,349
116
1,345
test/com/google/javascript/jscomp/FunctionInjectorTest.java
test
```markdown ## Issue-ID: Closure-1101 ## Issue-Title: Erroneous optimization in ADVANCED_OPTIMIZATIONS mode ## Issue-Description: **What steps will reproduce the problem?** 1. Create a file input.js with the following "minimal" test case: window["anchor"] = function (obj, modifiesProp) { return (function (saved) { return modifiesProp(obj) + saved; })(obj["prop"]); } 2. Compile it with: java -jar .../build/compiler.jar \ --compilation\_level ADVANCED\_OPTIMIZATIONS \ --warning\_level VERBOSE \ --externs window.js \ --js input.js \ --js\_output\_file output.js 3. That's all! What is the expected output? window.foo=function(a,b){var HOLD=a.prop;return b(a)+HOLD}; What do you see instead? window.foo=function(a,b){return b(a)+a.prop}; Note how this is semantically very different if modifiesProp/b (whose semantics are unknown to the compiler) side-effects a.prop. The evaluation order of + is well-defined in EcmaScript 5, but even then, this happens even if one substitutes the , (comma) operator. **What version of the product are you using? On what operating system?** Git HEAD commit 4a62ee4bca02169dd77a6f26ed64a624b3f05f95 Author: Chad Killingsworth <chadkillingsworth@missouristate.edu> Date: Wed Sep 25 14:52:28 2013 -0500 Add history.state to html5 externs on Linux. ``` You are a professional Java test case writer, please create a test case named `testIssue1101a` for the issue `Closure-1101`, utilizing the provided issue report information and the following function signature. ```java public void testIssue1101a() { ```
1,345
[ "com.google.javascript.jscomp.FunctionInjector" ]
2da75de178835c52badfc41da5e7461f6ba6480e062b15b287874fdb26842c39
public void testIssue1101a()
// You are a professional Java test case writer, please create a test case named `testIssue1101a` for the issue `Closure-1101`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1101 // // ## Issue-Title: // Erroneous optimization in ADVANCED_OPTIMIZATIONS mode // // ## Issue-Description: // **What steps will reproduce the problem?** // // 1. Create a file input.js with the following "minimal" test case: // // window["anchor"] = function (obj, modifiesProp) { // return (function (saved) { // return modifiesProp(obj) + saved; // })(obj["prop"]); // } // // 2. Compile it with: // // java -jar .../build/compiler.jar \ // --compilation\_level ADVANCED\_OPTIMIZATIONS \ // --warning\_level VERBOSE \ // --externs window.js \ // --js input.js \ // --js\_output\_file output.js // // 3. That's all! // // What is the expected output? // // window.foo=function(a,b){var HOLD=a.prop;return b(a)+HOLD}; // // What do you see instead? // // window.foo=function(a,b){return b(a)+a.prop}; // // Note how this is semantically very different if modifiesProp/b (whose // semantics are unknown to the compiler) side-effects a.prop. // // The evaluation order of + is well-defined in EcmaScript 5, but even // then, this happens even if one substitutes the , (comma) operator. // // **What version of the product are you using? On what operating system?** // // Git HEAD // // commit 4a62ee4bca02169dd77a6f26ed64a624b3f05f95 // Author: Chad Killingsworth <chadkillingsworth@missouristate.edu> // Date: Wed Sep 25 14:52:28 2013 -0500 // // Add history.state to html5 externs // // on Linux. // //
Closure
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.FunctionInjector.CanInlineResult; import com.google.javascript.jscomp.FunctionInjector.InliningMode; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.util.List; import java.util.Set; /** * Inline function tests. * @author johnlenz@google.com (John Lenz) */ public class FunctionInjectorTest extends TestCase { static final InliningMode INLINE_DIRECT = InliningMode.DIRECT; static final InliningMode INLINE_BLOCK = InliningMode.BLOCK; private boolean assumeStrictThis = false; private boolean assumeMinimumCapture = false; @Override protected void setUp() throws Exception { super.setUp(); assumeStrictThis = false; } private FunctionInjector getInjector() { Compiler compiler = new Compiler(); return new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), true, assumeStrictThis, assumeMinimumCapture); } public void testIsSimpleFunction1() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){}"))); } public void testIsSimpleFunction2() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return 0;}"))); } public void testIsSimpleFunction3() { assertTrue(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return x ? 0 : 1}"))); } public void testIsSimpleFunction4() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return;}"))); } public void testIsSimpleFunction5() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){return 0; return 0;}"))); } public void testIsSimpleFunction6() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){var x=true;return x ? 0 : 1}"))); } public void testIsSimpleFunction7() { assertFalse(getInjector().isDirectCallNodeReplacementPossible( prep("function f(){if (x) return 0; else return 1}"))); } public void testCanInlineReferenceToFunction1() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction2() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction3() { // NOTE: FoldConstants will convert this to a empty function, // so there is no need to explicitly support it. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return;}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction4() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return;}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction5() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction6() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction7() { // In var initialization. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x=foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction8() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction9() { // In assignment. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction10() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction11() { // In expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction12() { // "foo" is not known to be side-effect free, it might change the value // of "x", so it can't be inlined. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction12b() { // "foo" is not known to be side-effect free, it might change the value // of "x", so it can't be inlined. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return true;}; var x; x=x+foo();", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunction13() { // // ... if foo is side-effect free we can inline here. // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(){return true;};" + // "var x; x=x+foo();", "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunction14() { // Simple call with parameters helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; foo(x);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction15() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; foo(x);", "foo", INLINE_BLOCK); } // TODO(johnlenz): remove this constant once this has been proven in // production code. static final CanInlineResult NEW_VARS_IN_GLOBAL_SCOPE = CanInlineResult.YES; public void testCanInlineReferenceToFunction16() { // Function "foo" as it contains "var b" which // must be brought into the global scope. helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){var b;return a;}; foo(goo());", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction17() { // This doesn't bring names into the global name space. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a;}; " + "function x() { foo(goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction18() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a;} foo(x++);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction19() { // Parameter has mutable parameter referenced more than once. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo([]);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction20() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo({});", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction21() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo(new Date);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction22() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a} foo(true && new Date);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction23() { // variables to global scope. helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return a;}; foo(x++);", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction24() { // ... this is OK, because it doesn't introduce a new global name. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a;}; " + "function x() { foo(x++); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction25() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return a+a;}; foo(x++);", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction26() { helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return a+a;}; foo(x++);", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction27() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return a+a;}; " + "function x() { foo(x++); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction28() { // Parameter has side-effects. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; foo(goo());", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction29() { helperCanInlineReferenceToFunction(NEW_VARS_IN_GLOBAL_SCOPE, "function foo(a){return true;}; foo(goo());", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction30() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo(goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction31() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a) {return true;}; " + "function x() {foo.call(this, 1);}", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction32() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.apply(this, [1]); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction33() { // No special handling is required for method calls passing this. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.bar(this, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction34() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction35() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.apply(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction36() { helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.bar(this, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction37() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(null, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction38() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(null, goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(null, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction39() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(bar, 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction40() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(bar, goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(bar, goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction41() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), 1); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction42() { assumeStrictThis = false; helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), goo()); }", "foo", INLINE_BLOCK); assumeStrictThis = true; helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(a){return true;}; " + "function x() { foo.call(new bar(), goo()); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction43() { // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction44() { assumeStrictThis = false; // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_BLOCK); assumeStrictThis = true; // Handle the case of a missing 'this' value in a call. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return true;}; " + "function x() { foo.call(); }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction45() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction46() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction47() { // Call with inner function expression and variable decl. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){var a; return function() {return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction48() { // Call with inner function expression and variable decl. // TODO(johnlenz): should we validate no values in scope? helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){var a; return function() {return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction49() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {var a; return true;}}; foo();", "foo", INLINE_DIRECT); } public void testCanInlineReferenceToFunction50() { // Call with inner function expression. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){return function() {var a; return true;}}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunction51() { // Call with inner function statement. helperCanInlineReferenceToFunction(CanInlineResult.YES, "function foo(){function x() {var a; return true;} return x}; foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression1() { // Call in if condition helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { if (foo(1)) throw 'test'; }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression2() { // Call in return expression helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { return foo(1); }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression3() { // Call in switch expression helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() { switch(foo(1)) { default:break; } }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression4() { // Call in hook condition helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {foo(1)?0:1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression5() { // Call in hook side-effect free condition helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {true?foo(1):1 }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression5a() { // Call in hook side-effect free condition helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {true?foo(1):1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression6() { // Call in expression statement "condition" helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {foo(1) && 1 }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression7() { // Call in expression statement after side-effect free "condition" helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {1 && foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression7a() { // Call in expression statement after side-effect free "condition" helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {1 && foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression8() { // Call in expression statement after side-effect free operator helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression9() { // Call in VAR expression. helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var b = 1 + foo(1)}", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression10() { // Call in assignment expression. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return true;}; " + "function x() {var b; b += 1 + foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression10a() { // Call in assignment expression. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var b; b += 1 + foo(1) }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression11() { // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression12() { helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var a,b,c; a = b = c = foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression13() { helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(a){return true;}; " + "function x() {var a,b,c; a = b = c = 1 + foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression14() { // ... foo can not be inlined because of possible changes to "c". helperCanInlineReferenceToFunction(CanInlineResult.NO, "var a = {}, b = {}, c;" + "a.test = 'a';" + "b.test = 'b';" + "c = a;" + "function foo(){c = b; return 'foo'};" + "c.test=foo();", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression14a() { // ... foo can be inlined despite possible changes to "c". helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "var a = {}, b = {}, c;" + "a.test = 'a';" + "b.test = 'b';" + "c = a;" + "function foo(){c = b; return 'foo'};" + "c.test=foo();", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression15() { // // ... foo can be inlined as it is side-effect free. // helperCanInlineReferenceToFunction(true, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "c.test=foo();", // "foo", INLINE_BLOCK); // } // public void testCanInlineReferenceToFunctionInExpression16() { // // ... foo can not be inlined because of possible side-effects of x() // helperCanInlineReferenceToFunction(false, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "function x(){return c};" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "x().test=foo();", // "foo", INLINE_BLOCK); // } // public void testCanInlineReferenceToFunctionInExpression17() { // // ... foo can be inlined because of x() is side-effect free. // helperCanInlineReferenceToFunction(true, // "var a = {}, b = {}, c;" + // "a.test = 'a';" + // "b.test = 'b';" + // "c = a;" + // "/** @nosideeffects */ function x(){return c};" + // "/** @nosideeffects */ function foo(){return 'foo'};" + // "x().test=foo();", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression18() { // Call in within a call helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(){return _g();}; " + "function x() {1 + foo()() }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression19() { // ... unless foo is known to be side-effect free, it might actually // change the value of "_g" which would unfortunately change the behavior, // so we can't inline here. helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(foo()) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression19a() { // ... unless foo is known to be side-effect free, it might actually // change the value of "_g" which would unfortunately change the behavior, // so we can't inline here. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(foo()) }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testCanInlineReferenceToFunctionInExpression20() { // helperCanInlineReferenceToFunction(true, // "/** @nosideeffects */ function foo(){return a;}; " + // "function x() {1 + _g(foo()) }", // "foo", INLINE_BLOCK); // } public void testCanInlineReferenceToFunctionInExpression21() { // Assignments to object are problematic if the call has side-effects, // as the object that is being referred to can change. // Note: This could be changed be inlined if we in some way make "z" // as not escaping from the local scope. helperCanInlineReferenceToFunction(CanInlineResult.NO, "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression21a() { // Assignments to object are problematic if the call has side-effects, // as the object that is being referred to can change. // Note: This could be changed be inlined if we in some way make "z" // as not escaping from the local scope. helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression22() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo()) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression22a() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo()) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInExpression23() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo.call(this)) }", "foo", INLINE_BLOCK); } public void testCanInlineReferenceToFunctionInExpression23a() { // ... foo() is after a side-effect helperCanInlineReferenceToFunction( CanInlineResult.AFTER_PREPARATION, "function foo(){return a;}; " + "function x() {1 + _g(_a(), foo.call(this)) }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInLoop1() { helperCanInlineReferenceToFunction( CanInlineResult.YES, "function foo(){return a;}; " + "while(1) { foo(); }", "foo", INLINE_BLOCK, true); } public void testCanInlineReferenceToFunctionInLoop2() { // If function contains function, don't inline it into a loop. // TODO(johnlenz): this can be improved by looking to see // if the inner function contains any references to values defined // in the outer function. helperCanInlineReferenceToFunction( CanInlineResult.NO, "function foo(){return function() {};}; " + "while(1) { foo(); }", "foo", INLINE_BLOCK, true); } public void testInline1() { helperInlineReferenceToFunction( "function foo(){}; foo();", "function foo(){}; void 0", "foo", INLINE_DIRECT); } public void testInline2() { helperInlineReferenceToFunction( "function foo(){}; foo();", "function foo(){}; {}", "foo", INLINE_BLOCK); } public void testInline3() { helperInlineReferenceToFunction( "function foo(){return;}; foo();", "function foo(){return;}; {}", "foo", INLINE_BLOCK); } public void testInline4() { helperInlineReferenceToFunction( "function foo(){return true;}; foo();", "function foo(){return true;}; true;", "foo", INLINE_DIRECT); } public void testInline5() { helperInlineReferenceToFunction( "function foo(){return true;}; foo();", "function foo(){return true;}; {true;}", "foo", INLINE_BLOCK); } public void testInline6() { // In var initialization. helperInlineReferenceToFunction( "function foo(){return true;}; var x=foo();", "function foo(){return true;}; var x=true;", "foo", INLINE_DIRECT); } public void testInline7() { helperInlineReferenceToFunction( "function foo(){return true;}; var x=foo();", "function foo(){return true;}; var x;" + "{x=true}", "foo", INLINE_BLOCK); } public void testInline8() { // In assignment. helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=foo();", "function foo(){return true;}; var x; x=true;", "foo", INLINE_DIRECT); } public void testInline9() { helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=foo();", "function foo(){return true;}; var x;{x=true}", "foo", INLINE_BLOCK); } public void testInline10() { // In expression. helperInlineReferenceToFunction( "function foo(){return true;}; var x; x=x+foo();", "function foo(){return true;}; var x; x=x+true;", "foo", INLINE_DIRECT); } public void testInline11() { // Simple call with parameters helperInlineReferenceToFunction( "function foo(a){return true;}; foo(x);", "function foo(a){return true;}; true;", "foo", INLINE_DIRECT); } public void testInline12() { helperInlineReferenceToFunction( "function foo(a){return true;}; foo(x);", "function foo(a){return true;}; {true}", "foo", INLINE_BLOCK); } public void testInline13() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return a;}; " + "function x() { foo(x++); }", "function foo(a){return a;}; " + "function x() {{var a$$inline_0=x++;" + "a$$inline_0}}", "foo", INLINE_BLOCK); } public void testInline14() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(x++);", "function foo(a){return a+a;}; " + "{var a$$inline_0=x++;" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline15() { // Parameter has mutable, references more than once. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(new Date());", "function foo(a){return a+a;}; " + "{var a$$inline_0=new Date();" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline16() { // Parameter is large, references more than once. helperInlineReferenceToFunction( "function foo(a){return a+a;}; foo(function(){});", "function foo(a){return a+a;}; " + "{var a$$inline_0=function(){};" + " a$$inline_0+" + "a$$inline_0;}", "foo", INLINE_BLOCK); } public void testInline17() { // Parameter has side-effects. helperInlineReferenceToFunction( "function foo(a){return true;}; foo(goo());", "function foo(a){return true;};" + "{var a$$inline_0=goo();true}", "foo", INLINE_BLOCK); } public void testInline18() { // This doesn't bring names into the global name space. helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "function x() { foo(goo()); }", "function foo(a){var b;return a;}; " + "function x() {{var a$$inline_0=goo();" + "var b$$inline_1;a$$inline_0}}", "foo", INLINE_BLOCK); } public void testInline19() { // Properly alias. helperInlineReferenceToFunction( "var x = 1; var y = 2;" + "function foo(a,b){x = b; y = a;}; " + "function bar() { foo(x,y); }", "var x = 1; var y = 2;" + "function foo(a,b){x = b; y = a;}; " + "function bar() {" + "{var a$$inline_0=x;" + "x = y;" + "y = a$$inline_0;}" + "}", "foo", INLINE_BLOCK); } public void testInline19b() { helperInlineReferenceToFunction( "var x = 1; var y = 2;" + "function foo(a,b){y = a; x = b;}; " + "function bar() { foo(x,y); }", "var x = 1; var y = 2;" + "function foo(a,b){y = a; x = b;}; " + "function bar() {" + "{var b$$inline_1=y;" + "y = x;" + "x = b$$inline_1;}" + "}", "foo", INLINE_BLOCK); } public void testInlineIntoLoop() { helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "for(;1;){ foo(1); }", "function foo(a){var b;return a;}; " + "for(;1;){ {" + "var b$$inline_1=void 0;1}}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){var b;return a;}; " + "do{ foo(1); } while(1)", "function foo(a){var b;return a;}; " + "do{ {" + "var b$$inline_1=void 0;1}}while(1)", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){for(var b in c)return a;}; " + "for(;1;){ foo(1); }", "function foo(a){var b;for(b in c)return a;}; " + "for(;1;){ {JSCompiler_inline_label_foo_2:{" + "var b$$inline_1=void 0;for(b$$inline_1 in c){" + "1;break JSCompiler_inline_label_foo_2" + "}}}}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction1() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {return true;}}; foo();", "function foo(){return function() {return true;}};" + "(function() {return true;})", "foo", INLINE_DIRECT); } public void testInlineFunctionWithInnerFunction2() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {return true;}}; foo();", "function foo(){return function() {return true;}};" + "{(function() {return true;})}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction3() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {var a; return true;}}; foo();", "function foo(){return function() {var a; return true;}};" + "(function() {var a; return true;});", "foo", INLINE_DIRECT); } public void testInlineFunctionWithInnerFunction4() { // Call with inner function expression. helperInlineReferenceToFunction( "function foo(){return function() {var a; return true;}}; foo();", "function foo(){return function() {var a; return true;}};" + "{(function() {var a$$inline_0; return true;});}", "foo", INLINE_BLOCK); } public void testInlineFunctionWithInnerFunction5() { // Call with inner function statement. helperInlineReferenceToFunction( "function foo(){function x() {var a; return true;} return x}; foo();", "function foo(){function x(){var a;return true}return x};" + "{var x$$inline_0 = function(){" + "var a$$inline_1;return true};x$$inline_0}", "foo", INLINE_BLOCK); } public void testInlineReferenceInExpression1() { // Call in if condition helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { if (foo(1)) throw 'test'; }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "if (JSCompiler_inline_result$$0) throw 'test'; }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression2() { // Call in return expression helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { return foo(1); }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "return JSCompiler_inline_result$$0; }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression3() { // Call in switch expression helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { switch(foo(1)) { default:break; } }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "switch(JSCompiler_inline_result$$0) { default:break; } }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression4() { // Call in hook condition helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1)?0:1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0?0:1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression5() { // Call in expression statement "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1)&&1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0&&1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression6() { // Call in expression statement after side-effect free "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "1 + JSCompiler_inline_result$$0 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression7() { // Call in expression statement "condition" helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {foo(1) && 1 }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0; " + "{JSCompiler_inline_result$$0=true;}" + "JSCompiler_inline_result$$0&&1 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression8() { // Call in expression statement after side-effect free operator helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {1 + foo(1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=true;}" + "1 + JSCompiler_inline_result$$0 }", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression9() { // Call in VAR expression. helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {var b = 1 + foo(1)}", "function foo(a){return true;}; " + "function x() { " + "var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=true;}" + "var b = 1 + JSCompiler_inline_result$$0 " + "}", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testInlineReferenceInExpression10() { // // Call in assignment expression. // helperInlineReferenceToFunction( // "/** @nosideeffects */ function foo(a){return true;}; " + // "function x() {var b; b += 1 + foo(1) }", // "function foo(a){return true;}; " + // "function x() {var b;" + // "{var JSCompiler_inline_result$$0; " + // "JSCompiler_inline_result$$0=true;}" + // "b += 1 + JSCompiler_inline_result$$0 }", // "foo", INLINE_BLOCK); // } public void testInlineReferenceInExpression11() { // Call under label helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() {a:foo(1)?0:1 }", "function foo(a){return true;}; " + "function x() {" + " a:{" + " var JSCompiler_inline_result$$0; " + " {JSCompiler_inline_result$$0=true;}" + " JSCompiler_inline_result$$0?0:1 " + " }" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression12() { helperInlineReferenceToFunction( "function foo(a){return true;}" + "function x() { 1?foo(1):1; }", "function foo(a){return true}" + "function x() {" + " if(1) {" + " {true;}" + " } else {" + " 1;" + " }" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression13() { helperInlineReferenceToFunction( "function foo(a){return true;}; " + "function x() { goo() + (1?foo(1):1) }", "function foo(a){return true;}; " + "function x() { var JSCompiler_temp_const$$0=goo();" + "var JSCompiler_temp$$1;" + "if(1) {" + " {JSCompiler_temp$$1=true;} " + "} else {" + " JSCompiler_temp$$1=1;" + "}" + "JSCompiler_temp_const$$0 + JSCompiler_temp$$1" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression14() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression15() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.gack = foo.call(this,1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression16() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z[bar()] = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$1=z;" + "var JSCompiler_temp_const$$0=bar();" + "var JSCompiler_inline_result$$2;" + "{" + "z= {};" + "JSCompiler_inline_result$$2 = true;" + "}" + "JSCompiler_temp_const$$1[JSCompiler_temp_const$$0] = " + "JSCompiler_inline_result$$2;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineReferenceInExpression17() { helperInlineReferenceToFunction( "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() { z.y.x.gack = foo(1) }", "var z = {};" + "function foo(a){z = {};return true;}; " + "function x() {" + "var JSCompiler_temp_const$$0=z.y.x;" + "var JSCompiler_inline_result$$1;" + "{" + "z= {};" + "JSCompiler_inline_result$$1 = true;" + "}" + "JSCompiler_temp_const$$0.gack = JSCompiler_inline_result$$1;" + "}", "foo", INLINE_BLOCK, true); } public void testInlineWithinCalls1() { // Call in within a call helperInlineReferenceToFunction( "function foo(){return _g;}; " + "function x() {1 + foo()() }", "function foo(){return _g;}; " + "function x() { var JSCompiler_inline_result$$0;" + "{JSCompiler_inline_result$$0=_g;}" + "1 + JSCompiler_inline_result$$0() }", "foo", INLINE_BLOCK, true); } // TODO(nicksantos): Re-enable with side-effect detection. // public void testInlineWithinCalls2() { // helperInlineReferenceToFunction( // "/** @nosideeffects */ function foo(){return true;}; " + // "function x() {1 + _g(foo()) }", // "function foo(){return true;}; " + // "function x() { {var JSCompiler_inline_result$$0; " + // "JSCompiler_inline_result$$0=true;}" + // "1 + _g(JSCompiler_inline_result$$0) }", // "foo", INLINE_BLOCK, true); // } public void testInlineAssignmentToConstant() { // Call in within a call helperInlineReferenceToFunction( "function foo(){return _g;}; " + "function x(){var CONSTANT_RESULT = foo(); }", "function foo(){return _g;}; " + "function x() {" + " var JSCompiler_inline_result$$0;" + " {JSCompiler_inline_result$$0=_g;}" + " var CONSTANT_RESULT = JSCompiler_inline_result$$0;" + "}", "foo", INLINE_BLOCK, true); } public void testBug1897706() { helperInlineReferenceToFunction( "function foo(a){}; foo(x())", "function foo(a){}; {var a$$inline_0=x()}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a){bar()}; foo(x())", "function foo(a){bar()}; {var a$$inline_0=x();bar()}", "foo", INLINE_BLOCK); helperInlineReferenceToFunction( "function foo(a,b){bar()}; foo(x(),y())", "function foo(a,b){bar()};" + "{var a$$inline_0=x();var b$$inline_1=y();bar()}", "foo", INLINE_BLOCK); } public void testIssue1101a() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return modifiyX() + a;} foo(x);", "foo", INLINE_DIRECT); } public void testIssue1101b() { helperCanInlineReferenceToFunction(CanInlineResult.NO, "function foo(a){return (x.prop = 2),a;} foo(x.prop);", "foo", INLINE_DIRECT); } /** * Test case * * var a = {}, b = {} * a.test = "a", b.test = "b" * c = a; * foo() { c=b; return "a" } * c.teste * */ public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode) { helperCanInlineReferenceToFunction( expectedResult, code, fnName, mode, false); } public void helperCanInlineReferenceToFunction( final CanInlineResult expectedResult, final String code, final String fnName, final InliningMode mode, boolean allowDecomposition) { final Compiler compiler = new Compiler(); final FunctionInjector injector = new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), allowDecomposition, assumeStrictThis, assumeMinimumCapture); final Node tree = parse(compiler, code); final Node fnNode = findFunction(tree, fnName); final Set<String> unsafe = FunctionArgumentInjector.findModifiedParameters(fnNode); // can-inline tester Method tester = new Method() { @Override public boolean call(NodeTraversal t, Node n, Node parent) { CanInlineResult result = injector.canInlineReferenceToFunction( t, n, fnNode, unsafe, mode, NodeUtil.referencesThis(fnNode), NodeUtil.containsFunction(NodeUtil.getFunctionBody(fnNode))); assertEquals(expectedResult, result); return true; } }; compiler.resetUniqueNameId(); TestCallback test = new TestCallback(fnName, tester); NodeTraversal.traverse(compiler, tree, test); } public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode) { helperInlineReferenceToFunction( code, expectedResult, fnName, mode, false); } private void validateSourceInfo(Compiler compiler, Node subtree) { (new LineNumberCheck(compiler)).setCheckSubTree(subtree); // Source information problems are reported as compiler errors. if (compiler.getErrorCount() != 0) { String msg = "Error encountered: "; for (JSError err : compiler.getErrors()) { msg += err.toString() + "\n"; } assertTrue(msg, compiler.getErrorCount() == 0); } } public void helperInlineReferenceToFunction( String code, final String expectedResult, final String fnName, final InliningMode mode, final boolean decompose) { final Compiler compiler = new Compiler(); final FunctionInjector injector = new FunctionInjector( compiler, compiler.getUniqueNameIdSupplier(), decompose, assumeStrictThis, assumeMinimumCapture); List<SourceFile> externsInputs = Lists.newArrayList( SourceFile.fromCode("externs", "")); CompilerOptions options = new CompilerOptions(); options.setCodingConvention(new GoogleCodingConvention()); compiler.init(externsInputs, Lists.newArrayList( SourceFile.fromCode("code", code)), options); Node parseRoot = compiler.parseInputs(); Node externsRoot = parseRoot.getFirstChild(); final Node tree = parseRoot.getLastChild(); assertNotNull(tree); assertTrue(tree != externsRoot); final Node expectedRoot = parseExpected(new Compiler(), expectedResult); Node mainRoot = tree; MarkNoSideEffectCalls mark = new MarkNoSideEffectCalls(compiler); mark.process(externsRoot, mainRoot); Normalize normalize = new Normalize(compiler, false); normalize.process(externsRoot, mainRoot); compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED); final Node fnNode = findFunction(tree, fnName); assertNotNull(fnNode); final Set<String> unsafe = FunctionArgumentInjector.findModifiedParameters(fnNode); assertNotNull(fnNode); // inline tester Method tester = new Method() { @Override public boolean call(NodeTraversal t, Node n, Node parent) { CanInlineResult canInline = injector.canInlineReferenceToFunction( t, n, fnNode, unsafe, mode, NodeUtil.referencesThis(fnNode), NodeUtil.containsFunction(NodeUtil.getFunctionBody(fnNode))); assertTrue("canInlineReferenceToFunction should not be CAN_NOT_INLINE", CanInlineResult.NO != canInline); if (decompose) { assertTrue("canInlineReferenceToFunction " + "should be CAN_INLINE_AFTER_DECOMPOSITION", CanInlineResult.AFTER_PREPARATION == canInline); Set<String> knownConstants = Sets.newHashSet(); injector.setKnownConstants(knownConstants); injector.maybePrepareCall(n); assertTrue("canInlineReferenceToFunction " + "should be CAN_INLINE", CanInlineResult.YES != canInline); } Node result = injector.inline(n, fnName, fnNode, mode); validateSourceInfo(compiler, result); String explanation = expectedRoot.checkTreeEquals(tree.getFirstChild()); assertNull("\nExpected: " + toSource(expectedRoot) + "\nResult: " + toSource(tree.getFirstChild()) + "\n" + explanation, explanation); return true; } }; compiler.resetUniqueNameId(); TestCallback test = new TestCallback(fnName, tester); NodeTraversal.traverse(compiler, tree, test); } interface Method { boolean call(NodeTraversal t, Node n, Node parent); } class TestCallback implements Callback { private final String callname; private final Method method; private boolean complete = false; TestCallback(String callname, Method method) { this.callname = callname; this.method = method; } @Override public boolean shouldTraverse( NodeTraversal nodeTraversal, Node n, Node parent) { return !complete; } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isCall()) { Node callee; if (NodeUtil.isGet(n.getFirstChild())) { callee = n.getFirstChild().getFirstChild(); } else { callee = n.getFirstChild(); } if (callee.isName() && callee.getString().equals(callname)) { complete = method.call(t, n, parent); } } if (parent == null) { assertTrue(complete); } } } private static Node findFunction(Node n, String name) { if (n.isFunction()) { if (n.getFirstChild().getString().equals(name)) { return n; } } for (Node c : n.children()) { Node result = findFunction(c, name); if (result != null) { return result; } } return null; } private static Node prep(String js) { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); return n.getFirstChild(); } private static Node parse(Compiler compiler, String js) { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); return n; } private static Node parseExpected(Compiler compiler, String js) { Node n = compiler.parseTestCode(js); String message = "Unexpected errors: "; JSError[] errs = compiler.getErrors(); for (int i = 0; i < errs.length; i++){ message += "\n" + errs[i].toString(); } assertEquals(message, 0, compiler.getErrorCount()); return n; } private static String toSource(Node n) { return new CodePrinter.Builder(n) .setPrettyPrint(false) .setLineBreak(false) .setSourceMap(null) .build(); } }
public void testQuotedProps() { testSame("({'':0})"); testSame("({'1.0':0})"); testSame("({'\u1d17A':0})"); testSame("({'a\u0004b':0})"); }
com.google.javascript.jscomp.ConvertToDottedPropertiesTest::testQuotedProps
test/com/google/javascript/jscomp/ConvertToDottedPropertiesTest.java
72
test/com/google/javascript/jscomp/ConvertToDottedPropertiesTest.java
testQuotedProps
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Tests for {@link ConvertToDottedProperties}. * */ public class ConvertToDottedPropertiesTest extends CompilerTestCase { @Override public CompilerPass getProcessor(Compiler compiler) { return new ConvertToDottedProperties(compiler); } public void testConvert() { test("a['p']", "a.p"); test("a['_p_']", "a._p_"); test("a['_']", "a._"); test("a['$']", "a.$"); test("a.b.c['p']", "a.b.c.p"); test("a.b['c'].p", "a.b.c.p"); test("a['p']();", "a.p();"); test("a()['p']", "a().p"); // ASCII in Unicode is safe. test("a['\u0041A']", "a.AA"); } public void testDoNotConvert() { testSame("a[0]"); testSame("a['']"); testSame("a[' ']"); testSame("a[',']"); testSame("a[';']"); testSame("a[':']"); testSame("a['.']"); testSame("a['0']"); testSame("a['p ']"); testSame("a['p' + '']"); testSame("a[p]"); testSame("a[P]"); testSame("a[$]"); testSame("a[p()]"); testSame("a['default']"); // Ignorable control characters are ok in Java identifiers, but not in JS. testSame("a['A\u0004']"); // upper case lower half of o from phonetic extensions set. // valid in Safari, not in Firefox, IE. test("a['\u1d17A']", "a['\u1d17A']"); // Latin capital N with tilde - nice if we handled it, but for now let's // only allow simple Latin (aka ASCII) to be converted. test("a['\u00d1StuffAfter']", "a['\u00d1StuffAfter']"); } public void testQuotedProps() { testSame("({'':0})"); testSame("({'1.0':0})"); testSame("({'\u1d17A':0})"); testSame("({'a\u0004b':0})"); } public void test5746867() { testSame("var a = { '$\\\\' : 5 };"); testSame("var a = { 'x\\\\u0041$\\\\' : 5 };"); } }
// You are a professional Java test case writer, please create a test case named `testQuotedProps` for the issue `Closure-921`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-921 // // ## Issue-Title: // unicode characters in property names result in invalid output // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. use unicode characters in a property name for an object, like this: // var test={"a\u0004b":"c"}; // // 2. compile // // **What is the expected output? What do you see instead?** // Because unicode characters are not allowed in property names without quotes, the output should be the same as the input. However, the compiler converts the string \u0004 to the respective unicode character, and the output is: // var test={ab:"c"}; // unicode character between a and b can not be displayed here // // **What version of the product are you using? On what operating system?** // newest current snapshot on multiple os (OSX/linux) // // **Please provide any additional information below.** // // public void testQuotedProps() {
72
131
67
test/com/google/javascript/jscomp/ConvertToDottedPropertiesTest.java
test
```markdown ## Issue-ID: Closure-921 ## Issue-Title: unicode characters in property names result in invalid output ## Issue-Description: **What steps will reproduce the problem?** 1. use unicode characters in a property name for an object, like this: var test={"a\u0004b":"c"}; 2. compile **What is the expected output? What do you see instead?** Because unicode characters are not allowed in property names without quotes, the output should be the same as the input. However, the compiler converts the string \u0004 to the respective unicode character, and the output is: var test={ab:"c"}; // unicode character between a and b can not be displayed here **What version of the product are you using? On what operating system?** newest current snapshot on multiple os (OSX/linux) **Please provide any additional information below.** ``` You are a professional Java test case writer, please create a test case named `testQuotedProps` for the issue `Closure-921`, utilizing the provided issue report information and the following function signature. ```java public void testQuotedProps() { ```
67
[ "com.google.javascript.rhino.TokenStream" ]
2f0fd5f1b5f677e16617471bb21047234e23cf4433d4b3fd4bd86a82491bf954
public void testQuotedProps()
// You are a professional Java test case writer, please create a test case named `testQuotedProps` for the issue `Closure-921`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-921 // // ## Issue-Title: // unicode characters in property names result in invalid output // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. use unicode characters in a property name for an object, like this: // var test={"a\u0004b":"c"}; // // 2. compile // // **What is the expected output? What do you see instead?** // Because unicode characters are not allowed in property names without quotes, the output should be the same as the input. However, the compiler converts the string \u0004 to the respective unicode character, and the output is: // var test={ab:"c"}; // unicode character between a and b can not be displayed here // // **What version of the product are you using? On what operating system?** // newest current snapshot on multiple os (OSX/linux) // // **Please provide any additional information below.** // //
Closure
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; /** * Tests for {@link ConvertToDottedProperties}. * */ public class ConvertToDottedPropertiesTest extends CompilerTestCase { @Override public CompilerPass getProcessor(Compiler compiler) { return new ConvertToDottedProperties(compiler); } public void testConvert() { test("a['p']", "a.p"); test("a['_p_']", "a._p_"); test("a['_']", "a._"); test("a['$']", "a.$"); test("a.b.c['p']", "a.b.c.p"); test("a.b['c'].p", "a.b.c.p"); test("a['p']();", "a.p();"); test("a()['p']", "a().p"); // ASCII in Unicode is safe. test("a['\u0041A']", "a.AA"); } public void testDoNotConvert() { testSame("a[0]"); testSame("a['']"); testSame("a[' ']"); testSame("a[',']"); testSame("a[';']"); testSame("a[':']"); testSame("a['.']"); testSame("a['0']"); testSame("a['p ']"); testSame("a['p' + '']"); testSame("a[p]"); testSame("a[P]"); testSame("a[$]"); testSame("a[p()]"); testSame("a['default']"); // Ignorable control characters are ok in Java identifiers, but not in JS. testSame("a['A\u0004']"); // upper case lower half of o from phonetic extensions set. // valid in Safari, not in Firefox, IE. test("a['\u1d17A']", "a['\u1d17A']"); // Latin capital N with tilde - nice if we handled it, but for now let's // only allow simple Latin (aka ASCII) to be converted. test("a['\u00d1StuffAfter']", "a['\u00d1StuffAfter']"); } public void testQuotedProps() { testSame("({'':0})"); testSame("({'1.0':0})"); testSame("({'\u1d17A':0})"); testSame("({'a\u0004b':0})"); } public void test5746867() { testSame("var a = { '$\\\\' : 5 };"); testSame("var a = { 'x\\\\u0041$\\\\' : 5 };"); } }
public void testCompareTo() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Fraction third = new Fraction(1, 2); assertEquals(0, first.compareTo(first)); assertEquals(0, first.compareTo(third)); assertEquals(1, first.compareTo(second)); assertEquals(-1, second.compareTo(first)); // these two values are different approximations of PI // the first one is approximately PI - 3.07e-18 // the second one is approximately PI + 1.936e-17 Fraction pi1 = new Fraction(1068966896, 340262731); Fraction pi2 = new Fraction( 411557987, 131002976); assertEquals(-1, pi1.compareTo(pi2)); assertEquals( 1, pi2.compareTo(pi1)); assertEquals(0.0, pi1.doubleValue() - pi2.doubleValue(), 1.0e-20); }
org.apache.commons.math.fraction.FractionTest::testCompareTo
src/test/org/apache/commons/math/fraction/FractionTest.java
180
src/test/org/apache/commons/math/fraction/FractionTest.java
testCompareTo
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.fraction; import org.apache.commons.math.ConvergenceException; import junit.framework.TestCase; /** * @version $Revision$ $Date$ */ public class FractionTest extends TestCase { private void assertFraction(int expectedNumerator, int expectedDenominator, Fraction actual) { assertEquals(expectedNumerator, actual.getNumerator()); assertEquals(expectedDenominator, actual.getDenominator()); } public void testConstructor() { assertFraction(0, 1, new Fraction(0, 1)); assertFraction(0, 1, new Fraction(0, 2)); assertFraction(0, 1, new Fraction(0, -1)); assertFraction(1, 2, new Fraction(1, 2)); assertFraction(1, 2, new Fraction(2, 4)); assertFraction(-1, 2, new Fraction(-1, 2)); assertFraction(-1, 2, new Fraction(1, -2)); assertFraction(-1, 2, new Fraction(-2, 4)); assertFraction(-1, 2, new Fraction(2, -4)); // overflow try { new Fraction(Integer.MIN_VALUE, -1); fail(); } catch (ArithmeticException ex) { // success } try { new Fraction(1, Integer.MIN_VALUE); fail(); } catch (ArithmeticException ex) { // success } try { assertFraction(0, 1, new Fraction(0.00000000000001)); assertFraction(2, 5, new Fraction(0.40000000000001)); assertFraction(15, 1, new Fraction(15.0000000000001)); } catch (ConvergenceException ex) { fail(ex.getMessage()); } } public void testGoldenRatio() { try { // the golden ratio is notoriously a difficult number for continuous fraction new Fraction((1 + Math.sqrt(5)) / 2, 1.0e-12, 25); fail("an exception should have been thrown"); } catch (ConvergenceException ce) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); } } // MATH-179 public void testDoubleConstructor() throws ConvergenceException { assertFraction(1, 2, new Fraction((double)1 / (double)2)); assertFraction(1, 3, new Fraction((double)1 / (double)3)); assertFraction(2, 3, new Fraction((double)2 / (double)3)); assertFraction(1, 4, new Fraction((double)1 / (double)4)); assertFraction(3, 4, new Fraction((double)3 / (double)4)); assertFraction(1, 5, new Fraction((double)1 / (double)5)); assertFraction(2, 5, new Fraction((double)2 / (double)5)); assertFraction(3, 5, new Fraction((double)3 / (double)5)); assertFraction(4, 5, new Fraction((double)4 / (double)5)); assertFraction(1, 6, new Fraction((double)1 / (double)6)); assertFraction(5, 6, new Fraction((double)5 / (double)6)); assertFraction(1, 7, new Fraction((double)1 / (double)7)); assertFraction(2, 7, new Fraction((double)2 / (double)7)); assertFraction(3, 7, new Fraction((double)3 / (double)7)); assertFraction(4, 7, new Fraction((double)4 / (double)7)); assertFraction(5, 7, new Fraction((double)5 / (double)7)); assertFraction(6, 7, new Fraction((double)6 / (double)7)); assertFraction(1, 8, new Fraction((double)1 / (double)8)); assertFraction(3, 8, new Fraction((double)3 / (double)8)); assertFraction(5, 8, new Fraction((double)5 / (double)8)); assertFraction(7, 8, new Fraction((double)7 / (double)8)); assertFraction(1, 9, new Fraction((double)1 / (double)9)); assertFraction(2, 9, new Fraction((double)2 / (double)9)); assertFraction(4, 9, new Fraction((double)4 / (double)9)); assertFraction(5, 9, new Fraction((double)5 / (double)9)); assertFraction(7, 9, new Fraction((double)7 / (double)9)); assertFraction(8, 9, new Fraction((double)8 / (double)9)); assertFraction(1, 10, new Fraction((double)1 / (double)10)); assertFraction(3, 10, new Fraction((double)3 / (double)10)); assertFraction(7, 10, new Fraction((double)7 / (double)10)); assertFraction(9, 10, new Fraction((double)9 / (double)10)); assertFraction(1, 11, new Fraction((double)1 / (double)11)); assertFraction(2, 11, new Fraction((double)2 / (double)11)); assertFraction(3, 11, new Fraction((double)3 / (double)11)); assertFraction(4, 11, new Fraction((double)4 / (double)11)); assertFraction(5, 11, new Fraction((double)5 / (double)11)); assertFraction(6, 11, new Fraction((double)6 / (double)11)); assertFraction(7, 11, new Fraction((double)7 / (double)11)); assertFraction(8, 11, new Fraction((double)8 / (double)11)); assertFraction(9, 11, new Fraction((double)9 / (double)11)); assertFraction(10, 11, new Fraction((double)10 / (double)11)); } // MATH-181 public void testDigitLimitConstructor() throws ConvergenceException { assertFraction(2, 5, new Fraction(0.4, 9)); assertFraction(2, 5, new Fraction(0.4, 99)); assertFraction(2, 5, new Fraction(0.4, 999)); assertFraction(3, 5, new Fraction(0.6152, 9)); assertFraction(8, 13, new Fraction(0.6152, 99)); assertFraction(510, 829, new Fraction(0.6152, 999)); assertFraction(769, 1250, new Fraction(0.6152, 9999)); } public void testIntegerOverflow() { checkIntegerOverflow(0.75000000001455192); checkIntegerOverflow(1.0e10); } private void checkIntegerOverflow(double a) { try { new Fraction(a, 1.0e-12, 1000); fail("an exception should have been thrown"); } catch (ConvergenceException ce) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); } } public void testEpsilonLimitConstructor() throws ConvergenceException { assertFraction(2, 5, new Fraction(0.4, 1.0e-5, 100)); assertFraction(3, 5, new Fraction(0.6152, 0.02, 100)); assertFraction(8, 13, new Fraction(0.6152, 1.0e-3, 100)); assertFraction(251, 408, new Fraction(0.6152, 1.0e-4, 100)); assertFraction(251, 408, new Fraction(0.6152, 1.0e-5, 100)); assertFraction(510, 829, new Fraction(0.6152, 1.0e-6, 100)); assertFraction(769, 1250, new Fraction(0.6152, 1.0e-7, 100)); } public void testCompareTo() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Fraction third = new Fraction(1, 2); assertEquals(0, first.compareTo(first)); assertEquals(0, first.compareTo(third)); assertEquals(1, first.compareTo(second)); assertEquals(-1, second.compareTo(first)); // these two values are different approximations of PI // the first one is approximately PI - 3.07e-18 // the second one is approximately PI + 1.936e-17 Fraction pi1 = new Fraction(1068966896, 340262731); Fraction pi2 = new Fraction( 411557987, 131002976); assertEquals(-1, pi1.compareTo(pi2)); assertEquals( 1, pi2.compareTo(pi1)); assertEquals(0.0, pi1.doubleValue() - pi2.doubleValue(), 1.0e-20); } public void testDoubleValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); assertEquals(0.5, first.doubleValue(), 0.0); assertEquals(1.0 / 3.0, second.doubleValue(), 0.0); } public void testFloatValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); assertEquals(0.5f, first.floatValue(), 0.0f); assertEquals((float)(1.0 / 3.0), second.floatValue(), 0.0f); } public void testIntValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); assertEquals(0, first.intValue()); assertEquals(1, second.intValue()); } public void testLongValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); assertEquals(0L, first.longValue()); assertEquals(1L, second.longValue()); } public void testConstructorDouble() { try { assertFraction(1, 2, new Fraction(0.5)); assertFraction(1, 3, new Fraction(1.0 / 3.0)); assertFraction(17, 100, new Fraction(17.0 / 100.0)); assertFraction(317, 100, new Fraction(317.0 / 100.0)); assertFraction(-1, 2, new Fraction(-0.5)); assertFraction(-1, 3, new Fraction(-1.0 / 3.0)); assertFraction(-17, 100, new Fraction(17.0 / -100.0)); assertFraction(-317, 100, new Fraction(-317.0 / 100.0)); } catch (ConvergenceException ex) { fail(ex.getMessage()); } } public void testAbs() { Fraction a = new Fraction(10, 21); Fraction b = new Fraction(-10, 21); Fraction c = new Fraction(10, -21); assertFraction(10, 21, a.abs()); assertFraction(10, 21, b.abs()); assertFraction(10, 21, c.abs()); } public void testReciprocal() { Fraction f = null; f = new Fraction(50, 75); f = f.reciprocal(); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f = new Fraction(4, 3); f = f.reciprocal(); assertEquals(3, f.getNumerator()); assertEquals(4, f.getDenominator()); f = new Fraction(-15, 47); f = f.reciprocal(); assertEquals(-47, f.getNumerator()); assertEquals(15, f.getDenominator()); f = new Fraction(0, 3); try { f = f.reciprocal(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // large values f = new Fraction(Integer.MAX_VALUE, 1); f = f.reciprocal(); assertEquals(1, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); } public void testNegate() { Fraction f = null; f = new Fraction(50, 75); f = f.negate(); assertEquals(-2, f.getNumerator()); assertEquals(3, f.getDenominator()); f = new Fraction(-50, 75); f = f.negate(); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); // large values f = new Fraction(Integer.MAX_VALUE-1, Integer.MAX_VALUE); f = f.negate(); assertEquals(Integer.MIN_VALUE+2, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); f = new Fraction(Integer.MIN_VALUE, 1); try { f = f.negate(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testAdd() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 1, a.add(a)); assertFraction(7, 6, a.add(b)); assertFraction(7, 6, b.add(a)); assertFraction(4, 3, b.add(b)); Fraction f1 = new Fraction(Integer.MAX_VALUE - 1, 1); Fraction f2 = Fraction.ONE; Fraction f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = new Fraction(-1, 13*13*2*2); f2 = new Fraction(-2, 13*17*2); f = f1.add(f2); assertEquals(13*13*17*2*2, f.getDenominator()); assertEquals(-17 - 2*13*2, f.getNumerator()); try { f.add(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is added naively, it will overflow. // check that it doesn't. f1 = new Fraction(1,32768*3); f2 = new Fraction(1,59049); f = f1.add(f2); assertEquals(52451, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, 3); f2 = new Fraction(1,3); f = f1.add(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = new Fraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f = f.add(Fraction.ONE); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(-1,5); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testDivide() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 1, a.divide(a)); assertFraction(3, 4, a.divide(b)); assertFraction(4, 3, b.divide(a)); assertFraction(1, 1, b.divide(b)); Fraction f1 = new Fraction(3, 5); Fraction f2 = Fraction.ZERO; try { f1.divide(f2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = new Fraction(0, 5); f2 = new Fraction(2, 7); Fraction f = f1.divide(f2); assertSame(Fraction.ZERO, f); f1 = new Fraction(2, 7); f2 = Fraction.ONE; f = f1.divide(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.divide(null); fail("IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f1 = new Fraction(1, -Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testMultiply() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 4, a.multiply(a)); assertFraction(1, 3, a.multiply(b)); assertFraction(1, 3, b.multiply(a)); assertFraction(4, 9, b.multiply(b)); Fraction f1 = new Fraction(Integer.MAX_VALUE, 1); Fraction f2 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); Fraction f = f1.multiply(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.multiply(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } public void testSubtract() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(0, 1, a.subtract(a)); assertFraction(-1, 6, a.subtract(b)); assertFraction(1, 6, b.subtract(a)); assertFraction(0, 1, b.subtract(b)); Fraction f = new Fraction(1,1); try { f.subtract(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is subtracted naively, it will overflow. // check that it doesn't. Fraction f1 = new Fraction(1,32768*3); Fraction f2 = new Fraction(1,59049); f = f1.subtract(f2); assertEquals(-13085, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, 3); f2 = new Fraction(1,3).negate(); f = f1.subtract(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = new Fraction(Integer.MAX_VALUE, 1); f2 = Fraction.ONE; f = f1.subtract(f2); assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f1 = new Fraction(1, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE - 1); f = f1.subtract(f2); fail("expecting ArithmeticException"); //should overflow } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(1,5); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= new Fraction(Integer.MIN_VALUE, 1); f = f.subtract(Fraction.ONE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= new Fraction(Integer.MAX_VALUE, 1); f = f.subtract(Fraction.ONE.negate()); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testEqualsAndHashCode() { Fraction zero = new Fraction(0,1); Fraction nullFraction = null; assertTrue( zero.equals(zero)); assertFalse(zero.equals(nullFraction)); assertFalse(zero.equals(Double.valueOf(0))); Fraction zero2 = new Fraction(0,2); assertTrue(zero.equals(zero2)); assertEquals(zero.hashCode(), zero2.hashCode()); Fraction one = new Fraction(1,1); assertFalse((one.equals(zero) ||zero.equals(one))); } public void testGetReducedFraction() { Fraction threeFourths = new Fraction(3, 4); assertTrue(threeFourths.equals(Fraction.getReducedFraction(6, 8))); assertTrue(Fraction.ZERO.equals(Fraction.getReducedFraction(0, -1))); try { Fraction.getReducedFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) { // expected } assertEquals(Fraction.getReducedFraction (2, Integer.MIN_VALUE).getNumerator(),-1); assertEquals(Fraction.getReducedFraction (1, -1).getNumerator(), -1); } }
// You are a professional Java test case writer, please create a test case named `testCompareTo` for the issue `Math-MATH-252`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-252 // // ## Issue-Title: // Fraction.comparTo returns 0 for some differente fractions // // ## Issue-Description: // // If two different fractions evaluate to the same double due to limited precision, // // the compareTo methode returns 0 as if they were identical. // // // // // ``` // // value is roughly PI - 3.07e-18 // Fraction pi1 = new Fraction(1068966896, 340262731); // // // value is roughly PI + 1.936e-17 // Fraction pi2 = new Fraction( 411557987, 131002976); // // System.out.println(pi1.doubleValue() - pi2.doubleValue()); // exactly 0.0 due to limited IEEE754 precision // System.out.println(pi1.compareTo(pi2)); // display 0 instead of a negative value // // ``` // // // // // public void testCompareTo() {
180
91
162
src/test/org/apache/commons/math/fraction/FractionTest.java
src/test
```markdown ## Issue-ID: Math-MATH-252 ## Issue-Title: Fraction.comparTo returns 0 for some differente fractions ## Issue-Description: If two different fractions evaluate to the same double due to limited precision, the compareTo methode returns 0 as if they were identical. ``` // value is roughly PI - 3.07e-18 Fraction pi1 = new Fraction(1068966896, 340262731); // value is roughly PI + 1.936e-17 Fraction pi2 = new Fraction( 411557987, 131002976); System.out.println(pi1.doubleValue() - pi2.doubleValue()); // exactly 0.0 due to limited IEEE754 precision System.out.println(pi1.compareTo(pi2)); // display 0 instead of a negative value ``` ``` You are a professional Java test case writer, please create a test case named `testCompareTo` for the issue `Math-MATH-252`, utilizing the provided issue report information and the following function signature. ```java public void testCompareTo() { ```
162
[ "org.apache.commons.math.fraction.Fraction" ]
2f6d21de689b5ecced32930ed695549019139e7f73e1ce736858bf829a257a54
public void testCompareTo()
// You are a professional Java test case writer, please create a test case named `testCompareTo` for the issue `Math-MATH-252`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-252 // // ## Issue-Title: // Fraction.comparTo returns 0 for some differente fractions // // ## Issue-Description: // // If two different fractions evaluate to the same double due to limited precision, // // the compareTo methode returns 0 as if they were identical. // // // // // ``` // // value is roughly PI - 3.07e-18 // Fraction pi1 = new Fraction(1068966896, 340262731); // // // value is roughly PI + 1.936e-17 // Fraction pi2 = new Fraction( 411557987, 131002976); // // System.out.println(pi1.doubleValue() - pi2.doubleValue()); // exactly 0.0 due to limited IEEE754 precision // System.out.println(pi1.compareTo(pi2)); // display 0 instead of a negative value // // ``` // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.fraction; import org.apache.commons.math.ConvergenceException; import junit.framework.TestCase; /** * @version $Revision$ $Date$ */ public class FractionTest extends TestCase { private void assertFraction(int expectedNumerator, int expectedDenominator, Fraction actual) { assertEquals(expectedNumerator, actual.getNumerator()); assertEquals(expectedDenominator, actual.getDenominator()); } public void testConstructor() { assertFraction(0, 1, new Fraction(0, 1)); assertFraction(0, 1, new Fraction(0, 2)); assertFraction(0, 1, new Fraction(0, -1)); assertFraction(1, 2, new Fraction(1, 2)); assertFraction(1, 2, new Fraction(2, 4)); assertFraction(-1, 2, new Fraction(-1, 2)); assertFraction(-1, 2, new Fraction(1, -2)); assertFraction(-1, 2, new Fraction(-2, 4)); assertFraction(-1, 2, new Fraction(2, -4)); // overflow try { new Fraction(Integer.MIN_VALUE, -1); fail(); } catch (ArithmeticException ex) { // success } try { new Fraction(1, Integer.MIN_VALUE); fail(); } catch (ArithmeticException ex) { // success } try { assertFraction(0, 1, new Fraction(0.00000000000001)); assertFraction(2, 5, new Fraction(0.40000000000001)); assertFraction(15, 1, new Fraction(15.0000000000001)); } catch (ConvergenceException ex) { fail(ex.getMessage()); } } public void testGoldenRatio() { try { // the golden ratio is notoriously a difficult number for continuous fraction new Fraction((1 + Math.sqrt(5)) / 2, 1.0e-12, 25); fail("an exception should have been thrown"); } catch (ConvergenceException ce) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); } } // MATH-179 public void testDoubleConstructor() throws ConvergenceException { assertFraction(1, 2, new Fraction((double)1 / (double)2)); assertFraction(1, 3, new Fraction((double)1 / (double)3)); assertFraction(2, 3, new Fraction((double)2 / (double)3)); assertFraction(1, 4, new Fraction((double)1 / (double)4)); assertFraction(3, 4, new Fraction((double)3 / (double)4)); assertFraction(1, 5, new Fraction((double)1 / (double)5)); assertFraction(2, 5, new Fraction((double)2 / (double)5)); assertFraction(3, 5, new Fraction((double)3 / (double)5)); assertFraction(4, 5, new Fraction((double)4 / (double)5)); assertFraction(1, 6, new Fraction((double)1 / (double)6)); assertFraction(5, 6, new Fraction((double)5 / (double)6)); assertFraction(1, 7, new Fraction((double)1 / (double)7)); assertFraction(2, 7, new Fraction((double)2 / (double)7)); assertFraction(3, 7, new Fraction((double)3 / (double)7)); assertFraction(4, 7, new Fraction((double)4 / (double)7)); assertFraction(5, 7, new Fraction((double)5 / (double)7)); assertFraction(6, 7, new Fraction((double)6 / (double)7)); assertFraction(1, 8, new Fraction((double)1 / (double)8)); assertFraction(3, 8, new Fraction((double)3 / (double)8)); assertFraction(5, 8, new Fraction((double)5 / (double)8)); assertFraction(7, 8, new Fraction((double)7 / (double)8)); assertFraction(1, 9, new Fraction((double)1 / (double)9)); assertFraction(2, 9, new Fraction((double)2 / (double)9)); assertFraction(4, 9, new Fraction((double)4 / (double)9)); assertFraction(5, 9, new Fraction((double)5 / (double)9)); assertFraction(7, 9, new Fraction((double)7 / (double)9)); assertFraction(8, 9, new Fraction((double)8 / (double)9)); assertFraction(1, 10, new Fraction((double)1 / (double)10)); assertFraction(3, 10, new Fraction((double)3 / (double)10)); assertFraction(7, 10, new Fraction((double)7 / (double)10)); assertFraction(9, 10, new Fraction((double)9 / (double)10)); assertFraction(1, 11, new Fraction((double)1 / (double)11)); assertFraction(2, 11, new Fraction((double)2 / (double)11)); assertFraction(3, 11, new Fraction((double)3 / (double)11)); assertFraction(4, 11, new Fraction((double)4 / (double)11)); assertFraction(5, 11, new Fraction((double)5 / (double)11)); assertFraction(6, 11, new Fraction((double)6 / (double)11)); assertFraction(7, 11, new Fraction((double)7 / (double)11)); assertFraction(8, 11, new Fraction((double)8 / (double)11)); assertFraction(9, 11, new Fraction((double)9 / (double)11)); assertFraction(10, 11, new Fraction((double)10 / (double)11)); } // MATH-181 public void testDigitLimitConstructor() throws ConvergenceException { assertFraction(2, 5, new Fraction(0.4, 9)); assertFraction(2, 5, new Fraction(0.4, 99)); assertFraction(2, 5, new Fraction(0.4, 999)); assertFraction(3, 5, new Fraction(0.6152, 9)); assertFraction(8, 13, new Fraction(0.6152, 99)); assertFraction(510, 829, new Fraction(0.6152, 999)); assertFraction(769, 1250, new Fraction(0.6152, 9999)); } public void testIntegerOverflow() { checkIntegerOverflow(0.75000000001455192); checkIntegerOverflow(1.0e10); } private void checkIntegerOverflow(double a) { try { new Fraction(a, 1.0e-12, 1000); fail("an exception should have been thrown"); } catch (ConvergenceException ce) { // expected behavior } catch (Exception e) { fail("wrong exception caught"); } } public void testEpsilonLimitConstructor() throws ConvergenceException { assertFraction(2, 5, new Fraction(0.4, 1.0e-5, 100)); assertFraction(3, 5, new Fraction(0.6152, 0.02, 100)); assertFraction(8, 13, new Fraction(0.6152, 1.0e-3, 100)); assertFraction(251, 408, new Fraction(0.6152, 1.0e-4, 100)); assertFraction(251, 408, new Fraction(0.6152, 1.0e-5, 100)); assertFraction(510, 829, new Fraction(0.6152, 1.0e-6, 100)); assertFraction(769, 1250, new Fraction(0.6152, 1.0e-7, 100)); } public void testCompareTo() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Fraction third = new Fraction(1, 2); assertEquals(0, first.compareTo(first)); assertEquals(0, first.compareTo(third)); assertEquals(1, first.compareTo(second)); assertEquals(-1, second.compareTo(first)); // these two values are different approximations of PI // the first one is approximately PI - 3.07e-18 // the second one is approximately PI + 1.936e-17 Fraction pi1 = new Fraction(1068966896, 340262731); Fraction pi2 = new Fraction( 411557987, 131002976); assertEquals(-1, pi1.compareTo(pi2)); assertEquals( 1, pi2.compareTo(pi1)); assertEquals(0.0, pi1.doubleValue() - pi2.doubleValue(), 1.0e-20); } public void testDoubleValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); assertEquals(0.5, first.doubleValue(), 0.0); assertEquals(1.0 / 3.0, second.doubleValue(), 0.0); } public void testFloatValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); assertEquals(0.5f, first.floatValue(), 0.0f); assertEquals((float)(1.0 / 3.0), second.floatValue(), 0.0f); } public void testIntValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); assertEquals(0, first.intValue()); assertEquals(1, second.intValue()); } public void testLongValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); assertEquals(0L, first.longValue()); assertEquals(1L, second.longValue()); } public void testConstructorDouble() { try { assertFraction(1, 2, new Fraction(0.5)); assertFraction(1, 3, new Fraction(1.0 / 3.0)); assertFraction(17, 100, new Fraction(17.0 / 100.0)); assertFraction(317, 100, new Fraction(317.0 / 100.0)); assertFraction(-1, 2, new Fraction(-0.5)); assertFraction(-1, 3, new Fraction(-1.0 / 3.0)); assertFraction(-17, 100, new Fraction(17.0 / -100.0)); assertFraction(-317, 100, new Fraction(-317.0 / 100.0)); } catch (ConvergenceException ex) { fail(ex.getMessage()); } } public void testAbs() { Fraction a = new Fraction(10, 21); Fraction b = new Fraction(-10, 21); Fraction c = new Fraction(10, -21); assertFraction(10, 21, a.abs()); assertFraction(10, 21, b.abs()); assertFraction(10, 21, c.abs()); } public void testReciprocal() { Fraction f = null; f = new Fraction(50, 75); f = f.reciprocal(); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f = new Fraction(4, 3); f = f.reciprocal(); assertEquals(3, f.getNumerator()); assertEquals(4, f.getDenominator()); f = new Fraction(-15, 47); f = f.reciprocal(); assertEquals(-47, f.getNumerator()); assertEquals(15, f.getDenominator()); f = new Fraction(0, 3); try { f = f.reciprocal(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // large values f = new Fraction(Integer.MAX_VALUE, 1); f = f.reciprocal(); assertEquals(1, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); } public void testNegate() { Fraction f = null; f = new Fraction(50, 75); f = f.negate(); assertEquals(-2, f.getNumerator()); assertEquals(3, f.getDenominator()); f = new Fraction(-50, 75); f = f.negate(); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); // large values f = new Fraction(Integer.MAX_VALUE-1, Integer.MAX_VALUE); f = f.negate(); assertEquals(Integer.MIN_VALUE+2, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); f = new Fraction(Integer.MIN_VALUE, 1); try { f = f.negate(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testAdd() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 1, a.add(a)); assertFraction(7, 6, a.add(b)); assertFraction(7, 6, b.add(a)); assertFraction(4, 3, b.add(b)); Fraction f1 = new Fraction(Integer.MAX_VALUE - 1, 1); Fraction f2 = Fraction.ONE; Fraction f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = new Fraction(-1, 13*13*2*2); f2 = new Fraction(-2, 13*17*2); f = f1.add(f2); assertEquals(13*13*17*2*2, f.getDenominator()); assertEquals(-17 - 2*13*2, f.getNumerator()); try { f.add(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is added naively, it will overflow. // check that it doesn't. f1 = new Fraction(1,32768*3); f2 = new Fraction(1,59049); f = f1.add(f2); assertEquals(52451, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, 3); f2 = new Fraction(1,3); f = f1.add(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = new Fraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f = f.add(Fraction.ONE); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(-1,5); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testDivide() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 1, a.divide(a)); assertFraction(3, 4, a.divide(b)); assertFraction(4, 3, b.divide(a)); assertFraction(1, 1, b.divide(b)); Fraction f1 = new Fraction(3, 5); Fraction f2 = Fraction.ZERO; try { f1.divide(f2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = new Fraction(0, 5); f2 = new Fraction(2, 7); Fraction f = f1.divide(f2); assertSame(Fraction.ZERO, f); f1 = new Fraction(2, 7); f2 = Fraction.ONE; f = f1.divide(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.divide(null); fail("IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f1 = new Fraction(1, -Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testMultiply() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 4, a.multiply(a)); assertFraction(1, 3, a.multiply(b)); assertFraction(1, 3, b.multiply(a)); assertFraction(4, 9, b.multiply(b)); Fraction f1 = new Fraction(Integer.MAX_VALUE, 1); Fraction f2 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); Fraction f = f1.multiply(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.multiply(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } public void testSubtract() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(0, 1, a.subtract(a)); assertFraction(-1, 6, a.subtract(b)); assertFraction(1, 6, b.subtract(a)); assertFraction(0, 1, b.subtract(b)); Fraction f = new Fraction(1,1); try { f.subtract(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is subtracted naively, it will overflow. // check that it doesn't. Fraction f1 = new Fraction(1,32768*3); Fraction f2 = new Fraction(1,59049); f = f1.subtract(f2); assertEquals(-13085, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, 3); f2 = new Fraction(1,3).negate(); f = f1.subtract(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = new Fraction(Integer.MAX_VALUE, 1); f2 = Fraction.ONE; f = f1.subtract(f2); assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f1 = new Fraction(1, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE - 1); f = f1.subtract(f2); fail("expecting ArithmeticException"); //should overflow } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(1,5); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= new Fraction(Integer.MIN_VALUE, 1); f = f.subtract(Fraction.ONE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= new Fraction(Integer.MAX_VALUE, 1); f = f.subtract(Fraction.ONE.negate()); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testEqualsAndHashCode() { Fraction zero = new Fraction(0,1); Fraction nullFraction = null; assertTrue( zero.equals(zero)); assertFalse(zero.equals(nullFraction)); assertFalse(zero.equals(Double.valueOf(0))); Fraction zero2 = new Fraction(0,2); assertTrue(zero.equals(zero2)); assertEquals(zero.hashCode(), zero2.hashCode()); Fraction one = new Fraction(1,1); assertFalse((one.equals(zero) ||zero.equals(one))); } public void testGetReducedFraction() { Fraction threeFourths = new Fraction(3, 4); assertTrue(threeFourths.equals(Fraction.getReducedFraction(6, 8))); assertTrue(Fraction.ZERO.equals(Fraction.getReducedFraction(0, -1))); try { Fraction.getReducedFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) { // expected } assertEquals(Fraction.getReducedFraction (2, Integer.MIN_VALUE).getNumerator(),-1); assertEquals(Fraction.getReducedFraction (1, -1).getNumerator(), -1); } }
@Test public void treatsUndeclaredNamespaceAsLocalName() { String html = "<fb:like>One</fb:like>"; org.jsoup.nodes.Document doc = Jsoup.parse(html); Document w3Doc = new W3CDom().fromJsoup(doc); Node htmlEl = w3Doc.getFirstChild(); assertNull(htmlEl.getNamespaceURI()); assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); Node fb = htmlEl.getFirstChild().getNextSibling().getFirstChild(); assertNull(fb.getNamespaceURI()); assertEquals("like", fb.getLocalName()); assertEquals("fb:like", fb.getNodeName()); }
org.jsoup.helper.W3CDomTest::treatsUndeclaredNamespaceAsLocalName
src/test/java/org/jsoup/helper/W3CDomTest.java
155
src/test/java/org/jsoup/helper/W3CDomTest.java
treatsUndeclaredNamespaceAsLocalName
package org.jsoup.helper; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.integration.ParseTest; import org.jsoup.nodes.Element; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class W3CDomTest { @Test public void simpleConversion() { String html = "<html><head><title>W3c</title></head><body><p class='one' id=12>Text</p><!-- comment --><invalid>What<script>alert('!')"; org.jsoup.nodes.Document doc = Jsoup.parse(html); W3CDom w3c = new W3CDom(); Document wDoc = w3c.fromJsoup(doc); String out = TextUtil.stripNewlines(w3c.asString(wDoc)); String expected = TextUtil.stripNewlines( "<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>W3c</title>" + "</head><body><p class=\"one\" id=\"12\">Text</p><!-- comment --><invalid>What<script>alert('!')</script>" + "</invalid></body></html>" ); assertEquals(expected, out); } @Test public void convertsGoogle() throws IOException { File in = ParseTest.getFile("/htmltests/google-ipod.html"); org.jsoup.nodes.Document doc = Jsoup.parse(in, "UTF8"); W3CDom w3c = new W3CDom(); Document wDoc = w3c.fromJsoup(doc); Node htmlEl = wDoc.getChildNodes().item(0); assertEquals(null, htmlEl.getNamespaceURI()); assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); String out = w3c.asString(wDoc); assertTrue(out.contains("ipod")); } @Test public void convertsGoogleLocation() throws IOException { File in = ParseTest.getFile("/htmltests/google-ipod.html"); org.jsoup.nodes.Document doc = Jsoup.parse(in, "UTF8"); W3CDom w3c = new W3CDom(); Document wDoc = w3c.fromJsoup(doc); String out = w3c.asString(wDoc); assertEquals(doc.location(), wDoc.getDocumentURI() ); } @Test public void namespacePreservation() throws IOException { File in = ParseTest.getFile("/htmltests/namespaces.xhtml"); org.jsoup.nodes.Document jsoupDoc; jsoupDoc = Jsoup.parse(in, "UTF-8"); Document doc; org.jsoup.helper.W3CDom jDom = new org.jsoup.helper.W3CDom(); doc = jDom.fromJsoup(jsoupDoc); Node htmlEl = doc.getChildNodes().item(0); assertEquals("http://www.w3.org/1999/xhtml", htmlEl.getNamespaceURI()); assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); // inherits default namespace Node head = htmlEl.getFirstChild(); assertEquals("http://www.w3.org/1999/xhtml", head.getNamespaceURI()); assertEquals("head", head.getLocalName()); assertEquals("head", head.getNodeName()); Node epubTitle = htmlEl.getChildNodes().item(2).getChildNodes().item(3); assertEquals("Check", epubTitle.getTextContent()); assertEquals("http://www.idpf.org/2007/ops", epubTitle.getNamespaceURI()); assertEquals("title", epubTitle.getLocalName()); assertEquals("epub:title", epubTitle.getNodeName()); Node xSection = epubTitle.getNextSibling().getNextSibling(); assertEquals("urn:test", xSection.getNamespaceURI()); assertEquals("section", xSection.getLocalName()); assertEquals("x:section", xSection.getNodeName()); // https://github.com/jhy/jsoup/issues/977 // does not keep last set namespace Node svg = xSection.getNextSibling().getNextSibling(); assertEquals("http://www.w3.org/2000/svg", svg.getNamespaceURI()); assertEquals("svg", svg.getLocalName()); assertEquals("svg", svg.getNodeName()); Node path = svg.getChildNodes().item(1); assertEquals("http://www.w3.org/2000/svg", path.getNamespaceURI()); assertEquals("path", path.getLocalName()); assertEquals("path", path.getNodeName()); Node clip = path.getChildNodes().item(1); assertEquals("http://example.com/clip", clip.getNamespaceURI()); assertEquals("clip", clip.getLocalName()); assertEquals("clip", clip.getNodeName()); assertEquals("456", clip.getTextContent()); Node picture = svg.getNextSibling().getNextSibling(); assertEquals("http://www.w3.org/1999/xhtml", picture.getNamespaceURI()); assertEquals("picture", picture.getLocalName()); assertEquals("picture", picture.getNodeName()); Node img = picture.getFirstChild(); assertEquals("http://www.w3.org/1999/xhtml", img.getNamespaceURI()); assertEquals("img", img.getLocalName()); assertEquals("img", img.getNodeName()); } @Test public void handlesInvalidAttributeNames() { String html = "<html><head></head><body style=\"color: red\" \" name\"></body></html>"; org.jsoup.nodes.Document jsoupDoc; jsoupDoc = Jsoup.parse(html); Element body = jsoupDoc.select("body").first(); assertTrue(body.hasAttr("\"")); // actually an attribute with key '"'. Correct per HTML5 spec, but w3c xml dom doesn't dig it assertTrue(body.hasAttr("name\"")); Document w3Doc = new W3CDom().fromJsoup(jsoupDoc); } @Test public void treatsUndeclaredNamespaceAsLocalName() { String html = "<fb:like>One</fb:like>"; org.jsoup.nodes.Document doc = Jsoup.parse(html); Document w3Doc = new W3CDom().fromJsoup(doc); Node htmlEl = w3Doc.getFirstChild(); assertNull(htmlEl.getNamespaceURI()); assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); Node fb = htmlEl.getFirstChild().getNextSibling().getFirstChild(); assertNull(fb.getNamespaceURI()); assertEquals("like", fb.getLocalName()); assertEquals("fb:like", fb.getNodeName()); } }
// You are a professional Java test case writer, please create a test case named `treatsUndeclaredNamespaceAsLocalName` for the issue `Jsoup-848`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-848 // // ## Issue-Title: // W3CDom Helper fails to convert whenever some namespace declarations are missing // // ## Issue-Description: // Hello // // // I've been running into an issue where if I convert my Jsoup parsed document into a org.w3c.dom.Document with the W3CDom helper and that document happens to be missing namespace declarations we get the following exception: // // // // ``` // NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces. // // ``` // // I've looked into this a bit and first thing I tried was using a locally forked version of the W3CDom helper that simply turned this flag off: // // // // ``` // factory.setNamespaceAware(false); // // ``` // // However the issue continued, so instead I simply hacked the code to completely ignore namespaces // // // // ``` // // (csueiras): We purposely remove any namespace because we get malformed HTML that might not be // // declaring all of it's namespaces! // Element el = doc.createElementNS("", sourceEl.tagName()); // // ``` // // I am not completely sure if this will have any side effects, but it resolved the issues with the document I'm interacting with. I would be glad to provide a pull request if I have some guidance regarding how to properly handle this issue if it can be handled by Jsoup. // // // The document I'm having issues is simply making use of the Facebook like buttons using tags like this: // // // // ``` // <fb:like ... // // ``` // // But there's no namespace declaration for "fb". // // // // @Test public void treatsUndeclaredNamespaceAsLocalName() {
155
84
139
src/test/java/org/jsoup/helper/W3CDomTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-848 ## Issue-Title: W3CDom Helper fails to convert whenever some namespace declarations are missing ## Issue-Description: Hello I've been running into an issue where if I convert my Jsoup parsed document into a org.w3c.dom.Document with the W3CDom helper and that document happens to be missing namespace declarations we get the following exception: ``` NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces. ``` I've looked into this a bit and first thing I tried was using a locally forked version of the W3CDom helper that simply turned this flag off: ``` factory.setNamespaceAware(false); ``` However the issue continued, so instead I simply hacked the code to completely ignore namespaces ``` // (csueiras): We purposely remove any namespace because we get malformed HTML that might not be // declaring all of it's namespaces! Element el = doc.createElementNS("", sourceEl.tagName()); ``` I am not completely sure if this will have any side effects, but it resolved the issues with the document I'm interacting with. I would be glad to provide a pull request if I have some guidance regarding how to properly handle this issue if it can be handled by Jsoup. The document I'm having issues is simply making use of the Facebook like buttons using tags like this: ``` <fb:like ... ``` But there's no namespace declaration for "fb". ``` You are a professional Java test case writer, please create a test case named `treatsUndeclaredNamespaceAsLocalName` for the issue `Jsoup-848`, utilizing the provided issue report information and the following function signature. ```java @Test public void treatsUndeclaredNamespaceAsLocalName() { ```
139
[ "org.jsoup.helper.W3CDom" ]
2ffc9bb2e59ef1fd96112a97ec5f51eb56dd7cd0bfebc3adc58f22201c08ee51
@Test public void treatsUndeclaredNamespaceAsLocalName()
// You are a professional Java test case writer, please create a test case named `treatsUndeclaredNamespaceAsLocalName` for the issue `Jsoup-848`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-848 // // ## Issue-Title: // W3CDom Helper fails to convert whenever some namespace declarations are missing // // ## Issue-Description: // Hello // // // I've been running into an issue where if I convert my Jsoup parsed document into a org.w3c.dom.Document with the W3CDom helper and that document happens to be missing namespace declarations we get the following exception: // // // // ``` // NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces. // // ``` // // I've looked into this a bit and first thing I tried was using a locally forked version of the W3CDom helper that simply turned this flag off: // // // // ``` // factory.setNamespaceAware(false); // // ``` // // However the issue continued, so instead I simply hacked the code to completely ignore namespaces // // // // ``` // // (csueiras): We purposely remove any namespace because we get malformed HTML that might not be // // declaring all of it's namespaces! // Element el = doc.createElementNS("", sourceEl.tagName()); // // ``` // // I am not completely sure if this will have any side effects, but it resolved the issues with the document I'm interacting with. I would be glad to provide a pull request if I have some guidance regarding how to properly handle this issue if it can be handled by Jsoup. // // // The document I'm having issues is simply making use of the Facebook like buttons using tags like this: // // // // ``` // <fb:like ... // // ``` // // But there's no namespace declaration for "fb". // // // //
Jsoup
package org.jsoup.helper; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.integration.ParseTest; import org.jsoup.nodes.Element; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class W3CDomTest { @Test public void simpleConversion() { String html = "<html><head><title>W3c</title></head><body><p class='one' id=12>Text</p><!-- comment --><invalid>What<script>alert('!')"; org.jsoup.nodes.Document doc = Jsoup.parse(html); W3CDom w3c = new W3CDom(); Document wDoc = w3c.fromJsoup(doc); String out = TextUtil.stripNewlines(w3c.asString(wDoc)); String expected = TextUtil.stripNewlines( "<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>W3c</title>" + "</head><body><p class=\"one\" id=\"12\">Text</p><!-- comment --><invalid>What<script>alert('!')</script>" + "</invalid></body></html>" ); assertEquals(expected, out); } @Test public void convertsGoogle() throws IOException { File in = ParseTest.getFile("/htmltests/google-ipod.html"); org.jsoup.nodes.Document doc = Jsoup.parse(in, "UTF8"); W3CDom w3c = new W3CDom(); Document wDoc = w3c.fromJsoup(doc); Node htmlEl = wDoc.getChildNodes().item(0); assertEquals(null, htmlEl.getNamespaceURI()); assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); String out = w3c.asString(wDoc); assertTrue(out.contains("ipod")); } @Test public void convertsGoogleLocation() throws IOException { File in = ParseTest.getFile("/htmltests/google-ipod.html"); org.jsoup.nodes.Document doc = Jsoup.parse(in, "UTF8"); W3CDom w3c = new W3CDom(); Document wDoc = w3c.fromJsoup(doc); String out = w3c.asString(wDoc); assertEquals(doc.location(), wDoc.getDocumentURI() ); } @Test public void namespacePreservation() throws IOException { File in = ParseTest.getFile("/htmltests/namespaces.xhtml"); org.jsoup.nodes.Document jsoupDoc; jsoupDoc = Jsoup.parse(in, "UTF-8"); Document doc; org.jsoup.helper.W3CDom jDom = new org.jsoup.helper.W3CDom(); doc = jDom.fromJsoup(jsoupDoc); Node htmlEl = doc.getChildNodes().item(0); assertEquals("http://www.w3.org/1999/xhtml", htmlEl.getNamespaceURI()); assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); // inherits default namespace Node head = htmlEl.getFirstChild(); assertEquals("http://www.w3.org/1999/xhtml", head.getNamespaceURI()); assertEquals("head", head.getLocalName()); assertEquals("head", head.getNodeName()); Node epubTitle = htmlEl.getChildNodes().item(2).getChildNodes().item(3); assertEquals("Check", epubTitle.getTextContent()); assertEquals("http://www.idpf.org/2007/ops", epubTitle.getNamespaceURI()); assertEquals("title", epubTitle.getLocalName()); assertEquals("epub:title", epubTitle.getNodeName()); Node xSection = epubTitle.getNextSibling().getNextSibling(); assertEquals("urn:test", xSection.getNamespaceURI()); assertEquals("section", xSection.getLocalName()); assertEquals("x:section", xSection.getNodeName()); // https://github.com/jhy/jsoup/issues/977 // does not keep last set namespace Node svg = xSection.getNextSibling().getNextSibling(); assertEquals("http://www.w3.org/2000/svg", svg.getNamespaceURI()); assertEquals("svg", svg.getLocalName()); assertEquals("svg", svg.getNodeName()); Node path = svg.getChildNodes().item(1); assertEquals("http://www.w3.org/2000/svg", path.getNamespaceURI()); assertEquals("path", path.getLocalName()); assertEquals("path", path.getNodeName()); Node clip = path.getChildNodes().item(1); assertEquals("http://example.com/clip", clip.getNamespaceURI()); assertEquals("clip", clip.getLocalName()); assertEquals("clip", clip.getNodeName()); assertEquals("456", clip.getTextContent()); Node picture = svg.getNextSibling().getNextSibling(); assertEquals("http://www.w3.org/1999/xhtml", picture.getNamespaceURI()); assertEquals("picture", picture.getLocalName()); assertEquals("picture", picture.getNodeName()); Node img = picture.getFirstChild(); assertEquals("http://www.w3.org/1999/xhtml", img.getNamespaceURI()); assertEquals("img", img.getLocalName()); assertEquals("img", img.getNodeName()); } @Test public void handlesInvalidAttributeNames() { String html = "<html><head></head><body style=\"color: red\" \" name\"></body></html>"; org.jsoup.nodes.Document jsoupDoc; jsoupDoc = Jsoup.parse(html); Element body = jsoupDoc.select("body").first(); assertTrue(body.hasAttr("\"")); // actually an attribute with key '"'. Correct per HTML5 spec, but w3c xml dom doesn't dig it assertTrue(body.hasAttr("name\"")); Document w3Doc = new W3CDom().fromJsoup(jsoupDoc); } @Test public void treatsUndeclaredNamespaceAsLocalName() { String html = "<fb:like>One</fb:like>"; org.jsoup.nodes.Document doc = Jsoup.parse(html); Document w3Doc = new W3CDom().fromJsoup(doc); Node htmlEl = w3Doc.getFirstChild(); assertNull(htmlEl.getNamespaceURI()); assertEquals("html", htmlEl.getLocalName()); assertEquals("html", htmlEl.getNodeName()); Node fb = htmlEl.getFirstChild().getNextSibling().getFirstChild(); assertNull(fb.getNamespaceURI()); assertEquals("like", fb.getLocalName()); assertEquals("fb:like", fb.getNodeName()); } }
public void testBadEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); try { // bad interval solver.solve(f, 1, -1); fail("Expecting IllegalArgumentException - bad interval"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5, 1.2); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } }
org.apache.commons.math.analysis.solvers.BrentSolverTest::testBadEndpoints
src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java
337
src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java
testBadEndpoints
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.solvers; import junit.framework.TestCase; import org.apache.commons.math.MathException; import org.apache.commons.math.analysis.MonitoredFunction; import org.apache.commons.math.analysis.QuinticFunction; import org.apache.commons.math.analysis.SinFunction; import org.apache.commons.math.analysis.UnivariateRealFunction; /** * Testcase for UnivariateRealSolver. * Because Brent-Dekker is guaranteed to converge in less than the default * maximum iteration count due to bisection fallback, it is quite hard to * debug. I include measured iteration counts plus one in order to detect * regressions. On average Brent-Dekker should use 4..5 iterations for the * default absolute accuracy of 10E-8 for sinus and the quintic function around * zero, and 5..10 iterations for the other zeros. * * @version $Revision:670469 $ $Date:2008-06-23 10:01:38 +0200 (lun., 23 juin 2008) $ */ public final class BrentSolverTest extends TestCase { public BrentSolverTest(String name) { super(name); } @Deprecated public void testDeprecated() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(f); // Somewhat benign interval. The function is monotone. result = solver.solve(3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); // Larger and somewhat less benign interval. The function is grows first. result = solver.solve(1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); solver = new SecantSolver(f); result = solver.solve(3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); result = solver.solve(1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); assertEquals(result, solver.getResult(), 0); } public void testSinZero() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(); // Somewhat benign interval. The function is monotone. result = solver.solve(f, 3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); // Larger and somewhat less benign interval. The function is grows first. result = solver.solve(f, 1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); solver = new SecantSolver(); result = solver.solve(f, 3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); result = solver.solve(f, 1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); assertEquals(result, solver.getResult(), 0); } public void testQuinticZero() throws MathException { // The quintic function has zeros at 0, +-0.5 and +-1. // Around the root of 0 the function is well behaved, with a second derivative // of zero a 0. // The other roots are less well to find, in particular the root at 1, because // the function grows fast for x>1. // The function has extrema (first derivative is zero) at 0.27195613 and 0.82221643, // intervals containing these values are harder for the solvers. UnivariateRealFunction f = new QuinticFunction(); double result; // Brent-Dekker solver. UnivariateRealSolver solver = new BrentSolver(); // Symmetric bracket around 0. Test whether solvers can handle hitting // the root in the first iteration. result = solver.solve(f, -0.2, 0.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); assertTrue(solver.getIterationCount() <= 2); // 1 iterations on i586 JDK 1.4.1. // Asymmetric bracket around 0, just for fun. Contains extremum. result = solver.solve(f, -0.1, 0.3); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); // Large bracket around 0. Contains two extrema. result = solver.solve(f, -0.3, 0.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Benign bracket around 0.5, function is monotonous. result = solver.solve(f, 0.3, 0.7); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Less benign bracket around 0.5, contains one extremum. result = solver.solve(f, 0.2, 0.6); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Large, less benign bracket around 0.5, contains both extrema. result = solver.solve(f, 0.05, 0.95); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Relatively benign bracket around 1, function is monotonous. Fast growth for x>1 // is still a problem. result = solver.solve(f, 0.85, 1.25); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Less benign bracket around 1 with extremum. result = solver.solve(f, 0.8, 1.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Large bracket around 1. Monotonous. result = solver.solve(f, 0.85, 1.75); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 10 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 11); // Large bracket around 1. Interval contains extremum. result = solver.solve(f, 0.55, 1.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); // Very large bracket around 1 for testing fast growth behaviour. result = solver.solve(f, 0.85, 5); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 12 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 13); // Secant solver. solver = new SecantSolver(); result = solver.solve(f, -0.2, 0.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 1 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 2); result = solver.solve(f, -0.1, 0.3); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); result = solver.solve(f, -0.3, 0.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); result = solver.solve(f, 0.3, 0.7); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); result = solver.solve(f, 0.2, 0.6); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); result = solver.solve(f, 0.05, 0.95); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); result = solver.solve(f, 0.85, 1.25); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 10 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 11); result = solver.solve(f, 0.8, 1.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); result = solver.solve(f, 0.85, 1.75); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 14 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 15); // The followig is especially slow because the solver first has to reduce // the bracket to exclude the extremum. After that, convergence is rapide. result = solver.solve(f, 0.55, 1.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); result = solver.solve(f, 0.85, 5); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 14 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 15); // Static solve method result = UnivariateRealSolverUtils.solve(f, -0.2, 0.2); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = UnivariateRealSolverUtils.solve(f, -0.1, 0.3); assertEquals(result, 0, 1E-8); result = UnivariateRealSolverUtils.solve(f, -0.3, 0.45); assertEquals(result, 0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.3, 0.7); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.2, 0.6); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.05, 0.95); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 1.25); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.8, 1.2); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 1.75); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.55, 1.45); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 5); assertEquals(result, 1.0, 1E-6); } public void testRootEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); // endpoint is root double result = solver.solve(f, Math.PI, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); result = solver.solve(f, 3, Math.PI); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); } public void testBadEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); try { // bad interval solver.solve(f, 1, -1); fail("Expecting IllegalArgumentException - bad interval"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5, 1.2); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } } public void testInitialGuess() throws MathException { MonitoredFunction f = new MonitoredFunction(new QuinticFunction()); UnivariateRealSolver solver = new BrentSolver(); double result; // no guess result = solver.solve(f, 0.6, 7.0); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); int referenceCallsCount = f.getCallsCount(); assertTrue(referenceCallsCount >= 13); // invalid guess (it *is* a root, but outside of the range) try { result = solver.solve(f, 0.6, 7.0, 0.0); fail("an IllegalArgumentException was expected"); } catch (IllegalArgumentException iae) { // expected behaviour } catch (Exception e) { fail("wrong exception caught: " + e.getMessage()); } // bad guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.61); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() > referenceCallsCount); // good guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.999999); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() < referenceCallsCount); // perfect guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 1.0); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertEquals(0, solver.getIterationCount()); assertEquals(1, f.getCallsCount()); } }
// You are a professional Java test case writer, please create a test case named `testBadEndpoints` for the issue `Math-MATH-343`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-343 // // ## Issue-Title: // Brent solver doesn't throw IllegalArgumentException when initial guess has the wrong sign // // ## Issue-Description: // // Javadoc for "public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial)" claims that "if the values of the function at the three points have the same sign" an IllegalArgumentException is thrown. This case isn't even checked. // // // // // public void testBadEndpoints() throws Exception {
337
73
316
src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-343 ## Issue-Title: Brent solver doesn't throw IllegalArgumentException when initial guess has the wrong sign ## Issue-Description: Javadoc for "public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial)" claims that "if the values of the function at the three points have the same sign" an IllegalArgumentException is thrown. This case isn't even checked. ``` You are a professional Java test case writer, please create a test case named `testBadEndpoints` for the issue `Math-MATH-343`, utilizing the provided issue report information and the following function signature. ```java public void testBadEndpoints() throws Exception { ```
316
[ "org.apache.commons.math.analysis.solvers.BrentSolver" ]
310e5fccd103ed5ca2bac1a0023d0fab9def70ab67cc38db59356dba6d219c9c
public void testBadEndpoints() throws Exception
// You are a professional Java test case writer, please create a test case named `testBadEndpoints` for the issue `Math-MATH-343`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-343 // // ## Issue-Title: // Brent solver doesn't throw IllegalArgumentException when initial guess has the wrong sign // // ## Issue-Description: // // Javadoc for "public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial)" claims that "if the values of the function at the three points have the same sign" an IllegalArgumentException is thrown. This case isn't even checked. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.solvers; import junit.framework.TestCase; import org.apache.commons.math.MathException; import org.apache.commons.math.analysis.MonitoredFunction; import org.apache.commons.math.analysis.QuinticFunction; import org.apache.commons.math.analysis.SinFunction; import org.apache.commons.math.analysis.UnivariateRealFunction; /** * Testcase for UnivariateRealSolver. * Because Brent-Dekker is guaranteed to converge in less than the default * maximum iteration count due to bisection fallback, it is quite hard to * debug. I include measured iteration counts plus one in order to detect * regressions. On average Brent-Dekker should use 4..5 iterations for the * default absolute accuracy of 10E-8 for sinus and the quintic function around * zero, and 5..10 iterations for the other zeros. * * @version $Revision:670469 $ $Date:2008-06-23 10:01:38 +0200 (lun., 23 juin 2008) $ */ public final class BrentSolverTest extends TestCase { public BrentSolverTest(String name) { super(name); } @Deprecated public void testDeprecated() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(f); // Somewhat benign interval. The function is monotone. result = solver.solve(3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); // Larger and somewhat less benign interval. The function is grows first. result = solver.solve(1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); solver = new SecantSolver(f); result = solver.solve(3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); result = solver.solve(1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); assertEquals(result, solver.getResult(), 0); } public void testSinZero() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(); // Somewhat benign interval. The function is monotone. result = solver.solve(f, 3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); // Larger and somewhat less benign interval. The function is grows first. result = solver.solve(f, 1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); solver = new SecantSolver(); result = solver.solve(f, 3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); result = solver.solve(f, 1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); assertEquals(result, solver.getResult(), 0); } public void testQuinticZero() throws MathException { // The quintic function has zeros at 0, +-0.5 and +-1. // Around the root of 0 the function is well behaved, with a second derivative // of zero a 0. // The other roots are less well to find, in particular the root at 1, because // the function grows fast for x>1. // The function has extrema (first derivative is zero) at 0.27195613 and 0.82221643, // intervals containing these values are harder for the solvers. UnivariateRealFunction f = new QuinticFunction(); double result; // Brent-Dekker solver. UnivariateRealSolver solver = new BrentSolver(); // Symmetric bracket around 0. Test whether solvers can handle hitting // the root in the first iteration. result = solver.solve(f, -0.2, 0.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); assertTrue(solver.getIterationCount() <= 2); // 1 iterations on i586 JDK 1.4.1. // Asymmetric bracket around 0, just for fun. Contains extremum. result = solver.solve(f, -0.1, 0.3); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); // Large bracket around 0. Contains two extrema. result = solver.solve(f, -0.3, 0.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Benign bracket around 0.5, function is monotonous. result = solver.solve(f, 0.3, 0.7); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Less benign bracket around 0.5, contains one extremum. result = solver.solve(f, 0.2, 0.6); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Large, less benign bracket around 0.5, contains both extrema. result = solver.solve(f, 0.05, 0.95); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Relatively benign bracket around 1, function is monotonous. Fast growth for x>1 // is still a problem. result = solver.solve(f, 0.85, 1.25); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Less benign bracket around 1 with extremum. result = solver.solve(f, 0.8, 1.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Large bracket around 1. Monotonous. result = solver.solve(f, 0.85, 1.75); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 10 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 11); // Large bracket around 1. Interval contains extremum. result = solver.solve(f, 0.55, 1.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); // Very large bracket around 1 for testing fast growth behaviour. result = solver.solve(f, 0.85, 5); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 12 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 13); // Secant solver. solver = new SecantSolver(); result = solver.solve(f, -0.2, 0.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 1 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 2); result = solver.solve(f, -0.1, 0.3); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); result = solver.solve(f, -0.3, 0.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); result = solver.solve(f, 0.3, 0.7); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); result = solver.solve(f, 0.2, 0.6); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); result = solver.solve(f, 0.05, 0.95); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); result = solver.solve(f, 0.85, 1.25); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 10 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 11); result = solver.solve(f, 0.8, 1.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); result = solver.solve(f, 0.85, 1.75); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 14 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 15); // The followig is especially slow because the solver first has to reduce // the bracket to exclude the extremum. After that, convergence is rapide. result = solver.solve(f, 0.55, 1.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); result = solver.solve(f, 0.85, 5); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 14 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 15); // Static solve method result = UnivariateRealSolverUtils.solve(f, -0.2, 0.2); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = UnivariateRealSolverUtils.solve(f, -0.1, 0.3); assertEquals(result, 0, 1E-8); result = UnivariateRealSolverUtils.solve(f, -0.3, 0.45); assertEquals(result, 0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.3, 0.7); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.2, 0.6); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.05, 0.95); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 1.25); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.8, 1.2); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 1.75); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.55, 1.45); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 5); assertEquals(result, 1.0, 1E-6); } public void testRootEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); // endpoint is root double result = solver.solve(f, Math.PI, 4); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); result = solver.solve(f, 3, Math.PI); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); } public void testBadEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); try { // bad interval solver.solve(f, 1, -1); fail("Expecting IllegalArgumentException - bad interval"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5, 1.2); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } } public void testInitialGuess() throws MathException { MonitoredFunction f = new MonitoredFunction(new QuinticFunction()); UnivariateRealSolver solver = new BrentSolver(); double result; // no guess result = solver.solve(f, 0.6, 7.0); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); int referenceCallsCount = f.getCallsCount(); assertTrue(referenceCallsCount >= 13); // invalid guess (it *is* a root, but outside of the range) try { result = solver.solve(f, 0.6, 7.0, 0.0); fail("an IllegalArgumentException was expected"); } catch (IllegalArgumentException iae) { // expected behaviour } catch (Exception e) { fail("wrong exception caught: " + e.getMessage()); } // bad guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.61); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() > referenceCallsCount); // good guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.999999); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() < referenceCallsCount); // perfect guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 1.0); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertEquals(0, solver.getIterationCount()); assertEquals(1, f.getCallsCount()); } }
public void testLang645() { Locale locale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2010, 0, 1, 12, 0, 0); Date d = cal.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); assertEquals("fredag, week 53", fdf.format(d)); }
org.apache.commons.lang3.time.FastDateFormatTest::testLang645
src/test/java/org/apache/commons/lang3/time/FastDateFormatTest.java
337
src/test/java/org/apache/commons/lang3/time/FastDateFormatTest.java
testLang645
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import org.apache.commons.lang3.SerializationUtils; /** * Unit tests {@link org.apache.commons.lang3.time.FastDateFormat}. * * @author Sean Schofield * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @author Fredrik Westermarck * @since 2.0 * @version $Id$ */ public class FastDateFormatTest extends TestCase { public FastDateFormatTest(String name) { super(name); } public void test_getInstance() { FastDateFormat format1 = FastDateFormat.getInstance(); FastDateFormat format2 = FastDateFormat.getInstance(); assertSame(format1, format2); assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern()); } public void test_getInstance_String() { FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format2, format3); assertEquals("MM/DD/yyyy", format1.getPattern()); assertEquals(TimeZone.getDefault(), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); } public void test_getInstance_String_TimeZone() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik")); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault()); FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertSame(format3, format4); assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5); assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void test_getInstance_String_Locale() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format1, format3); assertSame(Locale.GERMANY, format1.getLocale()); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateTimeInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_getInstance_String_TimeZone_Locale() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault(), Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format3.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertEquals(true, format3.getTimeZoneOverridesCalendar()); assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format2.getLocale()); assertEquals(Locale.GERMANY, format3.getLocale()); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void testFormat() {} // Defects4J: flaky method // public void testFormat() { // Locale realDefaultLocale = Locale.getDefault(); // TimeZone realDefaultZone = TimeZone.getDefault(); // try { // Locale.setDefault(Locale.US); // TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); // FastDateFormat fdf = null; // SimpleDateFormat sdf = null; // // GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); // GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); // Date date1 = cal1.getTime(); // Date date2 = cal2.getTime(); // long millis1 = date1.getTime(); // long millis2 = date2.getTime(); // // fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); // sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // assertEquals(sdf.format(date1), fdf.format(date1)); // assertEquals("2003-01-10T15:33:20", fdf.format(date1)); // assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); // assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); // assertEquals("2003-07-10T09:00:00", fdf.format(date2)); // assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); // assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); // // fdf = FastDateFormat.getInstance("Z"); // assertEquals("-0500", fdf.format(date1)); // assertEquals("-0500", fdf.format(cal1)); // assertEquals("-0500", fdf.format(millis1)); // // fdf = FastDateFormat.getInstance("Z"); // assertEquals("-0400", fdf.format(date2)); // assertEquals("-0400", fdf.format(cal2)); // assertEquals("-0400", fdf.format(millis2)); // // fdf = FastDateFormat.getInstance("ZZ"); // assertEquals("-05:00", fdf.format(date1)); // assertEquals("-05:00", fdf.format(cal1)); // assertEquals("-05:00", fdf.format(millis1)); // // fdf = FastDateFormat.getInstance("ZZ"); // assertEquals("-04:00", fdf.format(date2)); // assertEquals("-04:00", fdf.format(cal2)); // assertEquals("-04:00", fdf.format(millis2)); // // String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + // " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; // fdf = FastDateFormat.getInstance(pattern); // sdf = new SimpleDateFormat(pattern); // assertEquals(sdf.format(date1), fdf.format(date1)); // assertEquals(sdf.format(date2), fdf.format(date2)); // // } finally { // Locale.setDefault(realDefaultLocale); // TimeZone.setDefault(realDefaultZone); // } // } /** * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}. */ public void testShortDateStyleWithLocales() { Locale usLocale = Locale.US; Locale swedishLocale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2004, 1, 3); FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale); assertEquals("2/3/04", fdf.format(cal)); fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale); assertEquals("2004-02-03", fdf.format(cal)); } /** * Tests that pre-1000AD years get padded with yyyy */ public void testLowYearPadding() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD"); cal.set(1,0,1); assertEquals("0001/01/01", format.format(cal)); cal.set(10,0,1); assertEquals("0010/01/01", format.format(cal)); cal.set(100,0,1); assertEquals("0100/01/01", format.format(cal)); cal.set(999,0,1); assertEquals("0999/01/01", format.format(cal)); } /** * Show Bug #39410 is solved */ public void testMilleniumBug() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy"); cal.set(1000,0,1); assertEquals("01.01.1000", format.format(cal)); } /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ // TODO: Fix this problem public void testSimpleDate() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); } public void testLang303() { Calendar cal = Calendar.getInstance(); cal.set(2004,11,31); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); String output = format.format(cal); format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) ); assertEquals(output, format.format(cal)); } public void testLang538() { final String dateTime = "2009-10-16T16:42:16.000Z"; // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", dateTime, format.format(cal)); } public void testLang645() { Locale locale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2010, 0, 1, 12, 0, 0); Date d = cal.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); assertEquals("fredag, week 53", fdf.format(d)); } }
// You are a professional Java test case writer, please create a test case named `testLang645` for the issue `Lang-LANG-645`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-645 // // ## Issue-Title: // FastDateFormat.format() outputs incorrect week of year because locale isn't respected // // ## Issue-Description: // // FastDateFormat apparently doesn't respect the locale it was sent on creation when outputting week in year (e.g. "ww") in format(). It seems to use the settings of the system locale for firstDayOfWeek and minimalDaysInFirstWeek, which (depending on the year) may result in the incorrect week number being output. // // // Here is a simple test program to demonstrate the problem by comparing with SimpleDateFormat, which gets the week number right: // // // // // ``` // import java.util.Calendar; // import java.util.Date; // import java.util.Locale; // import java.text.SimpleDateFormat; // // import org.apache.commons.lang.time.FastDateFormat; // // public class FastDateFormatWeekBugDemo { // public static void main(String[] args) { // Locale.setDefault(new Locale("en", "US")); // Locale locale = new Locale("sv", "SE"); // // Calendar cal = Calendar.getInstance(); // setting locale here doesn't change outcome // cal.set(2010, 0, 1, 12, 0, 0); // Date d = cal.getTime(); // System.out.println("Target date: " + d); // // FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); // SimpleDateFormat sdf = new SimpleDateFormat("EEEE', week 'ww", locale); // System.out.println("FastDateFormat: " + fdf.format(d)); // will output "FastDateFormat: fredag, week 01" // System.out.println("SimpleDateFormat: " + sdf.format(d)); // will output "SimpleDateFormat: fredag, week 53" // } // } // // ``` // // // If sv/SE is passed to Locale.setDefault() instead of en/US, both FastDateFormat and SimpleDateFormat output the correct week number. // // // // // public void testLang645() {
337
26
327
src/test/java/org/apache/commons/lang3/time/FastDateFormatTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-645 ## Issue-Title: FastDateFormat.format() outputs incorrect week of year because locale isn't respected ## Issue-Description: FastDateFormat apparently doesn't respect the locale it was sent on creation when outputting week in year (e.g. "ww") in format(). It seems to use the settings of the system locale for firstDayOfWeek and minimalDaysInFirstWeek, which (depending on the year) may result in the incorrect week number being output. Here is a simple test program to demonstrate the problem by comparing with SimpleDateFormat, which gets the week number right: ``` import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.text.SimpleDateFormat; import org.apache.commons.lang.time.FastDateFormat; public class FastDateFormatWeekBugDemo { public static void main(String[] args) { Locale.setDefault(new Locale("en", "US")); Locale locale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); // setting locale here doesn't change outcome cal.set(2010, 0, 1, 12, 0, 0); Date d = cal.getTime(); System.out.println("Target date: " + d); FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); SimpleDateFormat sdf = new SimpleDateFormat("EEEE', week 'ww", locale); System.out.println("FastDateFormat: " + fdf.format(d)); // will output "FastDateFormat: fredag, week 01" System.out.println("SimpleDateFormat: " + sdf.format(d)); // will output "SimpleDateFormat: fredag, week 53" } } ``` If sv/SE is passed to Locale.setDefault() instead of en/US, both FastDateFormat and SimpleDateFormat output the correct week number. ``` You are a professional Java test case writer, please create a test case named `testLang645` for the issue `Lang-LANG-645`, utilizing the provided issue report information and the following function signature. ```java public void testLang645() { ```
327
[ "org.apache.commons.lang3.time.FastDateFormat" ]
313ffa31096b6493a3649c925831a756eb2e4e1ad4a9b536f146f29a8f9c204c
public void testLang645()
// You are a professional Java test case writer, please create a test case named `testLang645` for the issue `Lang-LANG-645`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-645 // // ## Issue-Title: // FastDateFormat.format() outputs incorrect week of year because locale isn't respected // // ## Issue-Description: // // FastDateFormat apparently doesn't respect the locale it was sent on creation when outputting week in year (e.g. "ww") in format(). It seems to use the settings of the system locale for firstDayOfWeek and minimalDaysInFirstWeek, which (depending on the year) may result in the incorrect week number being output. // // // Here is a simple test program to demonstrate the problem by comparing with SimpleDateFormat, which gets the week number right: // // // // // ``` // import java.util.Calendar; // import java.util.Date; // import java.util.Locale; // import java.text.SimpleDateFormat; // // import org.apache.commons.lang.time.FastDateFormat; // // public class FastDateFormatWeekBugDemo { // public static void main(String[] args) { // Locale.setDefault(new Locale("en", "US")); // Locale locale = new Locale("sv", "SE"); // // Calendar cal = Calendar.getInstance(); // setting locale here doesn't change outcome // cal.set(2010, 0, 1, 12, 0, 0); // Date d = cal.getTime(); // System.out.println("Target date: " + d); // // FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); // SimpleDateFormat sdf = new SimpleDateFormat("EEEE', week 'ww", locale); // System.out.println("FastDateFormat: " + fdf.format(d)); // will output "FastDateFormat: fredag, week 01" // System.out.println("SimpleDateFormat: " + sdf.format(d)); // will output "SimpleDateFormat: fredag, week 53" // } // } // // ``` // // // If sv/SE is passed to Locale.setDefault() instead of en/US, both FastDateFormat and SimpleDateFormat output the correct week number. // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import org.apache.commons.lang3.SerializationUtils; /** * Unit tests {@link org.apache.commons.lang3.time.FastDateFormat}. * * @author Sean Schofield * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @author Fredrik Westermarck * @since 2.0 * @version $Id$ */ public class FastDateFormatTest extends TestCase { public FastDateFormatTest(String name) { super(name); } public void test_getInstance() { FastDateFormat format1 = FastDateFormat.getInstance(); FastDateFormat format2 = FastDateFormat.getInstance(); assertSame(format1, format2); assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern()); } public void test_getInstance_String() { FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format2, format3); assertEquals("MM/DD/yyyy", format1.getPattern()); assertEquals(TimeZone.getDefault(), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); } public void test_getInstance_String_TimeZone() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik")); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault()); FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertSame(format3, format4); assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5); assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void test_getInstance_String_Locale() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format1, format3); assertSame(Locale.GERMANY, format1.getLocale()); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateTimeInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_getInstance_String_TimeZone_Locale() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault(), Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format3.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertEquals(true, format3.getTimeZoneOverridesCalendar()); assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format2.getLocale()); assertEquals(Locale.GERMANY, format3.getLocale()); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void testFormat() {} // Defects4J: flaky method // public void testFormat() { // Locale realDefaultLocale = Locale.getDefault(); // TimeZone realDefaultZone = TimeZone.getDefault(); // try { // Locale.setDefault(Locale.US); // TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); // FastDateFormat fdf = null; // SimpleDateFormat sdf = null; // // GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); // GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); // Date date1 = cal1.getTime(); // Date date2 = cal2.getTime(); // long millis1 = date1.getTime(); // long millis2 = date2.getTime(); // // fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); // sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // assertEquals(sdf.format(date1), fdf.format(date1)); // assertEquals("2003-01-10T15:33:20", fdf.format(date1)); // assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); // assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); // assertEquals("2003-07-10T09:00:00", fdf.format(date2)); // assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); // assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); // // fdf = FastDateFormat.getInstance("Z"); // assertEquals("-0500", fdf.format(date1)); // assertEquals("-0500", fdf.format(cal1)); // assertEquals("-0500", fdf.format(millis1)); // // fdf = FastDateFormat.getInstance("Z"); // assertEquals("-0400", fdf.format(date2)); // assertEquals("-0400", fdf.format(cal2)); // assertEquals("-0400", fdf.format(millis2)); // // fdf = FastDateFormat.getInstance("ZZ"); // assertEquals("-05:00", fdf.format(date1)); // assertEquals("-05:00", fdf.format(cal1)); // assertEquals("-05:00", fdf.format(millis1)); // // fdf = FastDateFormat.getInstance("ZZ"); // assertEquals("-04:00", fdf.format(date2)); // assertEquals("-04:00", fdf.format(cal2)); // assertEquals("-04:00", fdf.format(millis2)); // // String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + // " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; // fdf = FastDateFormat.getInstance(pattern); // sdf = new SimpleDateFormat(pattern); // assertEquals(sdf.format(date1), fdf.format(date1)); // assertEquals(sdf.format(date2), fdf.format(date2)); // // } finally { // Locale.setDefault(realDefaultLocale); // TimeZone.setDefault(realDefaultZone); // } // } /** * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}. */ public void testShortDateStyleWithLocales() { Locale usLocale = Locale.US; Locale swedishLocale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2004, 1, 3); FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale); assertEquals("2/3/04", fdf.format(cal)); fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale); assertEquals("2004-02-03", fdf.format(cal)); } /** * Tests that pre-1000AD years get padded with yyyy */ public void testLowYearPadding() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD"); cal.set(1,0,1); assertEquals("0001/01/01", format.format(cal)); cal.set(10,0,1); assertEquals("0010/01/01", format.format(cal)); cal.set(100,0,1); assertEquals("0100/01/01", format.format(cal)); cal.set(999,0,1); assertEquals("0999/01/01", format.format(cal)); } /** * Show Bug #39410 is solved */ public void testMilleniumBug() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy"); cal.set(1000,0,1); assertEquals("01.01.1000", format.format(cal)); } /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ // TODO: Fix this problem public void testSimpleDate() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); } public void testLang303() { Calendar cal = Calendar.getInstance(); cal.set(2004,11,31); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); String output = format.format(cal); format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) ); assertEquals(output, format.format(cal)); } public void testLang538() { final String dateTime = "2009-10-16T16:42:16.000Z"; // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", dateTime, format.format(cal)); } public void testLang645() { Locale locale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2010, 0, 1, 12, 0, 0); Date d = cal.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); assertEquals("fredag, week 53", fdf.format(d)); } }
public void testNamespacedFunctionStubLocal() { testSame( "(function() {" + "var goog = {};" + "/** @param {number} x */ goog.foo;" + "});"); ObjectType goog = (ObjectType) findNameType("goog", lastLocalScope); assertTrue(goog.hasProperty("foo")); assertEquals("function (number): ?", goog.getPropertyType("foo").toString()); assertTrue(goog.isPropertyTypeDeclared("foo")); assertEquals(lastLocalScope.getVar("goog.foo").getType(), goog.getPropertyType("foo")); }
com.google.javascript.jscomp.TypedScopeCreatorTest::testNamespacedFunctionStubLocal
test/com/google/javascript/jscomp/TypedScopeCreatorTest.java
257
test/com/google/javascript/jscomp/TypedScopeCreatorTest.java
testNamespacedFunctionStubLocal
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.ScopeCreator; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.EnumType; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Deque; /** * Tests for {@link TypedScopeCreator} and {@link TypeInference}. Admittedly, * the name is a bit of a misnomer. * @author nicksantos@google.com (Nick Santos) */ public class TypedScopeCreatorTest extends CompilerTestCase { private JSTypeRegistry registry; private Scope globalScope; private Scope lastLocalScope; @Override public int getNumRepetitions() { return 1; } private final Callback callback = new AbstractPostOrderCallback() { public void visit(NodeTraversal t, Node n, Node parent) { Scope s = t.getScope(); if (s.isGlobal()) { globalScope = s; } else { lastLocalScope = s; } } }; @Override public CompilerPass getProcessor(final Compiler compiler) { registry = compiler.getTypeRegistry(); return new CompilerPass() { public void process(Node externs, Node root) { ScopeCreator scopeCreator = new MemoizedScopeCreator(new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(root.getParent(), null); (new TypeInferencePass( compiler, compiler.getReverseAbstractInterpreter(), topScope, scopeCreator)).process(externs, root); NodeTraversal t = new NodeTraversal( compiler, callback, scopeCreator); t.traverseRoots(Lists.newArrayList(externs, root)); } }; } public void testStubProperty() { testSame("function Foo() {}; Foo.bar;"); ObjectType foo = (ObjectType) globalScope.getVar("Foo").getType(); assertFalse(foo.hasProperty("bar")); assertEquals(registry.getNativeType(UNKNOWN_TYPE), foo.getPropertyType("bar")); assertEquals(Sets.newHashSet(foo), registry.getTypesWithProperty("bar")); } public void testConstructorProperty() { testSame("var foo = {}; /** @constructor */ foo.Bar = function() {};"); ObjectType foo = (ObjectType) findNameType("foo", globalScope); assertTrue(foo.hasProperty("Bar")); assertFalse(foo.isPropertyTypeInferred("Bar")); JSType fooBar = foo.getPropertyType("Bar"); assertEquals("function (this:foo.Bar): undefined", fooBar.toString()); assertEquals(Sets.newHashSet(foo), registry.getTypesWithProperty("Bar")); } public void testEnumProperty() { testSame("var foo = {}; /** @enum */ foo.Bar = {XXX: 'xxx'};"); ObjectType foo = (ObjectType) findNameType("foo", globalScope); assertTrue(foo.hasProperty("Bar")); assertFalse(foo.isPropertyTypeInferred("Bar")); assertTrue(foo.isPropertyTypeDeclared("Bar")); JSType fooBar = foo.getPropertyType("Bar"); assertEquals("enum{foo.Bar}", fooBar.toString()); assertEquals(Sets.newHashSet(foo), registry.getTypesWithProperty("Bar")); } public void testInferredProperty() { testSame("var foo = {}; foo.Bar = 3;"); ObjectType foo = (ObjectType) findNameType("foo", globalScope); assertTrue(foo.toString(), foo.hasProperty("Bar")); assertEquals("number", foo.getPropertyType("Bar").toString()); assertTrue(foo.isPropertyTypeInferred("Bar")); } public void testPrototypeInit() { testSame("/** @constructor */ var Foo = function() {};" + "Foo.prototype = {bar: 1}; var foo = new Foo();"); ObjectType foo = (ObjectType) findNameType("foo", globalScope); assertTrue(foo.hasProperty("bar")); assertEquals("number", foo.getPropertyType("bar").toString()); assertTrue(foo.isPropertyTypeInferred("bar")); } public void testInferredPrototypeProperty() { testSame("/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = 1; var x = new Foo();"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertTrue(x.hasProperty("bar")); assertEquals("number", x.getPropertyType("bar").toString()); assertTrue(x.isPropertyTypeInferred("bar")); } public void testEnum() { testSame("/** @enum */ var Foo = {BAR: 1}; var f = Foo;"); ObjectType f = (ObjectType) findNameType("f", globalScope); assertTrue(f.hasProperty("BAR")); assertEquals("Foo.<number>", f.getPropertyType("BAR").toString()); assertTrue(f instanceof EnumType); } public void testNamespacedEnum() { testSame("var goog = {}; goog.ui = {};" + "/** @constructor */goog.ui.Zippy = function() {};" + "/** @enum{string} */goog.ui.Zippy.EventType = { TOGGLE: 'toggle' };" + "var x = goog.ui.Zippy.EventType;" + "var y = goog.ui.Zippy.EventType.TOGGLE;"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertTrue(x.isEnumType()); assertTrue(x.hasProperty("TOGGLE")); assertEquals("enum{goog.ui.Zippy.EventType}", x.getReferenceName()); ObjectType y = (ObjectType) findNameType("y", globalScope); assertTrue(y.isSubtype(getNativeType(STRING_TYPE))); assertTrue(y.isEnumElementType()); assertEquals("goog.ui.Zippy.EventType", y.getReferenceName()); } public void testEnumAlias() { testSame("/** @enum */ var Foo = {BAR: 1}; " + "/** @enum */ var FooAlias = Foo; var f = FooAlias;"); assertEquals("Foo.<number>", registry.getType("FooAlias").toString()); assertEquals(registry.getType("FooAlias"), registry.getType("Foo")); ObjectType f = (ObjectType) findNameType("f", globalScope); assertTrue(f.hasProperty("BAR")); assertEquals("Foo.<number>", f.getPropertyType("BAR").toString()); assertTrue(f instanceof EnumType); } public void testNamespacesEnumAlias() { testSame("var goog = {}; /** @enum */ goog.Foo = {BAR: 1}; " + "/** @enum */ goog.FooAlias = goog.Foo;"); assertEquals("goog.Foo.<number>", registry.getType("goog.FooAlias").toString()); assertEquals(registry.getType("goog.Foo"), registry.getType("goog.FooAlias")); } public void testCollectedFunctionStub() { testSame( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}" + "var x = new f();"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertEquals("f", x.toString()); assertTrue(x.hasProperty("foo")); assertEquals("function (this:f): number", x.getPropertyType("foo").toString()); assertFalse(x.isPropertyTypeInferred("foo")); } public void testCollectedFunctionStubLocal() { testSame( "(function() {" + "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}" + "var x = new f();" + "});"); ObjectType x = (ObjectType) findNameType("x", lastLocalScope); assertEquals("f", x.toString()); assertTrue(x.hasProperty("foo")); assertEquals("function (this:f): number", x.getPropertyType("foo").toString()); assertFalse(x.isPropertyTypeInferred("foo")); } public void testNamespacedFunctionStub() { testSame( "var goog = {};" + "/** @param {number} x */ goog.foo;"); ObjectType goog = (ObjectType) findNameType("goog", globalScope); assertTrue(goog.hasProperty("foo")); assertEquals("function (number): ?", goog.getPropertyType("foo").toString()); assertTrue(goog.isPropertyTypeDeclared("foo")); assertEquals(globalScope.getVar("goog.foo").getType(), goog.getPropertyType("foo")); } public void testNamespacedFunctionStubLocal() { testSame( "(function() {" + "var goog = {};" + "/** @param {number} x */ goog.foo;" + "});"); ObjectType goog = (ObjectType) findNameType("goog", lastLocalScope); assertTrue(goog.hasProperty("foo")); assertEquals("function (number): ?", goog.getPropertyType("foo").toString()); assertTrue(goog.isPropertyTypeDeclared("foo")); assertEquals(lastLocalScope.getVar("goog.foo").getType(), goog.getPropertyType("foo")); } public void testCollectedCtorProperty() { testSame( "/** @constructor */ function f() { " + " /** @type {number} */ this.foo = 3;" + "}" + "var x = new f();"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertEquals("f", x.toString()); assertTrue(x.hasProperty("foo")); assertEquals("number", x.getPropertyType("foo").toString()); assertFalse(x.isPropertyTypeInferred("foo")); } public void testPropertyOnUnknownSuperClass() { testSame( "var goog = this.foo();" + "/** @constructor \n * @extends {goog.Unknown} */" + "function Foo() {}" + "Foo.prototype.bar = 1;" + "var x = new Foo();", RhinoErrorReporter.PARSE_ERROR); ObjectType x = (ObjectType) findNameType("x", globalScope); assertEquals("Foo", x.toString()); assertTrue(x.getImplicitPrototype().hasOwnProperty("bar")); assertEquals("?", x.getPropertyType("bar").toString()); assertTrue(x.isPropertyTypeInferred("bar")); } public void testMethodBeforeFunction() throws Exception { testSame( "var y = Window.prototype;" + "Window.prototype.alert = function(message) {};" + "/** @constructor */ function Window() {}\n" + "var window = new Window(); \n" + "var x = window;"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertEquals("Window", x.toString()); assertTrue(x.getImplicitPrototype().hasOwnProperty("alert")); assertEquals("function (this:Window, ?): undefined", x.getPropertyType("alert").toString()); assertTrue(x.isPropertyTypeDeclared("alert")); ObjectType y = (ObjectType) findNameType("y", globalScope); assertEquals("function (this:Window, ?): undefined", y.getPropertyType("alert").toString()); } public void testAddMethodsPrototypeTwoWays() throws Exception { testSame( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';" + "var x = new A();"); ObjectType instanceType = (ObjectType) findNameType("x", globalScope); assertEquals( getNativeObjectType(OBJECT_TYPE).getPropertiesCount() + 3, instanceType.getPropertiesCount()); assertEquals(getNativeType(NUMBER_TYPE), instanceType.getPropertyType("m1")); assertEquals(getNativeType(BOOLEAN_TYPE), instanceType.getPropertyType("m2")); assertEquals(getNativeType(STRING_TYPE), instanceType.getPropertyType("m3")); // Verify the prototype chain. // The prototype property of a Function has to be a FunctionPrototypeType. // In order to make the type safety work out correctly, we create // a FunctionPrototypeType with the anonymous object as its implicit // prototype. Verify this behavior. assertFalse(instanceType.hasOwnProperty("m1")); assertFalse(instanceType.hasOwnProperty("m2")); assertFalse(instanceType.hasOwnProperty("m3")); ObjectType proto1 = instanceType.getImplicitPrototype(); assertFalse(proto1.hasOwnProperty("m1")); assertFalse(proto1.hasOwnProperty("m2")); assertTrue(proto1.hasOwnProperty("m3")); ObjectType proto2 = proto1.getImplicitPrototype(); assertTrue(proto2.hasOwnProperty("m1")); assertTrue(proto2.hasOwnProperty("m2")); assertFalse(proto2.hasProperty("m3")); } public void testInferredVar() throws Exception { testSame("var x = 3; x = 'x'; x = true;"); Var x = globalScope.getVar("x"); assertEquals("(boolean|number|string)", x.getType().toString()); assertTrue(x.isTypeInferred()); } public void testDeclaredVar() throws Exception { testSame("/** @type {?number} */ var x = 3; var y = x;"); Var x = globalScope.getVar("x"); assertEquals("(null|number)", x.getType().toString()); assertFalse(x.isTypeInferred()); JSType y = findNameType("y", globalScope); assertEquals("(null|number)", y.toString()); } public void testPropertiesOnInterface() throws Exception { testSame("/** @interface */ var I = function() {};" + "/** @type {number} */ I.prototype.bar;" + "I.prototype.baz = function(){};"); Var i = globalScope.getVar("I"); assertEquals("function (this:I): ?", i.getType().toString()); assertTrue(i.getType().isInterface()); ObjectType iPrototype = (ObjectType) ((ObjectType) i.getType()).getPropertyType("prototype"); assertEquals("I.prototype", iPrototype.toString()); assertTrue(iPrototype.isFunctionPrototypeType()); assertEquals("number", iPrototype.getPropertyType("bar").toString()); assertEquals("function (this:I): undefined", iPrototype.getPropertyType("baz").toString()); assertEquals(iPrototype, globalScope.getVar("I.prototype").getType()); } public void testStubsInExterns() { testSame( "/** @constructor */ function Extern() {}" + "Extern.prototype.bar;" + "var e = new Extern(); e.baz;", "/** @constructor */ function Foo() {}" + "Foo.prototype.bar;" + "var f = new Foo(); f.baz;", null); ObjectType e = (ObjectType) globalScope.getVar("e").getType(); assertEquals("?", e.getPropertyType("bar").toString()); assertEquals("?", e.getPropertyType("baz").toString()); ObjectType f = (ObjectType) globalScope.getVar("f").getType(); assertEquals("?", f.getPropertyType("bar").toString()); assertFalse(f.hasProperty("baz")); } public void testStubsInExterns2() { testSame( "/** @constructor */ function Extern() {}" + "/** @type {Extern} */ var myExtern;" + "/** @type {number} */ myExtern.foo;", "", null); JSType e = globalScope.getVar("myExtern").getType(); assertEquals("(Extern|null)", e.toString()); ObjectType externType = (ObjectType) e.restrictByNotNullOrUndefined(); assertTrue(globalScope.getRootNode().toStringTree(), externType.hasOwnProperty("foo")); assertTrue(externType.isPropertyTypeDeclared("foo")); assertEquals("number", externType.getPropertyType("foo").toString()); assertTrue(externType.isPropertyInExterns("foo")); } public void testStubsInExterns3() { testSame( "/** @type {number} */ myExtern.foo;" + "/** @type {Extern} */ var myExtern;" + "/** @constructor */ function Extern() {}", "", null); JSType e = globalScope.getVar("myExtern").getType(); assertEquals("(Extern|null)", e.toString()); ObjectType externType = (ObjectType) e.restrictByNotNullOrUndefined(); assertTrue(globalScope.getRootNode().toStringTree(), externType.hasOwnProperty("foo")); assertTrue(externType.isPropertyTypeDeclared("foo")); assertEquals("number", externType.getPropertyType("foo").toString()); assertTrue(externType.isPropertyInExterns("foo")); } public void testStubsInExterns4() { testSame( "Extern.prototype.foo;" + "/** @constructor */ function Extern() {}", "", null); JSType e = globalScope.getVar("Extern").getType(); assertEquals("function (this:Extern): ?", e.toString()); ObjectType externProto = ((FunctionType) e).getPrototype(); assertTrue(globalScope.getRootNode().toStringTree(), externProto.hasOwnProperty("foo")); assertTrue(externProto.isPropertyTypeInferred("foo")); assertEquals("?", externProto.getPropertyType("foo").toString()); assertTrue(externProto.isPropertyInExterns("foo")); } public void testPropertyInExterns1() { testSame( "/** @constructor */ function Extern() {}" + "/** @type {Extern} */ var extern;" + "/** @return {number} */ extern.one;", "/** @constructor */ function Normal() {}" + "/** @type {Normal} */ var normal;" + "/** @return {number} */ normal.one;", null); JSType e = globalScope.getVar("Extern").getType(); ObjectType externInstance = ((FunctionType) e).getInstanceType(); assertTrue(externInstance.hasOwnProperty("one")); assertTrue(externInstance.isPropertyTypeDeclared("one")); assertTypeEquals("function (): number", externInstance.getPropertyType("one")); JSType n = globalScope.getVar("Normal").getType(); ObjectType normalInstance = ((FunctionType) n).getInstanceType(); assertFalse(normalInstance.hasOwnProperty("one")); } public void testPropertyInExterns2() { testSame( "/** @type {Object} */ var extern;" + "/** @return {number} */ extern.one;", "/** @type {Object} */ var normal;" + "/** @return {number} */ normal.one;", null); JSType e = globalScope.getVar("extern").getType(); assertFalse(e.dereference().hasOwnProperty("one")); JSType normal = globalScope.getVar("normal").getType(); assertFalse(normal.dereference().hasOwnProperty("one")); } public void testPropertyInExterns3() { testSame( "/** @constructor \n * @param {*} x */ function Object(x) {}" + "/** @type {number} */ Object.one;", "", null); ObjectType obj = globalScope.getVar("Object").getType().dereference(); assertTrue(obj.hasOwnProperty("one")); assertTypeEquals("number", obj.getPropertyType("one")); } public void testTypedStubsInExterns() { testSame( "/** @constructor \n * @param {*} var_args */ " + "function Function(var_args) {}" + "/** @type {!Function} */ Function.prototype.apply;", "var f = new Function();", null); ObjectType f = (ObjectType) globalScope.getVar("f").getType(); // The type of apply() on a function instance is resolved dynamically, // since apply varies with the type of the function it's called on. assertEquals( "function ((Object|null|undefined), (Object|null|undefined)): ?", f.getPropertyType("apply").toString()); // The type of apply() on the function prototype just takes what it was // declared with. FunctionType func = (FunctionType) globalScope.getVar("Function").getType(); assertEquals("Function", func.getPrototype().getPropertyType("apply").toString()); } public void testPropertyDeclarationOnInstanceType() { testSame( "/** @type {!Object} */ var a = {};" + "/** @type {number} */ a.name = 0;"); assertEquals("number", globalScope.getVar("a.name").getType().toString()); ObjectType a = (ObjectType) (globalScope.getVar("a").getType()); assertFalse(a.hasProperty("name")); assertFalse(getNativeObjectType(OBJECT_TYPE).hasProperty("name")); } public void testPropertyDeclarationOnRecordType() { testSame( "/** @type {{foo: number}} */ var a = {foo: 3};" + "/** @type {number} */ a.name = 0;"); assertEquals("number", globalScope.getVar("a.name").getType().toString()); ObjectType a = (ObjectType) (globalScope.getVar("a").getType()); assertEquals("{ foo : number }", a.toString()); assertFalse(a.hasProperty("name")); } public void testGlobalThis() { testSame( "/** @constructor */ function Window() {}" + "Window.prototype.alert = function() {};" + "var x = this;"); ObjectType x = (ObjectType) (globalScope.getVar("x").getType()); FunctionType windowCtor = (FunctionType) (globalScope.getVar("Window").getType()); assertEquals("global this", x.toString()); assertTrue(x.isSubtype(windowCtor.getInstanceType())); assertFalse(x.equals(windowCtor.getInstanceType())); assertTrue(x.hasProperty("alert")); } public void testObjectLiteralCast() { testSame("/** @constructor */ A.B = function() {}\n" + "A.B.prototype.isEnabled = true;\n" + "goog.reflect.object(A.B, {isEnabled: 3})\n" + "var x = (new A.B()).isEnabled;"); assertEquals("A.B", findTokenType(Token.OBJECTLIT, globalScope).toString()); assertEquals("boolean", findNameType("x", globalScope).toString()); } public void testBadObjectLiteralCast1() { testSame("/** @constructor */ A.B = function() {}\n" + "goog.reflect.object(A.B, 1)", ClosureCodingConvention.OBJECTLIT_EXPECTED); } public void testBadObjectLiteralCast2() { testSame("goog.reflect.object(A.B, {})", TypedScopeCreator.CONSTRUCTOR_EXPECTED); } public void testConstructorNode() { testSame("var goog = {}; /** @constructor */ goog.Foo = function() {};"); ObjectType ctor = (ObjectType) (findNameType("goog.Foo", globalScope)); assertNotNull(ctor); assertTrue(ctor.isConstructor()); assertEquals("function (this:goog.Foo): undefined", ctor.toString()); } public void testForLoopIntegration() { testSame("var y = 3; for (var x = true; x; y = x) {}"); Var y = globalScope.getVar("y"); assertTrue(y.isTypeInferred()); assertEquals("(boolean|number)", y.getType().toString()); } public void testConstructorAlias() { testSame( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;"); assertEquals("Foo", registry.getType("FooAlias").toString()); assertEquals(registry.getType("Foo"), registry.getType("FooAlias")); } public void testNamespacedConstructorAlias() { testSame( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;"); assertEquals("goog.Foo", registry.getType("goog.FooAlias").toString()); assertEquals(registry.getType("goog.Foo"), registry.getType("goog.FooAlias")); } public void testTemplateType() { testSame( "/**\n" + " * @param {function(this:T, ...)} fn\n" + " * @param {T} thisObj\n" + " * @template T\n" + " */\n" + "function bind(fn, thisObj) {}" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @return {number} */\n" + "Foo.prototype.baz = function() {};\n" + "bind(function() { var f = this.baz(); }, new Foo());"); assertEquals("number", findNameType("f", lastLocalScope).toString()); } public void testClosureParameterTypesWithoutJSDoc() { testSame( "/**\n" + " * @param {function(!Object)} bar\n" + " */\n" + "function foo(bar) {}\n" + "foo(function(baz) { var f = baz; })\n"); assertEquals("Object", findNameType("f", lastLocalScope).toString()); } public void testClosureParameterTypesWithJSDoc() { testSame( "/**\n" + " * @param {function(!Object)} bar\n" + " */\n" + "function foo(bar) {}\n" + "foo((/** @type {function(string)} */" + "function(baz) { var f = baz; }))\n"); assertEquals("string", findNameType("f", lastLocalScope).toString()); } public void testDuplicateExternProperty1() { testSame( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar;" + "/** @type {number} */ Foo.prototype.bar; var x = (new Foo).bar;", null); assertEquals("number", findNameType("x", globalScope).toString()); } public void testDuplicateExternProperty2() { testSame( "/** @constructor */ function Foo() {}" + "/** @type {number} */ Foo.prototype.bar;" + "Foo.prototype.bar; var x = (new Foo).bar;", null); assertEquals("number", findNameType("x", globalScope).toString()); } public void testAbstractMethod() { testSame( "/** @type {!Function} */ var abstractMethod;" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = abstractMethod;"); assertEquals( "Function", findNameType("abstractMethod", globalScope).toString()); FunctionType ctor = (FunctionType) findNameType("Foo", globalScope); ObjectType instance = ctor.getInstanceType(); assertEquals("Foo", instance.toString()); ObjectType proto = instance.getImplicitPrototype(); assertEquals("Foo.prototype", proto.toString()); assertEquals( "function (this:Foo, number): ?", proto.getPropertyType("bar").toString()); } public void testAbstractMethod2() { testSame( "/** @type {!Function} */ var abstractMethod;" + "/** @param {number} x */ var y = abstractMethod;"); assertEquals( "Function", findNameType("y", globalScope).toString()); assertEquals( "function (number): ?", globalScope.getVar("y").getType().toString()); } public void testAbstractMethod3() { testSame( "/** @type {!Function} */ var abstractMethod;" + "/** @param {number} x */ var y = abstractMethod; y;"); assertEquals( "function (number): ?", findNameType("y", globalScope).toString()); } public void testActiveXObject() { testSame( CompilerTypeTestCase.ACTIVE_X_OBJECT_DEF, "var x = new ActiveXObject();", null); assertEquals( "NoObject", findNameType("x", globalScope).toString()); } public void testReturnTypeInference1() { testSame("function f() {}"); assertEquals( "function (): undefined", findNameType("f", globalScope).toString()); } public void testReturnTypeInference2() { testSame("/** @return {?} */ function f() {}"); assertEquals( "function (): ?", findNameType("f", globalScope).toString()); } public void testReturnTypeInference3() { testSame("function f() {x: return 3;}"); assertEquals( "function (): ?", findNameType("f", globalScope).toString()); } public void testReturnTypeInference4() { testSame("function f() { throw Error(); }"); assertEquals( "function (): ?", findNameType("f", globalScope).toString()); } public void testReturnTypeInference5() { testSame("function f() { if (true) { return 1; } }"); assertEquals( "function (): ?", findNameType("f", globalScope).toString()); } public void testLiteralTypesInferred() { testSame("null + true + false + 0 + '' + {}"); assertEquals( "null", findTokenType(Token.NULL, globalScope).toString()); assertEquals( "boolean", findTokenType(Token.TRUE, globalScope).toString()); assertEquals( "boolean", findTokenType(Token.FALSE, globalScope).toString()); assertEquals( "number", findTokenType(Token.NUMBER, globalScope).toString()); assertEquals( "string", findTokenType(Token.STRING, globalScope).toString()); assertEquals( "{}", findTokenType(Token.OBJECTLIT, globalScope).toString()); } private JSType findNameType(final String name, Scope scope) { return findTypeOnMatchedNode(new Predicate<Node>() { @Override public boolean apply(Node n) { return name.equals(n.getQualifiedName()); } }, scope); } private JSType findTokenType(final int type, Scope scope) { return findTypeOnMatchedNode(new Predicate<Node>() { @Override public boolean apply(Node n) { return type == n.getType(); } }, scope); } private JSType findTypeOnMatchedNode(Predicate<Node> matcher, Scope scope) { Node root = scope.getRootNode(); Deque<Node> queue = Lists.newLinkedList(); queue.push(root); while (!queue.isEmpty()) { Node current = queue.pop(); if (matcher.apply(current) && current.getJSType() != null) { return current.getJSType(); } for (Node child : current.children()) { queue.push(child); } } return null; } private JSType getNativeType(JSTypeNative type) { return registry.getNativeType(type); } private ObjectType getNativeObjectType(JSTypeNative type) { return (ObjectType) registry.getNativeType(type); } private void assertTypeEquals(String s, JSType type) { assertEquals(s, type.toString()); } }
// You are a professional Java test case writer, please create a test case named `testNamespacedFunctionStubLocal` for the issue `Closure-61`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-61 // // ## Issue-Title: // Type checker misses annotations on functions defined within functions // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile the following code under --warning\_level VERBOSE // // var ns = {}; // // /\*\* @param {string=} b \*/ // ns.a = function(b) {} // // function d() { // ns.a(); // ns.a(123); // } // // 2. Observe that the type checker correctly emits one warning, as 123 // doesn't match the type {string} // // 3. Now compile the code with ns.a defined within an anonymous function, // like so: // // var ns = {}; // // (function() { // /\*\* @param {string=} b \*/ // ns.a = function(b) {} // })(); // // function d() { // ns.a(); // ns.a(123); // } // // 4. Observe that a warning is emitted for calling ns.a with 0 parameters, and // not for the type error, as though the @param declaration were ignored. // // **What version of the product are you using? On what operating system?** // r15 // // **Please provide any additional information below.** // // This sort of module pattern is common enough that it strikes me as worth // supporting. // // One last note to make matters stranger: if the calling code isn't itself within // a function, no warnings are emitted at all: // // var ns = {}; // // (function() { // /\*\* @param {string=} b \*/ // ns.a = function(b) {} // })(); // // ns.a(); // ns.a(123); // // public void testNamespacedFunctionStubLocal() {
257
150
242
test/com/google/javascript/jscomp/TypedScopeCreatorTest.java
test
```markdown ## Issue-ID: Closure-61 ## Issue-Title: Type checker misses annotations on functions defined within functions ## Issue-Description: **What steps will reproduce the problem?** 1. Compile the following code under --warning\_level VERBOSE var ns = {}; /\*\* @param {string=} b \*/ ns.a = function(b) {} function d() { ns.a(); ns.a(123); } 2. Observe that the type checker correctly emits one warning, as 123 doesn't match the type {string} 3. Now compile the code with ns.a defined within an anonymous function, like so: var ns = {}; (function() { /\*\* @param {string=} b \*/ ns.a = function(b) {} })(); function d() { ns.a(); ns.a(123); } 4. Observe that a warning is emitted for calling ns.a with 0 parameters, and not for the type error, as though the @param declaration were ignored. **What version of the product are you using? On what operating system?** r15 **Please provide any additional information below.** This sort of module pattern is common enough that it strikes me as worth supporting. One last note to make matters stranger: if the calling code isn't itself within a function, no warnings are emitted at all: var ns = {}; (function() { /\*\* @param {string=} b \*/ ns.a = function(b) {} })(); ns.a(); ns.a(123); ``` You are a professional Java test case writer, please create a test case named `testNamespacedFunctionStubLocal` for the issue `Closure-61`, utilizing the provided issue report information and the following function signature. ```java public void testNamespacedFunctionStubLocal() { ```
242
[ "com.google.javascript.jscomp.TypedScopeCreator" ]
31710e92354a041c25caff68b7c071586dfc075d667c59f16c65a72cc6256117
public void testNamespacedFunctionStubLocal()
// You are a professional Java test case writer, please create a test case named `testNamespacedFunctionStubLocal` for the issue `Closure-61`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-61 // // ## Issue-Title: // Type checker misses annotations on functions defined within functions // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile the following code under --warning\_level VERBOSE // // var ns = {}; // // /\*\* @param {string=} b \*/ // ns.a = function(b) {} // // function d() { // ns.a(); // ns.a(123); // } // // 2. Observe that the type checker correctly emits one warning, as 123 // doesn't match the type {string} // // 3. Now compile the code with ns.a defined within an anonymous function, // like so: // // var ns = {}; // // (function() { // /\*\* @param {string=} b \*/ // ns.a = function(b) {} // })(); // // function d() { // ns.a(); // ns.a(123); // } // // 4. Observe that a warning is emitted for calling ns.a with 0 parameters, and // not for the type error, as though the @param declaration were ignored. // // **What version of the product are you using? On what operating system?** // r15 // // **Please provide any additional information below.** // // This sort of module pattern is common enough that it strikes me as worth // supporting. // // One last note to make matters stranger: if the calling code isn't itself within // a function, no warnings are emitted at all: // // var ns = {}; // // (function() { // /\*\* @param {string=} b \*/ // ns.a = function(b) {} // })(); // // ns.a(); // ns.a(123); // //
Closure
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.ScopeCreator; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.EnumType; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Deque; /** * Tests for {@link TypedScopeCreator} and {@link TypeInference}. Admittedly, * the name is a bit of a misnomer. * @author nicksantos@google.com (Nick Santos) */ public class TypedScopeCreatorTest extends CompilerTestCase { private JSTypeRegistry registry; private Scope globalScope; private Scope lastLocalScope; @Override public int getNumRepetitions() { return 1; } private final Callback callback = new AbstractPostOrderCallback() { public void visit(NodeTraversal t, Node n, Node parent) { Scope s = t.getScope(); if (s.isGlobal()) { globalScope = s; } else { lastLocalScope = s; } } }; @Override public CompilerPass getProcessor(final Compiler compiler) { registry = compiler.getTypeRegistry(); return new CompilerPass() { public void process(Node externs, Node root) { ScopeCreator scopeCreator = new MemoizedScopeCreator(new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(root.getParent(), null); (new TypeInferencePass( compiler, compiler.getReverseAbstractInterpreter(), topScope, scopeCreator)).process(externs, root); NodeTraversal t = new NodeTraversal( compiler, callback, scopeCreator); t.traverseRoots(Lists.newArrayList(externs, root)); } }; } public void testStubProperty() { testSame("function Foo() {}; Foo.bar;"); ObjectType foo = (ObjectType) globalScope.getVar("Foo").getType(); assertFalse(foo.hasProperty("bar")); assertEquals(registry.getNativeType(UNKNOWN_TYPE), foo.getPropertyType("bar")); assertEquals(Sets.newHashSet(foo), registry.getTypesWithProperty("bar")); } public void testConstructorProperty() { testSame("var foo = {}; /** @constructor */ foo.Bar = function() {};"); ObjectType foo = (ObjectType) findNameType("foo", globalScope); assertTrue(foo.hasProperty("Bar")); assertFalse(foo.isPropertyTypeInferred("Bar")); JSType fooBar = foo.getPropertyType("Bar"); assertEquals("function (this:foo.Bar): undefined", fooBar.toString()); assertEquals(Sets.newHashSet(foo), registry.getTypesWithProperty("Bar")); } public void testEnumProperty() { testSame("var foo = {}; /** @enum */ foo.Bar = {XXX: 'xxx'};"); ObjectType foo = (ObjectType) findNameType("foo", globalScope); assertTrue(foo.hasProperty("Bar")); assertFalse(foo.isPropertyTypeInferred("Bar")); assertTrue(foo.isPropertyTypeDeclared("Bar")); JSType fooBar = foo.getPropertyType("Bar"); assertEquals("enum{foo.Bar}", fooBar.toString()); assertEquals(Sets.newHashSet(foo), registry.getTypesWithProperty("Bar")); } public void testInferredProperty() { testSame("var foo = {}; foo.Bar = 3;"); ObjectType foo = (ObjectType) findNameType("foo", globalScope); assertTrue(foo.toString(), foo.hasProperty("Bar")); assertEquals("number", foo.getPropertyType("Bar").toString()); assertTrue(foo.isPropertyTypeInferred("Bar")); } public void testPrototypeInit() { testSame("/** @constructor */ var Foo = function() {};" + "Foo.prototype = {bar: 1}; var foo = new Foo();"); ObjectType foo = (ObjectType) findNameType("foo", globalScope); assertTrue(foo.hasProperty("bar")); assertEquals("number", foo.getPropertyType("bar").toString()); assertTrue(foo.isPropertyTypeInferred("bar")); } public void testInferredPrototypeProperty() { testSame("/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = 1; var x = new Foo();"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertTrue(x.hasProperty("bar")); assertEquals("number", x.getPropertyType("bar").toString()); assertTrue(x.isPropertyTypeInferred("bar")); } public void testEnum() { testSame("/** @enum */ var Foo = {BAR: 1}; var f = Foo;"); ObjectType f = (ObjectType) findNameType("f", globalScope); assertTrue(f.hasProperty("BAR")); assertEquals("Foo.<number>", f.getPropertyType("BAR").toString()); assertTrue(f instanceof EnumType); } public void testNamespacedEnum() { testSame("var goog = {}; goog.ui = {};" + "/** @constructor */goog.ui.Zippy = function() {};" + "/** @enum{string} */goog.ui.Zippy.EventType = { TOGGLE: 'toggle' };" + "var x = goog.ui.Zippy.EventType;" + "var y = goog.ui.Zippy.EventType.TOGGLE;"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertTrue(x.isEnumType()); assertTrue(x.hasProperty("TOGGLE")); assertEquals("enum{goog.ui.Zippy.EventType}", x.getReferenceName()); ObjectType y = (ObjectType) findNameType("y", globalScope); assertTrue(y.isSubtype(getNativeType(STRING_TYPE))); assertTrue(y.isEnumElementType()); assertEquals("goog.ui.Zippy.EventType", y.getReferenceName()); } public void testEnumAlias() { testSame("/** @enum */ var Foo = {BAR: 1}; " + "/** @enum */ var FooAlias = Foo; var f = FooAlias;"); assertEquals("Foo.<number>", registry.getType("FooAlias").toString()); assertEquals(registry.getType("FooAlias"), registry.getType("Foo")); ObjectType f = (ObjectType) findNameType("f", globalScope); assertTrue(f.hasProperty("BAR")); assertEquals("Foo.<number>", f.getPropertyType("BAR").toString()); assertTrue(f instanceof EnumType); } public void testNamespacesEnumAlias() { testSame("var goog = {}; /** @enum */ goog.Foo = {BAR: 1}; " + "/** @enum */ goog.FooAlias = goog.Foo;"); assertEquals("goog.Foo.<number>", registry.getType("goog.FooAlias").toString()); assertEquals(registry.getType("goog.Foo"), registry.getType("goog.FooAlias")); } public void testCollectedFunctionStub() { testSame( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}" + "var x = new f();"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertEquals("f", x.toString()); assertTrue(x.hasProperty("foo")); assertEquals("function (this:f): number", x.getPropertyType("foo").toString()); assertFalse(x.isPropertyTypeInferred("foo")); } public void testCollectedFunctionStubLocal() { testSame( "(function() {" + "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}" + "var x = new f();" + "});"); ObjectType x = (ObjectType) findNameType("x", lastLocalScope); assertEquals("f", x.toString()); assertTrue(x.hasProperty("foo")); assertEquals("function (this:f): number", x.getPropertyType("foo").toString()); assertFalse(x.isPropertyTypeInferred("foo")); } public void testNamespacedFunctionStub() { testSame( "var goog = {};" + "/** @param {number} x */ goog.foo;"); ObjectType goog = (ObjectType) findNameType("goog", globalScope); assertTrue(goog.hasProperty("foo")); assertEquals("function (number): ?", goog.getPropertyType("foo").toString()); assertTrue(goog.isPropertyTypeDeclared("foo")); assertEquals(globalScope.getVar("goog.foo").getType(), goog.getPropertyType("foo")); } public void testNamespacedFunctionStubLocal() { testSame( "(function() {" + "var goog = {};" + "/** @param {number} x */ goog.foo;" + "});"); ObjectType goog = (ObjectType) findNameType("goog", lastLocalScope); assertTrue(goog.hasProperty("foo")); assertEquals("function (number): ?", goog.getPropertyType("foo").toString()); assertTrue(goog.isPropertyTypeDeclared("foo")); assertEquals(lastLocalScope.getVar("goog.foo").getType(), goog.getPropertyType("foo")); } public void testCollectedCtorProperty() { testSame( "/** @constructor */ function f() { " + " /** @type {number} */ this.foo = 3;" + "}" + "var x = new f();"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertEquals("f", x.toString()); assertTrue(x.hasProperty("foo")); assertEquals("number", x.getPropertyType("foo").toString()); assertFalse(x.isPropertyTypeInferred("foo")); } public void testPropertyOnUnknownSuperClass() { testSame( "var goog = this.foo();" + "/** @constructor \n * @extends {goog.Unknown} */" + "function Foo() {}" + "Foo.prototype.bar = 1;" + "var x = new Foo();", RhinoErrorReporter.PARSE_ERROR); ObjectType x = (ObjectType) findNameType("x", globalScope); assertEquals("Foo", x.toString()); assertTrue(x.getImplicitPrototype().hasOwnProperty("bar")); assertEquals("?", x.getPropertyType("bar").toString()); assertTrue(x.isPropertyTypeInferred("bar")); } public void testMethodBeforeFunction() throws Exception { testSame( "var y = Window.prototype;" + "Window.prototype.alert = function(message) {};" + "/** @constructor */ function Window() {}\n" + "var window = new Window(); \n" + "var x = window;"); ObjectType x = (ObjectType) findNameType("x", globalScope); assertEquals("Window", x.toString()); assertTrue(x.getImplicitPrototype().hasOwnProperty("alert")); assertEquals("function (this:Window, ?): undefined", x.getPropertyType("alert").toString()); assertTrue(x.isPropertyTypeDeclared("alert")); ObjectType y = (ObjectType) findNameType("y", globalScope); assertEquals("function (this:Window, ?): undefined", y.getPropertyType("alert").toString()); } public void testAddMethodsPrototypeTwoWays() throws Exception { testSame( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';" + "var x = new A();"); ObjectType instanceType = (ObjectType) findNameType("x", globalScope); assertEquals( getNativeObjectType(OBJECT_TYPE).getPropertiesCount() + 3, instanceType.getPropertiesCount()); assertEquals(getNativeType(NUMBER_TYPE), instanceType.getPropertyType("m1")); assertEquals(getNativeType(BOOLEAN_TYPE), instanceType.getPropertyType("m2")); assertEquals(getNativeType(STRING_TYPE), instanceType.getPropertyType("m3")); // Verify the prototype chain. // The prototype property of a Function has to be a FunctionPrototypeType. // In order to make the type safety work out correctly, we create // a FunctionPrototypeType with the anonymous object as its implicit // prototype. Verify this behavior. assertFalse(instanceType.hasOwnProperty("m1")); assertFalse(instanceType.hasOwnProperty("m2")); assertFalse(instanceType.hasOwnProperty("m3")); ObjectType proto1 = instanceType.getImplicitPrototype(); assertFalse(proto1.hasOwnProperty("m1")); assertFalse(proto1.hasOwnProperty("m2")); assertTrue(proto1.hasOwnProperty("m3")); ObjectType proto2 = proto1.getImplicitPrototype(); assertTrue(proto2.hasOwnProperty("m1")); assertTrue(proto2.hasOwnProperty("m2")); assertFalse(proto2.hasProperty("m3")); } public void testInferredVar() throws Exception { testSame("var x = 3; x = 'x'; x = true;"); Var x = globalScope.getVar("x"); assertEquals("(boolean|number|string)", x.getType().toString()); assertTrue(x.isTypeInferred()); } public void testDeclaredVar() throws Exception { testSame("/** @type {?number} */ var x = 3; var y = x;"); Var x = globalScope.getVar("x"); assertEquals("(null|number)", x.getType().toString()); assertFalse(x.isTypeInferred()); JSType y = findNameType("y", globalScope); assertEquals("(null|number)", y.toString()); } public void testPropertiesOnInterface() throws Exception { testSame("/** @interface */ var I = function() {};" + "/** @type {number} */ I.prototype.bar;" + "I.prototype.baz = function(){};"); Var i = globalScope.getVar("I"); assertEquals("function (this:I): ?", i.getType().toString()); assertTrue(i.getType().isInterface()); ObjectType iPrototype = (ObjectType) ((ObjectType) i.getType()).getPropertyType("prototype"); assertEquals("I.prototype", iPrototype.toString()); assertTrue(iPrototype.isFunctionPrototypeType()); assertEquals("number", iPrototype.getPropertyType("bar").toString()); assertEquals("function (this:I): undefined", iPrototype.getPropertyType("baz").toString()); assertEquals(iPrototype, globalScope.getVar("I.prototype").getType()); } public void testStubsInExterns() { testSame( "/** @constructor */ function Extern() {}" + "Extern.prototype.bar;" + "var e = new Extern(); e.baz;", "/** @constructor */ function Foo() {}" + "Foo.prototype.bar;" + "var f = new Foo(); f.baz;", null); ObjectType e = (ObjectType) globalScope.getVar("e").getType(); assertEquals("?", e.getPropertyType("bar").toString()); assertEquals("?", e.getPropertyType("baz").toString()); ObjectType f = (ObjectType) globalScope.getVar("f").getType(); assertEquals("?", f.getPropertyType("bar").toString()); assertFalse(f.hasProperty("baz")); } public void testStubsInExterns2() { testSame( "/** @constructor */ function Extern() {}" + "/** @type {Extern} */ var myExtern;" + "/** @type {number} */ myExtern.foo;", "", null); JSType e = globalScope.getVar("myExtern").getType(); assertEquals("(Extern|null)", e.toString()); ObjectType externType = (ObjectType) e.restrictByNotNullOrUndefined(); assertTrue(globalScope.getRootNode().toStringTree(), externType.hasOwnProperty("foo")); assertTrue(externType.isPropertyTypeDeclared("foo")); assertEquals("number", externType.getPropertyType("foo").toString()); assertTrue(externType.isPropertyInExterns("foo")); } public void testStubsInExterns3() { testSame( "/** @type {number} */ myExtern.foo;" + "/** @type {Extern} */ var myExtern;" + "/** @constructor */ function Extern() {}", "", null); JSType e = globalScope.getVar("myExtern").getType(); assertEquals("(Extern|null)", e.toString()); ObjectType externType = (ObjectType) e.restrictByNotNullOrUndefined(); assertTrue(globalScope.getRootNode().toStringTree(), externType.hasOwnProperty("foo")); assertTrue(externType.isPropertyTypeDeclared("foo")); assertEquals("number", externType.getPropertyType("foo").toString()); assertTrue(externType.isPropertyInExterns("foo")); } public void testStubsInExterns4() { testSame( "Extern.prototype.foo;" + "/** @constructor */ function Extern() {}", "", null); JSType e = globalScope.getVar("Extern").getType(); assertEquals("function (this:Extern): ?", e.toString()); ObjectType externProto = ((FunctionType) e).getPrototype(); assertTrue(globalScope.getRootNode().toStringTree(), externProto.hasOwnProperty("foo")); assertTrue(externProto.isPropertyTypeInferred("foo")); assertEquals("?", externProto.getPropertyType("foo").toString()); assertTrue(externProto.isPropertyInExterns("foo")); } public void testPropertyInExterns1() { testSame( "/** @constructor */ function Extern() {}" + "/** @type {Extern} */ var extern;" + "/** @return {number} */ extern.one;", "/** @constructor */ function Normal() {}" + "/** @type {Normal} */ var normal;" + "/** @return {number} */ normal.one;", null); JSType e = globalScope.getVar("Extern").getType(); ObjectType externInstance = ((FunctionType) e).getInstanceType(); assertTrue(externInstance.hasOwnProperty("one")); assertTrue(externInstance.isPropertyTypeDeclared("one")); assertTypeEquals("function (): number", externInstance.getPropertyType("one")); JSType n = globalScope.getVar("Normal").getType(); ObjectType normalInstance = ((FunctionType) n).getInstanceType(); assertFalse(normalInstance.hasOwnProperty("one")); } public void testPropertyInExterns2() { testSame( "/** @type {Object} */ var extern;" + "/** @return {number} */ extern.one;", "/** @type {Object} */ var normal;" + "/** @return {number} */ normal.one;", null); JSType e = globalScope.getVar("extern").getType(); assertFalse(e.dereference().hasOwnProperty("one")); JSType normal = globalScope.getVar("normal").getType(); assertFalse(normal.dereference().hasOwnProperty("one")); } public void testPropertyInExterns3() { testSame( "/** @constructor \n * @param {*} x */ function Object(x) {}" + "/** @type {number} */ Object.one;", "", null); ObjectType obj = globalScope.getVar("Object").getType().dereference(); assertTrue(obj.hasOwnProperty("one")); assertTypeEquals("number", obj.getPropertyType("one")); } public void testTypedStubsInExterns() { testSame( "/** @constructor \n * @param {*} var_args */ " + "function Function(var_args) {}" + "/** @type {!Function} */ Function.prototype.apply;", "var f = new Function();", null); ObjectType f = (ObjectType) globalScope.getVar("f").getType(); // The type of apply() on a function instance is resolved dynamically, // since apply varies with the type of the function it's called on. assertEquals( "function ((Object|null|undefined), (Object|null|undefined)): ?", f.getPropertyType("apply").toString()); // The type of apply() on the function prototype just takes what it was // declared with. FunctionType func = (FunctionType) globalScope.getVar("Function").getType(); assertEquals("Function", func.getPrototype().getPropertyType("apply").toString()); } public void testPropertyDeclarationOnInstanceType() { testSame( "/** @type {!Object} */ var a = {};" + "/** @type {number} */ a.name = 0;"); assertEquals("number", globalScope.getVar("a.name").getType().toString()); ObjectType a = (ObjectType) (globalScope.getVar("a").getType()); assertFalse(a.hasProperty("name")); assertFalse(getNativeObjectType(OBJECT_TYPE).hasProperty("name")); } public void testPropertyDeclarationOnRecordType() { testSame( "/** @type {{foo: number}} */ var a = {foo: 3};" + "/** @type {number} */ a.name = 0;"); assertEquals("number", globalScope.getVar("a.name").getType().toString()); ObjectType a = (ObjectType) (globalScope.getVar("a").getType()); assertEquals("{ foo : number }", a.toString()); assertFalse(a.hasProperty("name")); } public void testGlobalThis() { testSame( "/** @constructor */ function Window() {}" + "Window.prototype.alert = function() {};" + "var x = this;"); ObjectType x = (ObjectType) (globalScope.getVar("x").getType()); FunctionType windowCtor = (FunctionType) (globalScope.getVar("Window").getType()); assertEquals("global this", x.toString()); assertTrue(x.isSubtype(windowCtor.getInstanceType())); assertFalse(x.equals(windowCtor.getInstanceType())); assertTrue(x.hasProperty("alert")); } public void testObjectLiteralCast() { testSame("/** @constructor */ A.B = function() {}\n" + "A.B.prototype.isEnabled = true;\n" + "goog.reflect.object(A.B, {isEnabled: 3})\n" + "var x = (new A.B()).isEnabled;"); assertEquals("A.B", findTokenType(Token.OBJECTLIT, globalScope).toString()); assertEquals("boolean", findNameType("x", globalScope).toString()); } public void testBadObjectLiteralCast1() { testSame("/** @constructor */ A.B = function() {}\n" + "goog.reflect.object(A.B, 1)", ClosureCodingConvention.OBJECTLIT_EXPECTED); } public void testBadObjectLiteralCast2() { testSame("goog.reflect.object(A.B, {})", TypedScopeCreator.CONSTRUCTOR_EXPECTED); } public void testConstructorNode() { testSame("var goog = {}; /** @constructor */ goog.Foo = function() {};"); ObjectType ctor = (ObjectType) (findNameType("goog.Foo", globalScope)); assertNotNull(ctor); assertTrue(ctor.isConstructor()); assertEquals("function (this:goog.Foo): undefined", ctor.toString()); } public void testForLoopIntegration() { testSame("var y = 3; for (var x = true; x; y = x) {}"); Var y = globalScope.getVar("y"); assertTrue(y.isTypeInferred()); assertEquals("(boolean|number)", y.getType().toString()); } public void testConstructorAlias() { testSame( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;"); assertEquals("Foo", registry.getType("FooAlias").toString()); assertEquals(registry.getType("Foo"), registry.getType("FooAlias")); } public void testNamespacedConstructorAlias() { testSame( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;"); assertEquals("goog.Foo", registry.getType("goog.FooAlias").toString()); assertEquals(registry.getType("goog.Foo"), registry.getType("goog.FooAlias")); } public void testTemplateType() { testSame( "/**\n" + " * @param {function(this:T, ...)} fn\n" + " * @param {T} thisObj\n" + " * @template T\n" + " */\n" + "function bind(fn, thisObj) {}" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @return {number} */\n" + "Foo.prototype.baz = function() {};\n" + "bind(function() { var f = this.baz(); }, new Foo());"); assertEquals("number", findNameType("f", lastLocalScope).toString()); } public void testClosureParameterTypesWithoutJSDoc() { testSame( "/**\n" + " * @param {function(!Object)} bar\n" + " */\n" + "function foo(bar) {}\n" + "foo(function(baz) { var f = baz; })\n"); assertEquals("Object", findNameType("f", lastLocalScope).toString()); } public void testClosureParameterTypesWithJSDoc() { testSame( "/**\n" + " * @param {function(!Object)} bar\n" + " */\n" + "function foo(bar) {}\n" + "foo((/** @type {function(string)} */" + "function(baz) { var f = baz; }))\n"); assertEquals("string", findNameType("f", lastLocalScope).toString()); } public void testDuplicateExternProperty1() { testSame( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar;" + "/** @type {number} */ Foo.prototype.bar; var x = (new Foo).bar;", null); assertEquals("number", findNameType("x", globalScope).toString()); } public void testDuplicateExternProperty2() { testSame( "/** @constructor */ function Foo() {}" + "/** @type {number} */ Foo.prototype.bar;" + "Foo.prototype.bar; var x = (new Foo).bar;", null); assertEquals("number", findNameType("x", globalScope).toString()); } public void testAbstractMethod() { testSame( "/** @type {!Function} */ var abstractMethod;" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = abstractMethod;"); assertEquals( "Function", findNameType("abstractMethod", globalScope).toString()); FunctionType ctor = (FunctionType) findNameType("Foo", globalScope); ObjectType instance = ctor.getInstanceType(); assertEquals("Foo", instance.toString()); ObjectType proto = instance.getImplicitPrototype(); assertEquals("Foo.prototype", proto.toString()); assertEquals( "function (this:Foo, number): ?", proto.getPropertyType("bar").toString()); } public void testAbstractMethod2() { testSame( "/** @type {!Function} */ var abstractMethod;" + "/** @param {number} x */ var y = abstractMethod;"); assertEquals( "Function", findNameType("y", globalScope).toString()); assertEquals( "function (number): ?", globalScope.getVar("y").getType().toString()); } public void testAbstractMethod3() { testSame( "/** @type {!Function} */ var abstractMethod;" + "/** @param {number} x */ var y = abstractMethod; y;"); assertEquals( "function (number): ?", findNameType("y", globalScope).toString()); } public void testActiveXObject() { testSame( CompilerTypeTestCase.ACTIVE_X_OBJECT_DEF, "var x = new ActiveXObject();", null); assertEquals( "NoObject", findNameType("x", globalScope).toString()); } public void testReturnTypeInference1() { testSame("function f() {}"); assertEquals( "function (): undefined", findNameType("f", globalScope).toString()); } public void testReturnTypeInference2() { testSame("/** @return {?} */ function f() {}"); assertEquals( "function (): ?", findNameType("f", globalScope).toString()); } public void testReturnTypeInference3() { testSame("function f() {x: return 3;}"); assertEquals( "function (): ?", findNameType("f", globalScope).toString()); } public void testReturnTypeInference4() { testSame("function f() { throw Error(); }"); assertEquals( "function (): ?", findNameType("f", globalScope).toString()); } public void testReturnTypeInference5() { testSame("function f() { if (true) { return 1; } }"); assertEquals( "function (): ?", findNameType("f", globalScope).toString()); } public void testLiteralTypesInferred() { testSame("null + true + false + 0 + '' + {}"); assertEquals( "null", findTokenType(Token.NULL, globalScope).toString()); assertEquals( "boolean", findTokenType(Token.TRUE, globalScope).toString()); assertEquals( "boolean", findTokenType(Token.FALSE, globalScope).toString()); assertEquals( "number", findTokenType(Token.NUMBER, globalScope).toString()); assertEquals( "string", findTokenType(Token.STRING, globalScope).toString()); assertEquals( "{}", findTokenType(Token.OBJECTLIT, globalScope).toString()); } private JSType findNameType(final String name, Scope scope) { return findTypeOnMatchedNode(new Predicate<Node>() { @Override public boolean apply(Node n) { return name.equals(n.getQualifiedName()); } }, scope); } private JSType findTokenType(final int type, Scope scope) { return findTypeOnMatchedNode(new Predicate<Node>() { @Override public boolean apply(Node n) { return type == n.getType(); } }, scope); } private JSType findTypeOnMatchedNode(Predicate<Node> matcher, Scope scope) { Node root = scope.getRootNode(); Deque<Node> queue = Lists.newLinkedList(); queue.push(root); while (!queue.isEmpty()) { Node current = queue.pop(); if (matcher.apply(current) && current.getJSType() != null) { return current.getJSType(); } for (Node child : current.children()) { queue.push(child); } } return null; } private JSType getNativeType(JSTypeNative type) { return registry.getNativeType(type); } private ObjectType getNativeObjectType(JSTypeNative type) { return (ObjectType) registry.getNativeType(type); } private void assertTypeEquals(String s, JSType type) { assertEquals(s, type.toString()); } }
@Test public void discoverDeepMockingOfGenerics() { MyClass1 myMock1 = mock(MyClass1.class, RETURNS_DEEP_STUBS); when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World."); }
org.mockitousage.bugs.deepstubs.DeepStubFailingWhenGenricNestedAsRawTypeTest::discoverDeepMockingOfGenerics
test/org/mockitousage/bugs/deepstubs/DeepStubFailingWhenGenricNestedAsRawTypeTest.java
26
test/org/mockitousage/bugs/deepstubs/DeepStubFailingWhenGenricNestedAsRawTypeTest.java
discoverDeepMockingOfGenerics
package org.mockitousage.bugs.deepstubs; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test; public class DeepStubFailingWhenGenricNestedAsRawTypeTest { interface MyClass1<MC2 extends MyClass2> { MC2 getNested(); } interface MyClass2<MC3 extends MyClass3> { MC3 getNested(); } interface MyClass3 { String returnSomething(); } @Test public void discoverDeepMockingOfGenerics() { MyClass1 myMock1 = mock(MyClass1.class, RETURNS_DEEP_STUBS); when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World."); } }
// You are a professional Java test case writer, please create a test case named `discoverDeepMockingOfGenerics` for the issue `Mockito-128`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-128 // // ## Issue-Title: // Deep stubbing with generic responses in the call chain is not working // // ## Issue-Description: // Deep stubbing will throw an Exception if multiple generics occur in the call chain. For instance, consider having a mock `myMock1` that provides a function that returns a generic `T`. If `T` also has a function that returns a generic, an Exception with the message "Raw extraction not supported for : 'null'" will be thrown. // // // As an example the following test will throw an Exception: // // // // ``` // public class MockitoGenericsDeepStubTest { // // @Test // public void discoverDeepMockingOfGenerics() { // MyClass1 myMock1 = mock(MyClass1.class, RETURNS\_DEEP\_STUBS); // // when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World."); // } // // public static interface MyClass1 <MC2 extends MyClass2> { // public MC2 getNested(); // } // // public static interface MyClass2<MC3 extends MyClass3> { // public MC3 getNested(); // } // // public static interface MyClass3 { // public String returnSomething(); // } // } // ``` // // You can make this test run if you step into the class `ReturnsDeepStubs` and change the method `withSettingsUsing` to return `MockSettings` with `ReturnsDeepStubs` instead of `ReturnsDeepStubsSerializationFallback` as default answer: // // // // ``` // private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) { // MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ? // withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces()) // : withSettings(); // // return propagateSerializationSettings(mockSettings, parentMockSettings) // .defaultAnswer(this); // } // ``` // // However, this breaks other tests and features. // // // I think, the issue is that further generics are not possible to be mocked by `ReturnsDeepStubsSerializationFallback` since the `GenericMetadataSupport` is "closed" at this point. // // // Thanks and kind regards // // Tobias // // // // @Test public void discoverDeepMockingOfGenerics() {
26
7
22
test/org/mockitousage/bugs/deepstubs/DeepStubFailingWhenGenricNestedAsRawTypeTest.java
test
```markdown ## Issue-ID: Mockito-128 ## Issue-Title: Deep stubbing with generic responses in the call chain is not working ## Issue-Description: Deep stubbing will throw an Exception if multiple generics occur in the call chain. For instance, consider having a mock `myMock1` that provides a function that returns a generic `T`. If `T` also has a function that returns a generic, an Exception with the message "Raw extraction not supported for : 'null'" will be thrown. As an example the following test will throw an Exception: ``` public class MockitoGenericsDeepStubTest { @Test public void discoverDeepMockingOfGenerics() { MyClass1 myMock1 = mock(MyClass1.class, RETURNS\_DEEP\_STUBS); when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World."); } public static interface MyClass1 <MC2 extends MyClass2> { public MC2 getNested(); } public static interface MyClass2<MC3 extends MyClass3> { public MC3 getNested(); } public static interface MyClass3 { public String returnSomething(); } } ``` You can make this test run if you step into the class `ReturnsDeepStubs` and change the method `withSettingsUsing` to return `MockSettings` with `ReturnsDeepStubs` instead of `ReturnsDeepStubsSerializationFallback` as default answer: ``` private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) { MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ? withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces()) : withSettings(); return propagateSerializationSettings(mockSettings, parentMockSettings) .defaultAnswer(this); } ``` However, this breaks other tests and features. I think, the issue is that further generics are not possible to be mocked by `ReturnsDeepStubsSerializationFallback` since the `GenericMetadataSupport` is "closed" at this point. Thanks and kind regards Tobias ``` You are a professional Java test case writer, please create a test case named `discoverDeepMockingOfGenerics` for the issue `Mockito-128`, utilizing the provided issue report information and the following function signature. ```java @Test public void discoverDeepMockingOfGenerics() { ```
22
[ "org.mockito.internal.util.reflection.GenericMetadataSupport" ]
3218dca4fd2bccc1b6a5dcf6bdd7a2ae6dfa9c3562a145a587bfb754dce70313
@Test public void discoverDeepMockingOfGenerics()
// You are a professional Java test case writer, please create a test case named `discoverDeepMockingOfGenerics` for the issue `Mockito-128`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-128 // // ## Issue-Title: // Deep stubbing with generic responses in the call chain is not working // // ## Issue-Description: // Deep stubbing will throw an Exception if multiple generics occur in the call chain. For instance, consider having a mock `myMock1` that provides a function that returns a generic `T`. If `T` also has a function that returns a generic, an Exception with the message "Raw extraction not supported for : 'null'" will be thrown. // // // As an example the following test will throw an Exception: // // // // ``` // public class MockitoGenericsDeepStubTest { // // @Test // public void discoverDeepMockingOfGenerics() { // MyClass1 myMock1 = mock(MyClass1.class, RETURNS\_DEEP\_STUBS); // // when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World."); // } // // public static interface MyClass1 <MC2 extends MyClass2> { // public MC2 getNested(); // } // // public static interface MyClass2<MC3 extends MyClass3> { // public MC3 getNested(); // } // // public static interface MyClass3 { // public String returnSomething(); // } // } // ``` // // You can make this test run if you step into the class `ReturnsDeepStubs` and change the method `withSettingsUsing` to return `MockSettings` with `ReturnsDeepStubs` instead of `ReturnsDeepStubsSerializationFallback` as default answer: // // // // ``` // private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) { // MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ? // withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces()) // : withSettings(); // // return propagateSerializationSettings(mockSettings, parentMockSettings) // .defaultAnswer(this); // } // ``` // // However, this breaks other tests and features. // // // I think, the issue is that further generics are not possible to be mocked by `ReturnsDeepStubsSerializationFallback` since the `GenericMetadataSupport` is "closed" at this point. // // // Thanks and kind regards // // Tobias // // // //
Mockito
package org.mockitousage.bugs.deepstubs; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test; public class DeepStubFailingWhenGenricNestedAsRawTypeTest { interface MyClass1<MC2 extends MyClass2> { MC2 getNested(); } interface MyClass2<MC3 extends MyClass3> { MC3 getNested(); } interface MyClass3 { String returnSomething(); } @Test public void discoverDeepMockingOfGenerics() { MyClass1 myMock1 = mock(MyClass1.class, RETURNS_DEEP_STUBS); when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World."); } }
@Test public void handlesDodgyXmlDecl() { String xml = "<?xml version='1.0'><val>One</val>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("One", doc.select("val").text()); }
org.jsoup.parser.XmlTreeBuilderTest::handlesDodgyXmlDecl
src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java
228
src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java
handlesDodgyXmlDecl
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.CDataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.nodes.XmlDeclaration; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.List; import static org.jsoup.nodes.Document.OutputSettings.Syntax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests XmlTreeBuilder. * * @author Jonathan Hedley */ public class XmlTreeBuilderTest { @Test public void testSimpleXmlParse() { String xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>", TextUtil.stripNewlines(doc.html())); assertEquals(doc.getElementById("2").absUrl("href"), "http://foo.com/bar"); } @Test public void testPopToClose() { // test: </val> closes Two, </bar> ignored String xml = "<doc><val>One<val>Two</val></bar>Three</doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Test public void testCommentAndDocType() { String xml = "<!DOCTYPE HTML><!-- a comment -->One <qux />Two"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<!DOCTYPE HTML><!-- a comment -->One <qux />Two", TextUtil.stripNewlines(doc.html())); } @Test public void testSupplyParserToJsoupClass() { String xml = "<doc><val>One<val>Two</val></bar>Three</doc>"; Document doc = Jsoup.parse(xml, "http://foo.com/", Parser.xmlParser()); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Ignore @Test public void testSupplyParserToConnection() throws IOException { String xmlUrl = "http://direct.infohound.net/tools/jsoup-xml-test.xml"; // parse with both xml and html parser, ensure different Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get(); Document htmlDoc = Jsoup.connect(xmlUrl).parser(Parser.htmlParser()).get(); Document autoXmlDoc = Jsoup.connect(xmlUrl).get(); // check connection auto detects xml, uses xml parser assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(xmlDoc.html())); assertFalse(htmlDoc.equals(xmlDoc)); assertEquals(xmlDoc, autoXmlDoc); assertEquals(1, htmlDoc.select("head").size()); // html parser normalises assertEquals(0, xmlDoc.select("head").size()); // xml parser does not assertEquals(0, autoXmlDoc.select("head").size()); // xml parser does not } @Test public void testSupplyParserToDataStream() throws IOException, URISyntaxException { File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-test.xml").toURI()); InputStream inStream = new FileInputStream(xmlFile); Document doc = Jsoup.parse(inStream, null, "http://foo.com", Parser.xmlParser()); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Test public void testDoesNotForceSelfClosingKnownTags() { // html will force "<br>one</br>" to logically "<br />One<br />". XML should be stay "<br>one</br> -- don't recognise tag. Document htmlDoc = Jsoup.parse("<br>one</br>"); assertEquals("<br>one\n<br>", htmlDoc.body().html()); Document xmlDoc = Jsoup.parse("<br>one</br>", "", Parser.xmlParser()); assertEquals("<br>one</br>", xmlDoc.html()); } @Test public void handlesXmlDeclarationAsDeclaration() { String html = "<?xml encoding='UTF-8' ?><body>One</body><!-- comment -->"; Document doc = Jsoup.parse(html, "", Parser.xmlParser()); assertEquals("<?xml encoding=\"UTF-8\"?> <body> One </body> <!-- comment -->", StringUtil.normaliseWhitespace(doc.outerHtml())); assertEquals("#declaration", doc.childNode(0).nodeName()); assertEquals("#comment", doc.childNode(2).nodeName()); } @Test public void xmlFragment() { String xml = "<one src='/foo/' />Two<three><four /></three>"; List<Node> nodes = Parser.parseXmlFragment(xml, "http://example.com/"); assertEquals(3, nodes.size()); assertEquals("http://example.com/foo/", nodes.get(0).absUrl("src")); assertEquals("one", nodes.get(0).nodeName()); assertEquals("Two", ((TextNode)nodes.get(1)).text()); } @Test public void xmlParseDefaultsToHtmlOutputSyntax() { Document doc = Jsoup.parse("x", "", Parser.xmlParser()); assertEquals(Syntax.xml, doc.outputSettings().syntax()); } @Test public void testDoesHandleEOFInTag() { String html = "<img src=asdf onerror=\"alert(1)\" x="; Document xmlDoc = Jsoup.parse(html, "", Parser.xmlParser()); assertEquals("<img src=\"asdf\" onerror=\"alert(1)\" x=\"\" />", xmlDoc.html()); } @Test public void testDetectCharsetEncodingDeclaration() throws IOException, URISyntaxException { File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-charset.xml").toURI()); InputStream inStream = new FileInputStream(xmlFile); Document doc = Jsoup.parse(inStream, null, "http://example.com/", Parser.xmlParser()); assertEquals("ISO-8859-1", doc.charset().name()); assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <data>äöåéü</data>", TextUtil.stripNewlines(doc.html())); } @Test public void testParseDeclarationAttributes() { String xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); XmlDeclaration decl = (XmlDeclaration) doc.childNode(0); assertEquals("1", decl.attr("version")); assertEquals("UTF-8", decl.attr("encoding")); assertEquals("else", decl.attr("something")); assertEquals("version=\"1\" encoding=\"UTF-8\" something=\"else\"", decl.getWholeDeclaration()); assertEquals("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.outerHtml()); } @Test public void caseSensitiveDeclaration() { String xml = "<?XML version='1' encoding='UTF-8' something='else'?>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("<?XML version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", doc.outerHtml()); } @Test public void testCreatesValidProlog() { Document document = Document.createShell(""); document.outputSettings().syntax(Syntax.xml); document.charset(Charset.forName("utf-8")); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>", document.outerHtml()); } @Test public void preservesCaseByDefault() { String xml = "<CHECK>One</CHECK><TEST ID=1>Check</TEST>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("<CHECK>One</CHECK><TEST ID=\"1\">Check</TEST>", TextUtil.stripNewlines(doc.html())); } @Test public void canNormalizeCase() { String xml = "<TEST ID=1>Check</TEST>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser().settings(ParseSettings.htmlDefault)); assertEquals("<test id=\"1\">Check</test>", TextUtil.stripNewlines(doc.html())); } @Test public void normalizesDiscordantTags() { Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser); assertEquals("<div>\n test\n</div>\n<p></p>", document.html()); // was failing -> toString() = "<div>\n test\n <p></p>\n</div>" } @Test public void roundTripsCdata() { String xml = "<div id=1><![CDATA[\n<html>\n <foo><&amp;]]></div>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); Element div = doc.getElementById("1"); assertEquals("<html>\n <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node assertEquals("<div id=\"1\"><![CDATA[\n<html>\n <foo><&amp;]]>\n</div>", div.outerHtml()); CDataNode cdata = (CDataNode) div.textNodes().get(0); assertEquals("\n<html>\n <foo><&amp;", cdata.text()); } @Test public void cdataPreservesWhiteSpace() { String xml = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals(xml, doc.outerHtml()); assertEquals("//\n\n foo();\n//", doc.selectFirst("script").text()); } @Test public void handlesDodgyXmlDecl() { String xml = "<?xml version='1.0'><val>One</val>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("One", doc.select("val").text()); } }
// You are a professional Java test case writer, please create a test case named `handlesDodgyXmlDecl` for the issue `Jsoup-1015`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-1015 // // ## Issue-Title: // Faulty Xml Causes IndexOutOfBoundsException // // ## Issue-Description: // // ``` // @Test // public void parseFaultyXml() { // String xml = "<?xml version='1.0'><val>One</val>"; // Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); // } // ``` // // Results in: // // // // ``` // java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 // // at java.util.ArrayList.rangeCheck(ArrayList.java:657) // at java.util.ArrayList.get(ArrayList.java:433) // at org.jsoup.nodes.Element.child(Element.java:254) // at org.jsoup.parser.XmlTreeBuilder.insert(XmlTreeBuilder.java:91) // at org.jsoup.parser.XmlTreeBuilder.process(XmlTreeBuilder.java:49) // at org.jsoup.parser.TreeBuilder.runParser(TreeBuilder.java:52) // at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:45) // at org.jsoup.parser.Parser.parseInput(Parser.java:34) // at org.jsoup.Jsoup.parse(Jsoup.java:45) // // ``` // // // @Test public void handlesDodgyXmlDecl() {
228
80
223
src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-1015 ## Issue-Title: Faulty Xml Causes IndexOutOfBoundsException ## Issue-Description: ``` @Test public void parseFaultyXml() { String xml = "<?xml version='1.0'><val>One</val>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); } ``` Results in: ``` java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:657) at java.util.ArrayList.get(ArrayList.java:433) at org.jsoup.nodes.Element.child(Element.java:254) at org.jsoup.parser.XmlTreeBuilder.insert(XmlTreeBuilder.java:91) at org.jsoup.parser.XmlTreeBuilder.process(XmlTreeBuilder.java:49) at org.jsoup.parser.TreeBuilder.runParser(TreeBuilder.java:52) at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:45) at org.jsoup.parser.Parser.parseInput(Parser.java:34) at org.jsoup.Jsoup.parse(Jsoup.java:45) ``` ``` You are a professional Java test case writer, please create a test case named `handlesDodgyXmlDecl` for the issue `Jsoup-1015`, utilizing the provided issue report information and the following function signature. ```java @Test public void handlesDodgyXmlDecl() { ```
223
[ "org.jsoup.parser.XmlTreeBuilder" ]
3249b6f3eb9e734ac0bdf0884f592724752b381381dd1bad793a1eb108a5315f
@Test public void handlesDodgyXmlDecl()
// You are a professional Java test case writer, please create a test case named `handlesDodgyXmlDecl` for the issue `Jsoup-1015`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-1015 // // ## Issue-Title: // Faulty Xml Causes IndexOutOfBoundsException // // ## Issue-Description: // // ``` // @Test // public void parseFaultyXml() { // String xml = "<?xml version='1.0'><val>One</val>"; // Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); // } // ``` // // Results in: // // // // ``` // java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 // // at java.util.ArrayList.rangeCheck(ArrayList.java:657) // at java.util.ArrayList.get(ArrayList.java:433) // at org.jsoup.nodes.Element.child(Element.java:254) // at org.jsoup.parser.XmlTreeBuilder.insert(XmlTreeBuilder.java:91) // at org.jsoup.parser.XmlTreeBuilder.process(XmlTreeBuilder.java:49) // at org.jsoup.parser.TreeBuilder.runParser(TreeBuilder.java:52) // at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:45) // at org.jsoup.parser.Parser.parseInput(Parser.java:34) // at org.jsoup.Jsoup.parse(Jsoup.java:45) // // ``` // // //
Jsoup
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.CDataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.nodes.XmlDeclaration; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.List; import static org.jsoup.nodes.Document.OutputSettings.Syntax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests XmlTreeBuilder. * * @author Jonathan Hedley */ public class XmlTreeBuilderTest { @Test public void testSimpleXmlParse() { String xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>", TextUtil.stripNewlines(doc.html())); assertEquals(doc.getElementById("2").absUrl("href"), "http://foo.com/bar"); } @Test public void testPopToClose() { // test: </val> closes Two, </bar> ignored String xml = "<doc><val>One<val>Two</val></bar>Three</doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Test public void testCommentAndDocType() { String xml = "<!DOCTYPE HTML><!-- a comment -->One <qux />Two"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<!DOCTYPE HTML><!-- a comment -->One <qux />Two", TextUtil.stripNewlines(doc.html())); } @Test public void testSupplyParserToJsoupClass() { String xml = "<doc><val>One<val>Two</val></bar>Three</doc>"; Document doc = Jsoup.parse(xml, "http://foo.com/", Parser.xmlParser()); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Ignore @Test public void testSupplyParserToConnection() throws IOException { String xmlUrl = "http://direct.infohound.net/tools/jsoup-xml-test.xml"; // parse with both xml and html parser, ensure different Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get(); Document htmlDoc = Jsoup.connect(xmlUrl).parser(Parser.htmlParser()).get(); Document autoXmlDoc = Jsoup.connect(xmlUrl).get(); // check connection auto detects xml, uses xml parser assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(xmlDoc.html())); assertFalse(htmlDoc.equals(xmlDoc)); assertEquals(xmlDoc, autoXmlDoc); assertEquals(1, htmlDoc.select("head").size()); // html parser normalises assertEquals(0, xmlDoc.select("head").size()); // xml parser does not assertEquals(0, autoXmlDoc.select("head").size()); // xml parser does not } @Test public void testSupplyParserToDataStream() throws IOException, URISyntaxException { File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-test.xml").toURI()); InputStream inStream = new FileInputStream(xmlFile); Document doc = Jsoup.parse(inStream, null, "http://foo.com", Parser.xmlParser()); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Test public void testDoesNotForceSelfClosingKnownTags() { // html will force "<br>one</br>" to logically "<br />One<br />". XML should be stay "<br>one</br> -- don't recognise tag. Document htmlDoc = Jsoup.parse("<br>one</br>"); assertEquals("<br>one\n<br>", htmlDoc.body().html()); Document xmlDoc = Jsoup.parse("<br>one</br>", "", Parser.xmlParser()); assertEquals("<br>one</br>", xmlDoc.html()); } @Test public void handlesXmlDeclarationAsDeclaration() { String html = "<?xml encoding='UTF-8' ?><body>One</body><!-- comment -->"; Document doc = Jsoup.parse(html, "", Parser.xmlParser()); assertEquals("<?xml encoding=\"UTF-8\"?> <body> One </body> <!-- comment -->", StringUtil.normaliseWhitespace(doc.outerHtml())); assertEquals("#declaration", doc.childNode(0).nodeName()); assertEquals("#comment", doc.childNode(2).nodeName()); } @Test public void xmlFragment() { String xml = "<one src='/foo/' />Two<three><four /></three>"; List<Node> nodes = Parser.parseXmlFragment(xml, "http://example.com/"); assertEquals(3, nodes.size()); assertEquals("http://example.com/foo/", nodes.get(0).absUrl("src")); assertEquals("one", nodes.get(0).nodeName()); assertEquals("Two", ((TextNode)nodes.get(1)).text()); } @Test public void xmlParseDefaultsToHtmlOutputSyntax() { Document doc = Jsoup.parse("x", "", Parser.xmlParser()); assertEquals(Syntax.xml, doc.outputSettings().syntax()); } @Test public void testDoesHandleEOFInTag() { String html = "<img src=asdf onerror=\"alert(1)\" x="; Document xmlDoc = Jsoup.parse(html, "", Parser.xmlParser()); assertEquals("<img src=\"asdf\" onerror=\"alert(1)\" x=\"\" />", xmlDoc.html()); } @Test public void testDetectCharsetEncodingDeclaration() throws IOException, URISyntaxException { File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-charset.xml").toURI()); InputStream inStream = new FileInputStream(xmlFile); Document doc = Jsoup.parse(inStream, null, "http://example.com/", Parser.xmlParser()); assertEquals("ISO-8859-1", doc.charset().name()); assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <data>äöåéü</data>", TextUtil.stripNewlines(doc.html())); } @Test public void testParseDeclarationAttributes() { String xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); XmlDeclaration decl = (XmlDeclaration) doc.childNode(0); assertEquals("1", decl.attr("version")); assertEquals("UTF-8", decl.attr("encoding")); assertEquals("else", decl.attr("something")); assertEquals("version=\"1\" encoding=\"UTF-8\" something=\"else\"", decl.getWholeDeclaration()); assertEquals("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.outerHtml()); } @Test public void caseSensitiveDeclaration() { String xml = "<?XML version='1' encoding='UTF-8' something='else'?>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("<?XML version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", doc.outerHtml()); } @Test public void testCreatesValidProlog() { Document document = Document.createShell(""); document.outputSettings().syntax(Syntax.xml); document.charset(Charset.forName("utf-8")); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>", document.outerHtml()); } @Test public void preservesCaseByDefault() { String xml = "<CHECK>One</CHECK><TEST ID=1>Check</TEST>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("<CHECK>One</CHECK><TEST ID=\"1\">Check</TEST>", TextUtil.stripNewlines(doc.html())); } @Test public void canNormalizeCase() { String xml = "<TEST ID=1>Check</TEST>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser().settings(ParseSettings.htmlDefault)); assertEquals("<test id=\"1\">Check</test>", TextUtil.stripNewlines(doc.html())); } @Test public void normalizesDiscordantTags() { Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser); assertEquals("<div>\n test\n</div>\n<p></p>", document.html()); // was failing -> toString() = "<div>\n test\n <p></p>\n</div>" } @Test public void roundTripsCdata() { String xml = "<div id=1><![CDATA[\n<html>\n <foo><&amp;]]></div>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); Element div = doc.getElementById("1"); assertEquals("<html>\n <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node assertEquals("<div id=\"1\"><![CDATA[\n<html>\n <foo><&amp;]]>\n</div>", div.outerHtml()); CDataNode cdata = (CDataNode) div.textNodes().get(0); assertEquals("\n<html>\n <foo><&amp;", cdata.text()); } @Test public void cdataPreservesWhiteSpace() { String xml = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals(xml, doc.outerHtml()); assertEquals("//\n\n foo();\n//", doc.selectFirst("script").text()); } @Test public void handlesDodgyXmlDecl() { String xml = "<?xml version='1.0'><val>One</val>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("One", doc.select("val").text()); } }
@Test public void shouldDealWithNestedGenerics() throws Exception { assertEquals(Set.class, m.getGenericType(field("nested"))); assertEquals(Set.class, m.getGenericType(field("multiNested"))); }
org.mockito.internal.util.reflection.GenericMasterTest::shouldDealWithNestedGenerics
test/org/mockito/internal/util/reflection/GenericMasterTest.java
39
test/org/mockito/internal/util/reflection/GenericMasterTest.java
shouldDealWithNestedGenerics
package org.mockito.internal.util.reflection; import static org.junit.Assert.*; import java.lang.reflect.Field; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; public class GenericMasterTest { GenericMaster m = new GenericMaster(); List<String> one; Set<Integer> two; Map<Double, String> map; String nonGeneric; List<Set<String>> nested; List<Set<Collection<String>>> multiNested; @Test public void shouldFindGenericClass() throws Exception { assertEquals(String.class, m.getGenericType(field("one"))); assertEquals(Integer.class, m.getGenericType(field("two"))); assertEquals(Double.class, m.getGenericType(field("map"))); } @Test public void shouldGetObjectForNonGeneric() throws Exception { assertEquals(Object.class, m.getGenericType(field("nonGeneric"))); } @Test public void shouldDealWithNestedGenerics() throws Exception { assertEquals(Set.class, m.getGenericType(field("nested"))); assertEquals(Set.class, m.getGenericType(field("multiNested"))); } private Field field(String fieldName) throws SecurityException, NoSuchFieldException { return this.getClass().getDeclaredField(fieldName); } }
// You are a professional Java test case writer, please create a test case named `shouldDealWithNestedGenerics` for the issue `Mockito-188`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-188 // // ## Issue-Title: // ArgumentCaptor no longer working for varargs // // ## Issue-Description: // I ran into the issue described here: <http://stackoverflow.com/questions/27303562/why-does-upgrading-mockito-from-1-9-5-to-1-10-8-break-this-captor> // // // // @Test public void shouldDealWithNestedGenerics() throws Exception {
39
12
35
test/org/mockito/internal/util/reflection/GenericMasterTest.java
test
```markdown ## Issue-ID: Mockito-188 ## Issue-Title: ArgumentCaptor no longer working for varargs ## Issue-Description: I ran into the issue described here: <http://stackoverflow.com/questions/27303562/why-does-upgrading-mockito-from-1-9-5-to-1-10-8-break-this-captor> ``` You are a professional Java test case writer, please create a test case named `shouldDealWithNestedGenerics` for the issue `Mockito-188`, utilizing the provided issue report information and the following function signature. ```java @Test public void shouldDealWithNestedGenerics() throws Exception { ```
35
[ "org.mockito.internal.util.reflection.GenericMaster" ]
32dbc6836b7de0e1d86e5a86954e713eea25c946a7d8c7f85afb875b1363a171
@Test public void shouldDealWithNestedGenerics() throws Exception
// You are a professional Java test case writer, please create a test case named `shouldDealWithNestedGenerics` for the issue `Mockito-188`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-188 // // ## Issue-Title: // ArgumentCaptor no longer working for varargs // // ## Issue-Description: // I ran into the issue described here: <http://stackoverflow.com/questions/27303562/why-does-upgrading-mockito-from-1-9-5-to-1-10-8-break-this-captor> // // // //
Mockito
package org.mockito.internal.util.reflection; import static org.junit.Assert.*; import java.lang.reflect.Field; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; public class GenericMasterTest { GenericMaster m = new GenericMaster(); List<String> one; Set<Integer> two; Map<Double, String> map; String nonGeneric; List<Set<String>> nested; List<Set<Collection<String>>> multiNested; @Test public void shouldFindGenericClass() throws Exception { assertEquals(String.class, m.getGenericType(field("one"))); assertEquals(Integer.class, m.getGenericType(field("two"))); assertEquals(Double.class, m.getGenericType(field("map"))); } @Test public void shouldGetObjectForNonGeneric() throws Exception { assertEquals(Object.class, m.getGenericType(field("nonGeneric"))); } @Test public void shouldDealWithNestedGenerics() throws Exception { assertEquals(Set.class, m.getGenericType(field("nested"))); assertEquals(Set.class, m.getGenericType(field("multiNested"))); } private Field field(String fieldName) throws SecurityException, NoSuchFieldException { return this.getClass().getDeclaredField(fieldName); } }
public void testIssue1024() throws Exception { testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = '__proto'\n" + "}\n" + "/** @param {Object} b\n" + " * @return {!Object}\n" + " */\n" + "function g(b) {\n" + " return b.prototype\n" + "}\n"); /* TODO(blickly): Make this warning go away. * This is old behavior, but it doesn't make sense to warn about since * both assignments are inferred. */ testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = {foo:3};\n" + "}\n" + "/** @param {Object} b\n" + " */\n" + "function g(b) {\n" + " b.prototype = function(){};\n" + "}\n", "assignment to property prototype of Object\n" + "found : {foo: number}\n" + "required: function (): undefined"); }
com.google.javascript.jscomp.TypeCheckTest::testIssue1024
test/com/google/javascript/jscomp/TypeCheckTest.java
12,020
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue1024
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testGoodExtends18() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor\n" + " * @template T */\n" + "function C() {}\n" + "/** @constructor\n" + " * @extends {C.<string>} */\n" + "function D() {};\n" + "goog.inherits(D, C);\n" + "(new D())"); } public void testGoodExtends19() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */\n" + "function C() {}\n" + "" + "/** @interface\n" + " * @template T */\n" + "function D() {}\n" + "/** @param {T} t */\n" + "D.prototype.method;\n" + "" + "/** @constructor\n" + " * @template T\n" + " * @extends {C}\n" + " * @implements {D.<T>} */\n" + "function E() {};\n" + "goog.inherits(E, C);\n" + "/** @override */\n" + "E.prototype.method = function(t) {};\n" + "" + "var e = /** @type {E.<string>} */ (new E());\n" + "e.method(3);", "actual parameter 1 of E.prototype.method does not match formal " + "parameter\n" + "found : number\n" + "required: string"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar())['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } public void testIssue1023() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "(function () {" + " F.prototype = {" + " /** @param {string} x */" + " bar: function (x) { }" + " };" + "})();" + "(new F()).bar(true)", "actual parameter 1 of F.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testEnums() throws Exception { testTypes( "var outer = function() {" + " /** @enum {number} */" + " var Level = {" + " NONE: 0," + " };" + " /** @type {!Level} */" + " var l = Level.NONE;" + "}"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};" + "" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {A}\n" + " */\n" + "var B = function() { this.bar = function(){}; };" + "" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype2() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " this.x = 123;\n" + "}\n" + "var objlit = /** @struct */ { y: 234 };\n" + "Foo.prototype = objlit;\n" + "var n = objlit.x;\n", "Property x never defined on Foo.prototype", false); } public void testIssue1024() throws Exception { testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = '__proto'\n" + "}\n" + "/** @param {Object} b\n" + " * @return {!Object}\n" + " */\n" + "function g(b) {\n" + " return b.prototype\n" + "}\n"); /* TODO(blickly): Make this warning go away. * This is old behavior, but it doesn't make sense to warn about since * both assignments are inferred. */ testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = {foo:3};\n" + "}\n" + "/** @param {Object} b\n" + " */\n" + "function g(b) {\n" + " b.prototype = function(){};\n" + "}\n", "assignment to property prototype of Object\n" + "found : {foo: number}\n" + "required: function (): undefined"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testIssue1024` for the issue `Closure-1042`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1042 // // ## Issue-Title: // Type of prototype property incorrectly inferred to string // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile the following code: // // /\*\* @param {Object} a \*/ // function f(a) { // a.prototype = '\_\_proto'; // } // // /\*\* @param {Object} a \*/ // function g(a) { // a.prototype = function(){}; // } // // **What is the expected output? What do you see instead?** // // Should type check. Instead, gives error: // // WARNING - assignment to property prototype of Object // found : function (): undefined // required: string // a.prototype = function(){}; // ^ // // public void testIssue1024() throws Exception {
12,020
172
11,991
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-1042 ## Issue-Title: Type of prototype property incorrectly inferred to string ## Issue-Description: **What steps will reproduce the problem?** 1. Compile the following code: /\*\* @param {Object} a \*/ function f(a) { a.prototype = '\_\_proto'; } /\*\* @param {Object} a \*/ function g(a) { a.prototype = function(){}; } **What is the expected output? What do you see instead?** Should type check. Instead, gives error: WARNING - assignment to property prototype of Object found : function (): undefined required: string a.prototype = function(){}; ^ ``` You are a professional Java test case writer, please create a test case named `testIssue1024` for the issue `Closure-1042`, utilizing the provided issue report information and the following function signature. ```java public void testIssue1024() throws Exception { ```
11,991
[ "com.google.javascript.jscomp.TypedScopeCreator" ]
33160e7ccb5e2fd8f543cba3ad9b7dc46f121fb1f5fa65006325c7262373aa8d
public void testIssue1024() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue1024` for the issue `Closure-1042`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1042 // // ## Issue-Title: // Type of prototype property incorrectly inferred to string // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile the following code: // // /\*\* @param {Object} a \*/ // function f(a) { // a.prototype = '\_\_proto'; // } // // /\*\* @param {Object} a \*/ // function g(a) { // a.prototype = function(){}; // } // // **What is the expected output? What do you see instead?** // // Should type check. Instead, gives error: // // WARNING - assignment to property prototype of Object // found : function (): undefined // required: string // a.prototype = function(){}; // ^ // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testGoodExtends18() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor\n" + " * @template T */\n" + "function C() {}\n" + "/** @constructor\n" + " * @extends {C.<string>} */\n" + "function D() {};\n" + "goog.inherits(D, C);\n" + "(new D())"); } public void testGoodExtends19() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */\n" + "function C() {}\n" + "" + "/** @interface\n" + " * @template T */\n" + "function D() {}\n" + "/** @param {T} t */\n" + "D.prototype.method;\n" + "" + "/** @constructor\n" + " * @template T\n" + " * @extends {C}\n" + " * @implements {D.<T>} */\n" + "function E() {};\n" + "goog.inherits(E, C);\n" + "/** @override */\n" + "E.prototype.method = function(t) {};\n" + "" + "var e = /** @type {E.<string>} */ (new E());\n" + "e.method(3);", "actual parameter 1 of E.prototype.method does not match formal " + "parameter\n" + "found : number\n" + "required: string"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar())['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } public void testIssue1023() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "(function () {" + " F.prototype = {" + " /** @param {string} x */" + " bar: function (x) { }" + " };" + "})();" + "(new F()).bar(true)", "actual parameter 1 of F.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testEnums() throws Exception { testTypes( "var outer = function() {" + " /** @enum {number} */" + " var Level = {" + " NONE: 0," + " };" + " /** @type {!Level} */" + " var l = Level.NONE;" + "}"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};" + "" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {A}\n" + " */\n" + "var B = function() { this.bar = function(){}; };" + "" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype2() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " this.x = 123;\n" + "}\n" + "var objlit = /** @struct */ { y: 234 };\n" + "Foo.prototype = objlit;\n" + "var n = objlit.x;\n", "Property x never defined on Foo.prototype", false); } public void testIssue1024() throws Exception { testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = '__proto'\n" + "}\n" + "/** @param {Object} b\n" + " * @return {!Object}\n" + " */\n" + "function g(b) {\n" + " return b.prototype\n" + "}\n"); /* TODO(blickly): Make this warning go away. * This is old behavior, but it doesn't make sense to warn about since * both assignments are inferred. */ testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = {foo:3};\n" + "}\n" + "/** @param {Object} b\n" + " */\n" + "function g(b) {\n" + " b.prototype = function(){};\n" + "}\n", "assignment to property prototype of Object\n" + "found : {foo: number}\n" + "required: function (): undefined"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
public void testIsSameLocalTime_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(true, DateUtils.isSameLocalTime(cal1, cal2)); Calendar cal3 = Calendar.getInstance(); Calendar cal4 = Calendar.getInstance(); cal3.set(2004, 6, 9, 4, 0, 0); cal4.set(2004, 6, 9, 16, 0, 0); cal3.set(Calendar.MILLISECOND, 0); cal4.set(Calendar.MILLISECOND, 0); assertFalse("LANG-677", DateUtils.isSameLocalTime(cal3, cal4)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(false, DateUtils.isSameLocalTime(cal1, cal2)); try { DateUtils.isSameLocalTime((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} }
org.apache.commons.lang3.time.DateUtilsTest::testIsSameLocalTime_Cal
src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
244
src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
testIsSameLocalTime_Cal
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import static org.apache.commons.lang3.JavaVersion.*; import org.apache.commons.lang3.SystemUtils; /** * Unit tests {@link org.apache.commons.lang3.time.DateUtils}. * * @author <a href="mailto:sergek@lokitech.com">Serge Knystautas</a> * @author <a href="mailto:steve@mungoknotwise.com">Steven Caswell</a> */ public class DateUtilsTest extends TestCase { private static final long MILLIS_TEST; static { GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2); cal.set(Calendar.MILLISECOND, 1); MILLIS_TEST = cal.getTime().getTime(); } DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null; public DateUtilsTest(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); dateParser = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH); dateAmPm1 = dateTimeParser.parse("February 3, 2002 01:10:00.000"); dateAmPm2 = dateTimeParser.parse("February 3, 2002 11:10:00.000"); dateAmPm3 = dateTimeParser.parse("February 3, 2002 13:10:00.000"); dateAmPm4 = dateTimeParser.parse("February 3, 2002 19:10:00.000"); date0 = dateTimeParser.parse("February 3, 2002 12:34:56.789"); date1 = dateTimeParser.parse("February 12, 2002 12:34:56.789"); date2 = dateTimeParser.parse("November 18, 2001 1:23:11.321"); defaultZone = TimeZone.getDefault(); zone = TimeZone.getTimeZone("MET"); TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); date3 = dateTimeParser.parse("March 30, 2003 05:30:45.000"); date4 = dateTimeParser.parse("March 30, 2003 01:10:00.000"); date5 = dateTimeParser.parse("March 30, 2003 01:40:00.000"); date6 = dateTimeParser.parse("March 30, 2003 02:10:00.000"); date7 = dateTimeParser.parse("March 30, 2003 02:40:00.000"); date8 = dateTimeParser.parse("October 26, 2003 05:30:45.000"); dateTimeParser.setTimeZone(defaultZone); TimeZone.setDefault(defaultZone); calAmPm1 = Calendar.getInstance(); calAmPm1.setTime(dateAmPm1); calAmPm2 = Calendar.getInstance(); calAmPm2.setTime(dateAmPm2); calAmPm3 = Calendar.getInstance(); calAmPm3.setTime(dateAmPm3); calAmPm4 = Calendar.getInstance(); calAmPm4.setTime(dateAmPm4); cal1 = Calendar.getInstance(); cal1.setTime(date1); cal2 = Calendar.getInstance(); cal2.setTime(date2); TimeZone.setDefault(zone); cal3 = Calendar.getInstance(); cal3.setTime(date3); cal4 = Calendar.getInstance(); cal4.setTime(date4); cal5 = Calendar.getInstance(); cal5.setTime(date5); cal6 = Calendar.getInstance(); cal6.setTime(date6); cal7 = Calendar.getInstance(); cal7.setTime(date7); cal8 = Calendar.getInstance(); cal8.setTime(date8); TimeZone.setDefault(defaultZone); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new DateUtils()); Constructor<?>[] cons = DateUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(DateUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(DateUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testIsSameDay_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); try { DateUtils.isSameDay((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameDay_Cal() { GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45); GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.DAY_OF_YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); cal1.add(Calendar.DAY_OF_YEAR, 1); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); try { DateUtils.isSameDay((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); try { DateUtils.isSameInstant((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(false, DateUtils.isSameInstant(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(true, DateUtils.isSameInstant(cal1, cal2)); try { DateUtils.isSameInstant((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameLocalTime_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(true, DateUtils.isSameLocalTime(cal1, cal2)); Calendar cal3 = Calendar.getInstance(); Calendar cal4 = Calendar.getInstance(); cal3.set(2004, 6, 9, 4, 0, 0); cal4.set(2004, 6, 9, 16, 0, 0); cal3.set(Calendar.MILLISECOND, 0); cal4.set(Calendar.MILLISECOND, 0); assertFalse("LANG-677", DateUtils.isSameLocalTime(cal3, cal4)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(false, DateUtils.isSameLocalTime(cal1, cal2)); try { DateUtils.isSameLocalTime((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseDate() throws Exception { GregorianCalendar cal = new GregorianCalendar(1972, 11, 3); String dateStr = "1972-12-03"; String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "1972-338"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "19721203"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { DateUtils.parseDate("PURPLE", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate("197212AB", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate(null, parsers); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, (String[]) null); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, new String[0]); fail(); } catch (ParseException ex) {} } // LANG-486 public void testParseDateWithLeniency() throws Exception { GregorianCalendar cal = new GregorianCalendar(1998, 6, 30); String dateStr = "02 942, 1996"; String[] parsers = new String[] {"MM DDD, yyyy"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { date = DateUtils.parseDateStrictly(dateStr, parsers); fail(); } catch (ParseException ex) {} } //----------------------------------------------------------------------- public void testAddYears() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addYears(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2001, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 1999, 6, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMonths() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMonths(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMonths(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 7, 5, 4, 3, 2, 1); result = DateUtils.addMonths(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 5, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddWeeks() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addWeeks(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addWeeks(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 12, 4, 3, 2, 1); result = DateUtils.addWeeks(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // july assertDate(result, 2000, 5, 28, 4, 3, 2, 1); // june } //----------------------------------------------------------------------- public void testAddDays() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addDays(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 6, 4, 3, 2, 1); result = DateUtils.addDays(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 4, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddHours() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addHours(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 5, 3, 2, 1); result = DateUtils.addHours(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 3, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMinutes() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMinutes(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 4, 2, 1); result = DateUtils.addMinutes(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 2, 2, 1); } //----------------------------------------------------------------------- public void testAddSeconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addSeconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 3, 1); result = DateUtils.addSeconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 1, 1); } //----------------------------------------------------------------------- public void testAddMilliseconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMilliseconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMilliseconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 2); result = DateUtils.addMilliseconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 0); } // ----------------------------------------------------------------------- public void testSetYears() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setYears(base, 2000); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.setYears(base, 2008); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2008, 6, 5, 4, 3, 2, 1); result = DateUtils.setYears(base, 2005); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2005, 6, 5, 4, 3, 2, 1); } // ----------------------------------------------------------------------- public void testSetMonths() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMonths(base, 5); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 5, 5, 4, 3, 2, 1); result = DateUtils.setMonths(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 1, 5, 4, 3, 2, 1); try { result = DateUtils.setMonths(base, 12); fail("DateUtils.setMonths did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetDays() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 1, 4, 3, 2, 1); result = DateUtils.setDays(base, 29); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 29, 4, 3, 2, 1); try { result = DateUtils.setDays(base, 32); fail("DateUtils.setDays did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetHours() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 0, 3, 2, 1); result = DateUtils.setHours(base, 23); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 23, 3, 2, 1); try { result = DateUtils.setHours(base, 24); fail("DateUtils.setHours did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetMinutes() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 0, 2, 1); result = DateUtils.setMinutes(base, 59); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 59, 2, 1); try { result = DateUtils.setMinutes(base, 60); fail("DateUtils.setMinutes did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetSeconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 0, 1); result = DateUtils.setSeconds(base, 59); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 59, 1); try { result = DateUtils.setSeconds(base, 60); fail("DateUtils.setSeconds did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetMilliseconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMilliseconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 0); result = DateUtils.setMilliseconds(base, 999); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 999); try { result = DateUtils.setMilliseconds(base, 1000); fail("DateUtils.setMilliseconds did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- private void assertDate(Date date, int year, int month, int day, int hour, int min, int sec, int mil) throws Exception { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); assertEquals(year, cal.get(Calendar.YEAR)); assertEquals(month, cal.get(Calendar.MONTH)); assertEquals(day, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(min, cal.get(Calendar.MINUTE)); assertEquals(sec, cal.get(Calendar.SECOND)); assertEquals(mil, cal.get(Calendar.MILLISECOND)); } //----------------------------------------------------------------------- public void testToCalendar() { assertEquals("Failed to convert to a Calendar and back", date1, DateUtils.toCalendar(date1).getTime()); try { DateUtils.toCalendar(null); fail("Expected NullPointerException to be thrown"); } catch(NullPointerException npe) { // expected } } //----------------------------------------------------------------------- /** * Tests various values with the round method */ public void testRound() throws Exception { // tests for public static Date round(Date date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round(date2, Calendar.MONTH)); assertEquals("round semimonth-0 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date0, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round(date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round(date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round(date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round(date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round(date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round(date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round(date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round(date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round(date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round(date2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round(dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round(dateAmPm4, Calendar.AM_PM)); // tests for public static Date round(Object date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round((Object) date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round((Object) date2, Calendar.MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round((Object) date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round((Object) date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round((Object) date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round((Object) date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round((Object) date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round((Object) date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) date2, Calendar.SECOND)); assertEquals("round calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) cal1, Calendar.SECOND)); assertEquals("round calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) cal2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm4, Calendar.AM_PM)); try { DateUtils.round((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} try { DateUtils.round(date1, -9999); fail(); } catch(IllegalArgumentException ex) {} assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm4, Calendar.AM_PM)); // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 / LANG-13 // Test rounding across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round(date4, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round(date7, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date rounding tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); } /** * Tests the Changes Made by LANG-346 to the DateUtils.modify() private method invoked * by DateUtils.round(). */ public void testRoundLang346() throws Exception { TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); Calendar testCalendar = Calendar.getInstance(); testCalendar.set(2007, 6, 2, 8, 8, 50); Date date = testCalendar.getTime(); assertEquals("Minute Round Up Failed", dateTimeParser.parse("July 2, 2007 08:09:00.000"), DateUtils.round(date, Calendar.MINUTE)); testCalendar.set(2007, 6, 2, 8, 8, 20); date = testCalendar.getTime(); assertEquals("Minute No Round Failed", dateTimeParser.parse("July 2, 2007 08:08:00.000"), DateUtils.round(date, Calendar.MINUTE)); testCalendar.set(2007, 6, 2, 8, 8, 50); testCalendar.set(Calendar.MILLISECOND, 600); date = testCalendar.getTime(); assertEquals("Second Round Up with 600 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:51.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 50); testCalendar.set(Calendar.MILLISECOND, 200); date = testCalendar.getTime(); assertEquals("Second Round Down with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:50.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 20); testCalendar.set(Calendar.MILLISECOND, 600); date = testCalendar.getTime(); assertEquals("Second Round Up with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:21.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 20); testCalendar.set(Calendar.MILLISECOND, 200); date = testCalendar.getTime(); assertEquals("Second Round Down with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:20.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 50); date = testCalendar.getTime(); assertEquals("Hour Round Down Failed", dateTimeParser.parse("July 2, 2007 08:00:00.000"), DateUtils.round(date, Calendar.HOUR)); testCalendar.set(2007, 6, 2, 8, 31, 50); date = testCalendar.getTime(); assertEquals("Hour Round Up Failed", dateTimeParser.parse("July 2, 2007 09:00:00.000"), DateUtils.round(date, Calendar.HOUR)); } /** * Tests various values with the trunc method */ public void testTruncate() throws Exception { // tests public static Date truncate(Date date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate(date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate(date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate(date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate(date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate(date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate(date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate(date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate(date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate(date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate(date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate(date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate(date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm4, Calendar.AM_PM)); // tests public static Date truncate(Object date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate((Object) date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate((Object) date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate((Object) date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate((Object) date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate((Object) date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate((Object) date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate((Object) date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate((Object) date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate((Object) date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("truncate calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) cal1, Calendar.SECOND)); assertEquals("truncate calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) cal2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.truncate((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test truncate across beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate(date3, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate((Object) cal3, Calendar.DATE)); // Test truncate across end of daylight saving time assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate(date8, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate((Object) cal8, Calendar.DATE)); TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); Calendar cal = DateUtils.truncate(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests for LANG-59 * * see http://issues.apache.org/jira/browse/LANG-59 */ public void testTruncateLang59() throws Exception { if (!SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { this.warn("WARNING: Test for LANG-59 not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); return; } // Set TimeZone to Mountain Time TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT"); TimeZone.setDefault(MST_MDT); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); format.setTimeZone(MST_MDT); Date oct31_01MDT = new Date(1099206000000L); Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT)); assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT)); assertEquals("Check 01:02:00.000", "2004-10-31 01:02:00.000 MDT", format.format(oct31_01_02MDT)); assertEquals("Check 01:02:03.000", "2004-10-31 01:02:03.000 MDT", format.format(oct31_01_02_03MDT)); assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT)); // ------- Demonstrate Problem ------- Calendar gval = Calendar.getInstance(); gval.setTime(new Date(oct31_01MDT.getTime())); gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L); // ---------- Test Truncate ---------- assertEquals("Truncate Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Truncate Calendar.SECOND", oct31_01_02_03MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Truncate Calendar.MINUTE", oct31_01_02MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Truncate Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Truncate Calendar.HOUR", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Truncate Calendar.DATE", oct31MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.DATE)); // ---------- Test Round (down) ---------- assertEquals("Round Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Round Calendar.SECOND", oct31_01_02_03MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Round Calendar.MINUTE", oct31_01_02MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Round Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Round Calendar.HOUR", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Round Calendar.DATE", oct31MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.DATE)); // restore default time zone TimeZone.setDefault(defaultZone); } // http://issues.apache.org/jira/browse/LANG-530 public void testLang530() throws ParseException { Date d = new Date(); String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d); Date d2 = DateUtils.parseDate(isoDateStr, new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() }); // the format loses milliseconds so have to reintroduce them assertEquals("Date not equal to itself ISO formatted and parsed", d.getTime(), d2.getTime() + d.getTime() % 1000); } /** * Tests various values with the ceiling method */ public void testCeil() throws Exception { // test javadoc assertEquals("ceiling javadoc-1 failed", dateTimeParser.parse("March 28, 2002 14:00:00.000"), DateUtils.ceiling( dateTimeParser.parse("March 28, 2002 13:45:01.231"), Calendar.HOUR)); assertEquals("ceiling javadoc-2 failed", dateTimeParser.parse("April 1, 2002 00:00:00.000"), DateUtils.ceiling( dateTimeParser.parse("March 28, 2002 13:45:01.231"), Calendar.MONTH)); // tests public static Date ceiling(Date date, int field) assertEquals("ceiling year-1 failed", dateParser.parse("January 1, 2003"), DateUtils.ceiling(date1, Calendar.YEAR)); assertEquals("ceiling year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.ceiling(date2, Calendar.YEAR)); assertEquals("ceiling month-1 failed", dateParser.parse("March 1, 2002"), DateUtils.ceiling(date1, Calendar.MONTH)); assertEquals("ceiling month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling(date2, Calendar.MONTH)); assertEquals("ceiling semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.ceiling(date1, DateUtils.SEMI_MONTH)); assertEquals("ceiling semimonth-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling(date2, DateUtils.SEMI_MONTH)); assertEquals("ceiling date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.ceiling(date1, Calendar.DATE)); assertEquals("ceiling date-2 failed", dateParser.parse("November 19, 2001"), DateUtils.ceiling(date2, Calendar.DATE)); assertEquals("ceiling hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.ceiling(date1, Calendar.HOUR)); assertEquals("ceiling hour-2 failed", dateTimeParser.parse("November 18, 2001 2:00:00.000"), DateUtils.ceiling(date2, Calendar.HOUR)); assertEquals("ceiling minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.ceiling(date1, Calendar.MINUTE)); assertEquals("ceiling minute-2 failed", dateTimeParser.parse("November 18, 2001 1:24:00.000"), DateUtils.ceiling(date2, Calendar.MINUTE)); assertEquals("ceiling second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling(date1, Calendar.SECOND)); assertEquals("ceiling second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling(date2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling(dateAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling(dateAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling(dateAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling(dateAmPm4, Calendar.AM_PM)); // tests public static Date ceiling(Object date, int field) assertEquals("ceiling year-1 failed", dateParser.parse("January 1, 2003"), DateUtils.ceiling((Object) date1, Calendar.YEAR)); assertEquals("ceiling year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.ceiling((Object) date2, Calendar.YEAR)); assertEquals("ceiling month-1 failed", dateParser.parse("March 1, 2002"), DateUtils.ceiling((Object) date1, Calendar.MONTH)); assertEquals("ceiling month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling((Object) date2, Calendar.MONTH)); assertEquals("ceiling semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.ceiling((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("ceiling semimonth-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("ceiling date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.ceiling((Object) date1, Calendar.DATE)); assertEquals("ceiling date-2 failed", dateParser.parse("November 19, 2001"), DateUtils.ceiling((Object) date2, Calendar.DATE)); assertEquals("ceiling hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.ceiling((Object) date1, Calendar.HOUR)); assertEquals("ceiling hour-2 failed", dateTimeParser.parse("November 18, 2001 2:00:00.000"), DateUtils.ceiling((Object) date2, Calendar.HOUR)); assertEquals("ceiling minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.ceiling((Object) date1, Calendar.MINUTE)); assertEquals("ceiling minute-2 failed", dateTimeParser.parse("November 18, 2001 1:24:00.000"), DateUtils.ceiling((Object) date2, Calendar.MINUTE)); assertEquals("ceiling second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling((Object) date1, Calendar.SECOND)); assertEquals("ceiling second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling((Object) date2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("ceiling calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling((Object) cal1, Calendar.SECOND)); assertEquals("ceiling calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling((Object) cal2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) calAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) calAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) calAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.ceiling((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} try { DateUtils.ceiling(date1, -9999); fail(); } catch(IllegalArgumentException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test ceiling across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date4, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal4, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date5, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal5, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date6, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal6, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date7, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal7, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling(date4, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling(date5, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling(date6, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling(date7, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date ceiling tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.ceiling(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.ceiling(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests the iterator exceptions */ public void testIteratorEx() throws Exception { try { DateUtils.iterator(Calendar.getInstance(), -9999); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER); fail(); } catch (ClassCastException ex) {} } /** * Tests the calendar iterator for week ranges */ public void testWeekIterator() throws Exception { Calendar now = Calendar.getInstance(); for (int i = 0; i< 7; i++) { Calendar today = DateUtils.truncate(now, Calendar.DATE); Calendar sunday = DateUtils.truncate(now, Calendar.DATE); sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK)); Calendar monday = DateUtils.truncate(now, Calendar.DATE); if (monday.get(Calendar.DAY_OF_WEEK) == 1) { //This is sunday... roll back 6 days monday.add(Calendar.DATE, -6); } else { monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK)); } Calendar centered = DateUtils.truncate(now, Calendar.DATE); centered.add(Calendar.DATE, -3); Iterator<?> it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_SUNDAY); assertWeekIterator(it, sunday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_MONDAY); assertWeekIterator(it, monday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_RELATIVE); assertWeekIterator(it, today); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); try { it.next(); fail(); } catch (NoSuchElementException ex) {} it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); it.next(); try { it.remove(); } catch( UnsupportedOperationException ex) {} now.add(Calendar.DATE,1); } } /** * Tests the calendar iterator for month-based ranges */ public void testMonthIterator() throws Exception { Iterator<?> it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("January 27, 2002"), dateParser.parse("March 2, 2002")); it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("January 28, 2002"), dateParser.parse("March 3, 2002")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("October 28, 2001"), dateParser.parse("December 1, 2001")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("October 29, 2001"), dateParser.parse("December 2, 2001")); } /** * This checks that this is a 7 element iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other. */ private static void assertWeekIterator(Iterator<?> it, Calendar start) { Calendar end = (Calendar) start.clone(); end.add(Calendar.DATE, 6); assertWeekIterator(it, start, end); } /** * Convenience method for when working with Date objects */ private static void assertWeekIterator(Iterator<?> it, Date start, Date end) { Calendar calStart = Calendar.getInstance(); calStart.setTime(start); Calendar calEnd = Calendar.getInstance(); calEnd.setTime(end); assertWeekIterator(it, calStart, calEnd); } /** * This checks that this is a 7 divisble iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other * (in addition to the proper start and stop dates) */ private static void assertWeekIterator(Iterator<?> it, Calendar start, Calendar end) { Calendar cal = (Calendar) it.next(); assertEquals("", start, cal, 0); Calendar last = null; int count = 1; while (it.hasNext()) { //Check this is just a date (no time component) assertEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0); last = cal; cal = (Calendar) it.next(); count++; //Check that this is one day more than the last date last.add(Calendar.DATE, 1); assertEquals("", last, cal, 0); } if (count % 7 != 0) { throw new AssertionFailedError("There were " + count + " days in this iterator"); } assertEquals("", end, cal, 0); } /** * Used to check that Calendar objects are close enough * delta is in milliseconds */ private static void assertEquals(String message, Calendar cal1, Calendar cal2, long delta) { if (Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta) { throw new AssertionFailedError( message + " expected " + cal1.getTime() + " but got " + cal2.getTime()); } } void warn(String msg) { System.err.println(msg); } }
// You are a professional Java test case writer, please create a test case named `testIsSameLocalTime_Cal` for the issue `Lang-LANG-677`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-677 // // ## Issue-Title: // DateUtils.isSameLocalTime does not work correct // // ## Issue-Description: // // Hi, I think I found a bug in the DateUtils class in the method isSameLocalTime. // // // Example: // // Calendar a = Calendar.getInstance(); // // a.setTimeInMillis(1297364400000L); // // // Calendar b = Calendar.getInstance(); // // b.setTimeInMillis(1297321200000L); // // // Assert.assertFalse(DateUtils.isSameLocalTime(a, b)); // // // This is because the method compares // // cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) // // // but I think it has to be // // cal1.get(Calendar.HOUR\_OF\_DAY) == cal2.get(Calendar.HOUR\_OF\_DAY) // // // // // public void testIsSameLocalTime_Cal() {
244
//-----------------------------------------------------------------------
21
221
src/test/java/org/apache/commons/lang3/time/DateUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-677 ## Issue-Title: DateUtils.isSameLocalTime does not work correct ## Issue-Description: Hi, I think I found a bug in the DateUtils class in the method isSameLocalTime. Example: Calendar a = Calendar.getInstance(); a.setTimeInMillis(1297364400000L); Calendar b = Calendar.getInstance(); b.setTimeInMillis(1297321200000L); Assert.assertFalse(DateUtils.isSameLocalTime(a, b)); This is because the method compares cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) but I think it has to be cal1.get(Calendar.HOUR\_OF\_DAY) == cal2.get(Calendar.HOUR\_OF\_DAY) ``` You are a professional Java test case writer, please create a test case named `testIsSameLocalTime_Cal` for the issue `Lang-LANG-677`, utilizing the provided issue report information and the following function signature. ```java public void testIsSameLocalTime_Cal() { ```
221
[ "org.apache.commons.lang3.time.DateUtils" ]
335c4ab1bf42d5808e6173fe45acac4b9ddff34c7fa98f7c16109594fe493046
public void testIsSameLocalTime_Cal()
// You are a professional Java test case writer, please create a test case named `testIsSameLocalTime_Cal` for the issue `Lang-LANG-677`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-677 // // ## Issue-Title: // DateUtils.isSameLocalTime does not work correct // // ## Issue-Description: // // Hi, I think I found a bug in the DateUtils class in the method isSameLocalTime. // // // Example: // // Calendar a = Calendar.getInstance(); // // a.setTimeInMillis(1297364400000L); // // // Calendar b = Calendar.getInstance(); // // b.setTimeInMillis(1297321200000L); // // // Assert.assertFalse(DateUtils.isSameLocalTime(a, b)); // // // This is because the method compares // // cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) // // // but I think it has to be // // cal1.get(Calendar.HOUR\_OF\_DAY) == cal2.get(Calendar.HOUR\_OF\_DAY) // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import static org.apache.commons.lang3.JavaVersion.*; import org.apache.commons.lang3.SystemUtils; /** * Unit tests {@link org.apache.commons.lang3.time.DateUtils}. * * @author <a href="mailto:sergek@lokitech.com">Serge Knystautas</a> * @author <a href="mailto:steve@mungoknotwise.com">Steven Caswell</a> */ public class DateUtilsTest extends TestCase { private static final long MILLIS_TEST; static { GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2); cal.set(Calendar.MILLISECOND, 1); MILLIS_TEST = cal.getTime().getTime(); } DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null; public DateUtilsTest(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); dateParser = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH); dateAmPm1 = dateTimeParser.parse("February 3, 2002 01:10:00.000"); dateAmPm2 = dateTimeParser.parse("February 3, 2002 11:10:00.000"); dateAmPm3 = dateTimeParser.parse("February 3, 2002 13:10:00.000"); dateAmPm4 = dateTimeParser.parse("February 3, 2002 19:10:00.000"); date0 = dateTimeParser.parse("February 3, 2002 12:34:56.789"); date1 = dateTimeParser.parse("February 12, 2002 12:34:56.789"); date2 = dateTimeParser.parse("November 18, 2001 1:23:11.321"); defaultZone = TimeZone.getDefault(); zone = TimeZone.getTimeZone("MET"); TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); date3 = dateTimeParser.parse("March 30, 2003 05:30:45.000"); date4 = dateTimeParser.parse("March 30, 2003 01:10:00.000"); date5 = dateTimeParser.parse("March 30, 2003 01:40:00.000"); date6 = dateTimeParser.parse("March 30, 2003 02:10:00.000"); date7 = dateTimeParser.parse("March 30, 2003 02:40:00.000"); date8 = dateTimeParser.parse("October 26, 2003 05:30:45.000"); dateTimeParser.setTimeZone(defaultZone); TimeZone.setDefault(defaultZone); calAmPm1 = Calendar.getInstance(); calAmPm1.setTime(dateAmPm1); calAmPm2 = Calendar.getInstance(); calAmPm2.setTime(dateAmPm2); calAmPm3 = Calendar.getInstance(); calAmPm3.setTime(dateAmPm3); calAmPm4 = Calendar.getInstance(); calAmPm4.setTime(dateAmPm4); cal1 = Calendar.getInstance(); cal1.setTime(date1); cal2 = Calendar.getInstance(); cal2.setTime(date2); TimeZone.setDefault(zone); cal3 = Calendar.getInstance(); cal3.setTime(date3); cal4 = Calendar.getInstance(); cal4.setTime(date4); cal5 = Calendar.getInstance(); cal5.setTime(date5); cal6 = Calendar.getInstance(); cal6.setTime(date6); cal7 = Calendar.getInstance(); cal7.setTime(date7); cal8 = Calendar.getInstance(); cal8.setTime(date8); TimeZone.setDefault(defaultZone); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new DateUtils()); Constructor<?>[] cons = DateUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(DateUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(DateUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testIsSameDay_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); try { DateUtils.isSameDay((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameDay_Cal() { GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45); GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.DAY_OF_YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); cal1.add(Calendar.DAY_OF_YEAR, 1); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); try { DateUtils.isSameDay((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); try { DateUtils.isSameInstant((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(false, DateUtils.isSameInstant(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(true, DateUtils.isSameInstant(cal1, cal2)); try { DateUtils.isSameInstant((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameLocalTime_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(true, DateUtils.isSameLocalTime(cal1, cal2)); Calendar cal3 = Calendar.getInstance(); Calendar cal4 = Calendar.getInstance(); cal3.set(2004, 6, 9, 4, 0, 0); cal4.set(2004, 6, 9, 16, 0, 0); cal3.set(Calendar.MILLISECOND, 0); cal4.set(Calendar.MILLISECOND, 0); assertFalse("LANG-677", DateUtils.isSameLocalTime(cal3, cal4)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(false, DateUtils.isSameLocalTime(cal1, cal2)); try { DateUtils.isSameLocalTime((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseDate() throws Exception { GregorianCalendar cal = new GregorianCalendar(1972, 11, 3); String dateStr = "1972-12-03"; String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "1972-338"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "19721203"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { DateUtils.parseDate("PURPLE", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate("197212AB", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate(null, parsers); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, (String[]) null); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, new String[0]); fail(); } catch (ParseException ex) {} } // LANG-486 public void testParseDateWithLeniency() throws Exception { GregorianCalendar cal = new GregorianCalendar(1998, 6, 30); String dateStr = "02 942, 1996"; String[] parsers = new String[] {"MM DDD, yyyy"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { date = DateUtils.parseDateStrictly(dateStr, parsers); fail(); } catch (ParseException ex) {} } //----------------------------------------------------------------------- public void testAddYears() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addYears(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2001, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 1999, 6, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMonths() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMonths(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMonths(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 7, 5, 4, 3, 2, 1); result = DateUtils.addMonths(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 5, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddWeeks() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addWeeks(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addWeeks(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 12, 4, 3, 2, 1); result = DateUtils.addWeeks(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // july assertDate(result, 2000, 5, 28, 4, 3, 2, 1); // june } //----------------------------------------------------------------------- public void testAddDays() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addDays(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 6, 4, 3, 2, 1); result = DateUtils.addDays(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 4, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddHours() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addHours(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 5, 3, 2, 1); result = DateUtils.addHours(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 3, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMinutes() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMinutes(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 4, 2, 1); result = DateUtils.addMinutes(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 2, 2, 1); } //----------------------------------------------------------------------- public void testAddSeconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addSeconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 3, 1); result = DateUtils.addSeconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 1, 1); } //----------------------------------------------------------------------- public void testAddMilliseconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMilliseconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMilliseconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 2); result = DateUtils.addMilliseconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 0); } // ----------------------------------------------------------------------- public void testSetYears() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setYears(base, 2000); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.setYears(base, 2008); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2008, 6, 5, 4, 3, 2, 1); result = DateUtils.setYears(base, 2005); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2005, 6, 5, 4, 3, 2, 1); } // ----------------------------------------------------------------------- public void testSetMonths() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMonths(base, 5); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 5, 5, 4, 3, 2, 1); result = DateUtils.setMonths(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 1, 5, 4, 3, 2, 1); try { result = DateUtils.setMonths(base, 12); fail("DateUtils.setMonths did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetDays() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 1, 4, 3, 2, 1); result = DateUtils.setDays(base, 29); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 29, 4, 3, 2, 1); try { result = DateUtils.setDays(base, 32); fail("DateUtils.setDays did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetHours() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 0, 3, 2, 1); result = DateUtils.setHours(base, 23); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 23, 3, 2, 1); try { result = DateUtils.setHours(base, 24); fail("DateUtils.setHours did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetMinutes() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 0, 2, 1); result = DateUtils.setMinutes(base, 59); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 59, 2, 1); try { result = DateUtils.setMinutes(base, 60); fail("DateUtils.setMinutes did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetSeconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 0, 1); result = DateUtils.setSeconds(base, 59); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 59, 1); try { result = DateUtils.setSeconds(base, 60); fail("DateUtils.setSeconds did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetMilliseconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMilliseconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 0); result = DateUtils.setMilliseconds(base, 999); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 999); try { result = DateUtils.setMilliseconds(base, 1000); fail("DateUtils.setMilliseconds did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- private void assertDate(Date date, int year, int month, int day, int hour, int min, int sec, int mil) throws Exception { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); assertEquals(year, cal.get(Calendar.YEAR)); assertEquals(month, cal.get(Calendar.MONTH)); assertEquals(day, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(min, cal.get(Calendar.MINUTE)); assertEquals(sec, cal.get(Calendar.SECOND)); assertEquals(mil, cal.get(Calendar.MILLISECOND)); } //----------------------------------------------------------------------- public void testToCalendar() { assertEquals("Failed to convert to a Calendar and back", date1, DateUtils.toCalendar(date1).getTime()); try { DateUtils.toCalendar(null); fail("Expected NullPointerException to be thrown"); } catch(NullPointerException npe) { // expected } } //----------------------------------------------------------------------- /** * Tests various values with the round method */ public void testRound() throws Exception { // tests for public static Date round(Date date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round(date2, Calendar.MONTH)); assertEquals("round semimonth-0 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date0, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round(date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round(date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round(date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round(date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round(date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round(date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round(date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round(date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round(date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round(date2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round(dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round(dateAmPm4, Calendar.AM_PM)); // tests for public static Date round(Object date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round((Object) date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round((Object) date2, Calendar.MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round((Object) date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round((Object) date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round((Object) date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round((Object) date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round((Object) date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round((Object) date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) date2, Calendar.SECOND)); assertEquals("round calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) cal1, Calendar.SECOND)); assertEquals("round calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) cal2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm4, Calendar.AM_PM)); try { DateUtils.round((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} try { DateUtils.round(date1, -9999); fail(); } catch(IllegalArgumentException ex) {} assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm4, Calendar.AM_PM)); // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 / LANG-13 // Test rounding across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round(date4, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round(date7, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date rounding tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); } /** * Tests the Changes Made by LANG-346 to the DateUtils.modify() private method invoked * by DateUtils.round(). */ public void testRoundLang346() throws Exception { TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); Calendar testCalendar = Calendar.getInstance(); testCalendar.set(2007, 6, 2, 8, 8, 50); Date date = testCalendar.getTime(); assertEquals("Minute Round Up Failed", dateTimeParser.parse("July 2, 2007 08:09:00.000"), DateUtils.round(date, Calendar.MINUTE)); testCalendar.set(2007, 6, 2, 8, 8, 20); date = testCalendar.getTime(); assertEquals("Minute No Round Failed", dateTimeParser.parse("July 2, 2007 08:08:00.000"), DateUtils.round(date, Calendar.MINUTE)); testCalendar.set(2007, 6, 2, 8, 8, 50); testCalendar.set(Calendar.MILLISECOND, 600); date = testCalendar.getTime(); assertEquals("Second Round Up with 600 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:51.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 50); testCalendar.set(Calendar.MILLISECOND, 200); date = testCalendar.getTime(); assertEquals("Second Round Down with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:50.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 20); testCalendar.set(Calendar.MILLISECOND, 600); date = testCalendar.getTime(); assertEquals("Second Round Up with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:21.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 20); testCalendar.set(Calendar.MILLISECOND, 200); date = testCalendar.getTime(); assertEquals("Second Round Down with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:20.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 50); date = testCalendar.getTime(); assertEquals("Hour Round Down Failed", dateTimeParser.parse("July 2, 2007 08:00:00.000"), DateUtils.round(date, Calendar.HOUR)); testCalendar.set(2007, 6, 2, 8, 31, 50); date = testCalendar.getTime(); assertEquals("Hour Round Up Failed", dateTimeParser.parse("July 2, 2007 09:00:00.000"), DateUtils.round(date, Calendar.HOUR)); } /** * Tests various values with the trunc method */ public void testTruncate() throws Exception { // tests public static Date truncate(Date date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate(date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate(date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate(date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate(date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate(date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate(date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate(date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate(date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate(date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate(date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate(date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate(date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm4, Calendar.AM_PM)); // tests public static Date truncate(Object date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate((Object) date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate((Object) date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate((Object) date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate((Object) date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate((Object) date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate((Object) date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate((Object) date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate((Object) date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate((Object) date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("truncate calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) cal1, Calendar.SECOND)); assertEquals("truncate calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) cal2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.truncate((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test truncate across beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate(date3, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate((Object) cal3, Calendar.DATE)); // Test truncate across end of daylight saving time assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate(date8, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate((Object) cal8, Calendar.DATE)); TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); Calendar cal = DateUtils.truncate(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests for LANG-59 * * see http://issues.apache.org/jira/browse/LANG-59 */ public void testTruncateLang59() throws Exception { if (!SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { this.warn("WARNING: Test for LANG-59 not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); return; } // Set TimeZone to Mountain Time TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT"); TimeZone.setDefault(MST_MDT); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); format.setTimeZone(MST_MDT); Date oct31_01MDT = new Date(1099206000000L); Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT)); assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT)); assertEquals("Check 01:02:00.000", "2004-10-31 01:02:00.000 MDT", format.format(oct31_01_02MDT)); assertEquals("Check 01:02:03.000", "2004-10-31 01:02:03.000 MDT", format.format(oct31_01_02_03MDT)); assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT)); // ------- Demonstrate Problem ------- Calendar gval = Calendar.getInstance(); gval.setTime(new Date(oct31_01MDT.getTime())); gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L); // ---------- Test Truncate ---------- assertEquals("Truncate Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Truncate Calendar.SECOND", oct31_01_02_03MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Truncate Calendar.MINUTE", oct31_01_02MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Truncate Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Truncate Calendar.HOUR", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Truncate Calendar.DATE", oct31MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.DATE)); // ---------- Test Round (down) ---------- assertEquals("Round Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Round Calendar.SECOND", oct31_01_02_03MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Round Calendar.MINUTE", oct31_01_02MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Round Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Round Calendar.HOUR", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Round Calendar.DATE", oct31MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.DATE)); // restore default time zone TimeZone.setDefault(defaultZone); } // http://issues.apache.org/jira/browse/LANG-530 public void testLang530() throws ParseException { Date d = new Date(); String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d); Date d2 = DateUtils.parseDate(isoDateStr, new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() }); // the format loses milliseconds so have to reintroduce them assertEquals("Date not equal to itself ISO formatted and parsed", d.getTime(), d2.getTime() + d.getTime() % 1000); } /** * Tests various values with the ceiling method */ public void testCeil() throws Exception { // test javadoc assertEquals("ceiling javadoc-1 failed", dateTimeParser.parse("March 28, 2002 14:00:00.000"), DateUtils.ceiling( dateTimeParser.parse("March 28, 2002 13:45:01.231"), Calendar.HOUR)); assertEquals("ceiling javadoc-2 failed", dateTimeParser.parse("April 1, 2002 00:00:00.000"), DateUtils.ceiling( dateTimeParser.parse("March 28, 2002 13:45:01.231"), Calendar.MONTH)); // tests public static Date ceiling(Date date, int field) assertEquals("ceiling year-1 failed", dateParser.parse("January 1, 2003"), DateUtils.ceiling(date1, Calendar.YEAR)); assertEquals("ceiling year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.ceiling(date2, Calendar.YEAR)); assertEquals("ceiling month-1 failed", dateParser.parse("March 1, 2002"), DateUtils.ceiling(date1, Calendar.MONTH)); assertEquals("ceiling month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling(date2, Calendar.MONTH)); assertEquals("ceiling semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.ceiling(date1, DateUtils.SEMI_MONTH)); assertEquals("ceiling semimonth-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling(date2, DateUtils.SEMI_MONTH)); assertEquals("ceiling date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.ceiling(date1, Calendar.DATE)); assertEquals("ceiling date-2 failed", dateParser.parse("November 19, 2001"), DateUtils.ceiling(date2, Calendar.DATE)); assertEquals("ceiling hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.ceiling(date1, Calendar.HOUR)); assertEquals("ceiling hour-2 failed", dateTimeParser.parse("November 18, 2001 2:00:00.000"), DateUtils.ceiling(date2, Calendar.HOUR)); assertEquals("ceiling minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.ceiling(date1, Calendar.MINUTE)); assertEquals("ceiling minute-2 failed", dateTimeParser.parse("November 18, 2001 1:24:00.000"), DateUtils.ceiling(date2, Calendar.MINUTE)); assertEquals("ceiling second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling(date1, Calendar.SECOND)); assertEquals("ceiling second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling(date2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling(dateAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling(dateAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling(dateAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling(dateAmPm4, Calendar.AM_PM)); // tests public static Date ceiling(Object date, int field) assertEquals("ceiling year-1 failed", dateParser.parse("January 1, 2003"), DateUtils.ceiling((Object) date1, Calendar.YEAR)); assertEquals("ceiling year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.ceiling((Object) date2, Calendar.YEAR)); assertEquals("ceiling month-1 failed", dateParser.parse("March 1, 2002"), DateUtils.ceiling((Object) date1, Calendar.MONTH)); assertEquals("ceiling month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling((Object) date2, Calendar.MONTH)); assertEquals("ceiling semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.ceiling((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("ceiling semimonth-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("ceiling date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.ceiling((Object) date1, Calendar.DATE)); assertEquals("ceiling date-2 failed", dateParser.parse("November 19, 2001"), DateUtils.ceiling((Object) date2, Calendar.DATE)); assertEquals("ceiling hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.ceiling((Object) date1, Calendar.HOUR)); assertEquals("ceiling hour-2 failed", dateTimeParser.parse("November 18, 2001 2:00:00.000"), DateUtils.ceiling((Object) date2, Calendar.HOUR)); assertEquals("ceiling minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.ceiling((Object) date1, Calendar.MINUTE)); assertEquals("ceiling minute-2 failed", dateTimeParser.parse("November 18, 2001 1:24:00.000"), DateUtils.ceiling((Object) date2, Calendar.MINUTE)); assertEquals("ceiling second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling((Object) date1, Calendar.SECOND)); assertEquals("ceiling second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling((Object) date2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("ceiling calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling((Object) cal1, Calendar.SECOND)); assertEquals("ceiling calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling((Object) cal2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) calAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) calAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) calAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.ceiling((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} try { DateUtils.ceiling(date1, -9999); fail(); } catch(IllegalArgumentException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test ceiling across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date4, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal4, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date5, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal5, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date6, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal6, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date7, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal7, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling(date4, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling(date5, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling(date6, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling(date7, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date ceiling tests not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.ceiling(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.ceiling(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests the iterator exceptions */ public void testIteratorEx() throws Exception { try { DateUtils.iterator(Calendar.getInstance(), -9999); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER); fail(); } catch (ClassCastException ex) {} } /** * Tests the calendar iterator for week ranges */ public void testWeekIterator() throws Exception { Calendar now = Calendar.getInstance(); for (int i = 0; i< 7; i++) { Calendar today = DateUtils.truncate(now, Calendar.DATE); Calendar sunday = DateUtils.truncate(now, Calendar.DATE); sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK)); Calendar monday = DateUtils.truncate(now, Calendar.DATE); if (monday.get(Calendar.DAY_OF_WEEK) == 1) { //This is sunday... roll back 6 days monday.add(Calendar.DATE, -6); } else { monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK)); } Calendar centered = DateUtils.truncate(now, Calendar.DATE); centered.add(Calendar.DATE, -3); Iterator<?> it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_SUNDAY); assertWeekIterator(it, sunday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_MONDAY); assertWeekIterator(it, monday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_RELATIVE); assertWeekIterator(it, today); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); try { it.next(); fail(); } catch (NoSuchElementException ex) {} it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); it.next(); try { it.remove(); } catch( UnsupportedOperationException ex) {} now.add(Calendar.DATE,1); } } /** * Tests the calendar iterator for month-based ranges */ public void testMonthIterator() throws Exception { Iterator<?> it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("January 27, 2002"), dateParser.parse("March 2, 2002")); it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("January 28, 2002"), dateParser.parse("March 3, 2002")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("October 28, 2001"), dateParser.parse("December 1, 2001")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("October 29, 2001"), dateParser.parse("December 2, 2001")); } /** * This checks that this is a 7 element iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other. */ private static void assertWeekIterator(Iterator<?> it, Calendar start) { Calendar end = (Calendar) start.clone(); end.add(Calendar.DATE, 6); assertWeekIterator(it, start, end); } /** * Convenience method for when working with Date objects */ private static void assertWeekIterator(Iterator<?> it, Date start, Date end) { Calendar calStart = Calendar.getInstance(); calStart.setTime(start); Calendar calEnd = Calendar.getInstance(); calEnd.setTime(end); assertWeekIterator(it, calStart, calEnd); } /** * This checks that this is a 7 divisble iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other * (in addition to the proper start and stop dates) */ private static void assertWeekIterator(Iterator<?> it, Calendar start, Calendar end) { Calendar cal = (Calendar) it.next(); assertEquals("", start, cal, 0); Calendar last = null; int count = 1; while (it.hasNext()) { //Check this is just a date (no time component) assertEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0); last = cal; cal = (Calendar) it.next(); count++; //Check that this is one day more than the last date last.add(Calendar.DATE, 1); assertEquals("", last, cal, 0); } if (count % 7 != 0) { throw new AssertionFailedError("There were " + count + " days in this iterator"); } assertEquals("", end, cal, 0); } /** * Used to check that Calendar objects are close enough * delta is in milliseconds */ private static void assertEquals(String message, Calendar cal1, Calendar cal2, long delta) { if (Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta) { throw new AssertionFailedError( message + " expected " + cal1.getTime() + " but got " + cal2.getTime()); } } void warn(String msg) { System.err.println(msg); } }
public void testBug3476684_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); DateTime base = new DateTime(2012, 2, 25, 22, 15, zone); DateTime baseBefore = base.plusHours(1); // 23:15 (first) DateTime baseAfter = base.plusHours(2); // 23:15 (second) assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); }
org.joda.time.TestDateTimeZoneCutover::testBug3476684_adjustOffset
src/test/java/org/joda/time/TestDateTimeZoneCutover.java
1,262
src/test/java/org/joda/time/TestDateTimeZoneCutover.java
testBug3476684_adjustOffset
/* * Copyright 2001-2012 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.tz.DateTimeZoneBuilder; /** * This class is a JUnit test for DateTimeZone. * * @author Stephen Colebourne */ public class TestDateTimeZoneCutover extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeZoneCutover.class); } public TestDateTimeZoneCutover(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- // The behaviour of getOffsetFromLocal is defined in its javadoc // However, this definition doesn't work for all DateTimeField operations /** Mock zone simulating Asia/Gaza cutover at midnight 2007-04-01 */ private static long CUTOVER_GAZA = 1175378400000L; private static int OFFSET_GAZA = 7200000; // +02:00 private static final DateTimeZone MOCK_GAZA = new MockZone(CUTOVER_GAZA, OFFSET_GAZA, 3600); //----------------------------------------------------------------------- public void test_MockGazaIsCorrect() { DateTime pre = new DateTime(CUTOVER_GAZA - 1L, MOCK_GAZA); assertEquals("2007-03-31T23:59:59.999+02:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_GAZA + 1L, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Gaza() { doTest_getOffsetFromLocal_Gaza(-1, 23, 0, "2007-03-31T23:00:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(-1, 23, 30, "2007-03-31T23:30:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 2, 0, "2007-04-01T02:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 3, 0, "2007-04-01T03:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 4, 0, "2007-04-01T04:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 5, 0, "2007-04-01T05:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 6, 0, "2007-04-01T06:00:00.000+03:00"); } private void doTest_getOffsetFromLocal_Gaza(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_GAZA.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_GAZA); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_roundCeiling_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T20:00:00.000+02:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_setHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_DateTime_minusHour_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000+02:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000+02:00", minus9.toString()); } public void test_DateTime_plusHour_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T16:00:00.000+02:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000+02:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000+02:00", minus2.toString()); } public void test_DateTime_plusDay_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:00:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:30:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000+03:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Gaza() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-30T00:00:00.000+03:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_MutableDateTime_withZoneRetainFields_Gaza() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", dt.toString()); } public void test_LocalDate_new_Gaza() { LocalDate date1 = new LocalDate(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_GAZA - 1, MOCK_GAZA); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Gaza() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Gaza() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Gaza() { new DateTime(2007, 3, 31, 19, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 21, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 22, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_GAZA); } public void test_DateTime_parse_Gaza() { try { new DateTime("2007-04-01T00:00", MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- /** Mock zone simulating America/Grand_Turk cutover at midnight 2007-04-01 */ private static long CUTOVER_TURK = 1175403600000L; private static int OFFSET_TURK = -18000000; // -05:00 private static final DateTimeZone MOCK_TURK = new MockZone(CUTOVER_TURK, OFFSET_TURK, 3600); //----------------------------------------------------------------------- public void test_MockTurkIsCorrect() { DateTime pre = new DateTime(CUTOVER_TURK - 1L, MOCK_TURK); assertEquals("2007-03-31T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_TURK + 1L, MOCK_TURK); assertEquals("2007-04-01T01:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_Turk() { doTest_getOffsetFromLocal_Turk(-1, 23, 0, "2007-03-31T23:00:00.000-05:00"); doTest_getOffsetFromLocal_Turk(-1, 23, 30, "2007-03-31T23:30:00.000-05:00"); doTest_getOffsetFromLocal_Turk(0, 0, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 0, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 2, 0, "2007-04-01T02:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 3, 0, "2007-04-01T03:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 4, 0, "2007-04-01T04:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 5, 0, "2007-04-01T05:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 6, 0, "2007-04-01T06:00:00.000-04:00"); } private void doTest_getOffsetFromLocal_Turk(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_TURK.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_TURK); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloorNotDST_Turk() { DateTime dt = new DateTime(2007, 4, 2, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-02T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_Turk() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T20:00:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_setHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_DateTime_minusHour_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000-04:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000-05:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000-05:00", minus9.toString()); } public void test_DateTime_plusHour_Turk() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T16:00:00.000-05:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000-05:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000-04:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000-04:00", plus9.toString()); } public void test_DateTime_minusDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000-05:00", minus2.toString()); } public void test_DateTime_plusDay_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:30:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000-04:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Turk() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-30T00:00:00.000-04:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Turk() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_MutableDateTime_setZoneRetainFields_Turk() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", dt.toString()); } public void test_LocalDate_new_Turk() { LocalDate date1 = new LocalDate(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_TURK - 1, MOCK_TURK); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Turk() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Turk() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Turk() { new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 4, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 5, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 6, 0, 0, 0, MOCK_TURK); } public void test_DateTime_parse_Turk() { try { new DateTime("2007-04-01T00:00", MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 03:00 on 2007-03-11 */ private static long CUTOVER_NEW_YORK_SPRING = 1173596400000L; // 2007-03-11T03:00:00.000-04:00 private static final DateTimeZone ZONE_NEW_YORK = DateTimeZone.forID("America/New_York"); // DateTime x = new DateTime(2007, 1, 1, 0, 0, 0, 0, ZONE_NEW_YORK); // System.out.println(ZONE_NEW_YORK.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_NEW_YORK.nextTransition(x.getMillis()), ZONE_NEW_YORK); // System.out.println(y); //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Spring() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_SPRING - 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T01:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_SPRING, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_SPRING + 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Spring() { doTest_getOffsetFromLocal(3, 11, 1, 0, "2007-03-11T01:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 1,30, "2007-03-11T01:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 4, 0, "2007-03-11T04:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 5, 0, "2007-03-11T05:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 6, 0, "2007-03-11T06:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 7, 0, "2007-03-11T07:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 8, 0, "2007-03-11T08:00:00.000-04:00", ZONE_NEW_YORK); } public void test_DateTime_setHourAcross_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-11T04:00:00.000-04:00", res.toString()); } public void test_DateTime_setHourForward_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T03:30:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T04:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T03:31:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 01:00 on 2007-11-04 */ private static long CUTOVER_NEW_YORK_AUTUMN = 1194156000000L; // 2007-11-04T01:00:00.000-05:00 //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_AUTUMN - 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:59:59.999-04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_AUTUMN, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.000-05:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_AUTUMN + 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.001-05:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Autumn() { doTest_getOffsetFromLocal(11, 4, 0, 0, "2007-11-04T00:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 0,30, "2007-11-04T00:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1, 0, "2007-11-04T01:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1,30, "2007-11-04T01:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2, 0, "2007-11-04T02:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2,30, "2007-11-04T02:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3, 0, "2007-11-04T03:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3,30, "2007-11-04T03:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 4, 0, "2007-11-04T04:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 5, 0, "2007-11-04T05:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 6, 0, "2007-11-04T06:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 7, 0, "2007-11-04T07:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 8, 0, "2007-11-04T08:00:00.000-05:00", ZONE_NEW_YORK); } public void test_DateTime_constructor_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); } public void test_DateTime_plusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 3, 18, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-03T18:00:00.000-04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-11-04T00:00:00.000-04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-11-04T01:00:00.000-04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-11-04T01:00:00.000-05:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-11-04T02:00:00.000-05:00", plus9.toString()); } public void test_DateTime_minusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T08:00:00.000-05:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-11-04T02:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-11-04T01:00:00.000-05:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-11-04T01:00:00.000-04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-11-04T00:00:00.000-04:00", minus9.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T02:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- /** Europe/Moscow cutover from 01:59 to 03:00 on 2007-03-25 */ private static long CUTOVER_MOSCOW_SPRING = 1174777200000L; // 2007-03-25T03:00:00.000+04:00 private static final DateTimeZone ZONE_MOSCOW = DateTimeZone.forID("Europe/Moscow"); //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Spring() { // DateTime x = new DateTime(2007, 7, 1, 0, 0, 0, 0, ZONE_MOSCOW); // System.out.println(ZONE_MOSCOW.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_MOSCOW.nextTransition(x.getMillis()), ZONE_MOSCOW); // System.out.println(y); DateTime pre = new DateTime(CUTOVER_MOSCOW_SPRING - 1L, ZONE_MOSCOW); assertEquals("2007-03-25T01:59:59.999+03:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_SPRING, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.000+04:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_SPRING + 1L, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.001+04:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Spring() { doTest_getOffsetFromLocal(3, 25, 1, 0, "2007-03-25T01:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 1,30, "2007-03-25T01:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 4, 0, "2007-03-25T04:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 5, 0, "2007-03-25T05:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 6, 0, "2007-03-25T06:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 7, 0, "2007-03-25T07:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 8, 0, "2007-03-25T08:00:00.000+04:00", ZONE_MOSCOW); } public void test_DateTime_setHourAcross_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-25T04:00:00.000+04:00", res.toString()); } public void test_DateTime_setHourForward_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 8, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T08:00:00.000+04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- /** America/New_York cutover from 02:59 to 02:00 on 2007-10-28 */ private static long CUTOVER_MOSCOW_AUTUMN = 1193526000000L; // 2007-10-28T02:00:00.000+03:00 //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_MOSCOW_AUTUMN - 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:59:59.999+04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_AUTUMN, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_AUTUMN + 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Autumn() { doTest_getOffsetFromLocal(10, 28, 0, 0, "2007-10-28T00:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 0,30, "2007-10-28T00:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1, 0, "2007-10-28T01:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1,30, "2007-10-28T01:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2, 0, "2007-10-28T02:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30, "2007-10-28T02:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30,59,999, "2007-10-28T02:30:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,998, "2007-10-28T02:59:59.998+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,999, "2007-10-28T02:59:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3, 0, "2007-10-28T03:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3,30, "2007-10-28T03:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 4, 0, "2007-10-28T04:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 5, 0, "2007-10-28T05:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 6, 0, "2007-10-28T06:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 7, 0, "2007-10-28T07:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 8, 0, "2007-10-28T08:00:00.000+03:00", ZONE_MOSCOW); } public void test_getOffsetFromLocal_Moscow_Autumn_overlap_mins() { for (int min = 0; min < 60; min++) { if (min < 10) { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:0" + min + ":00.000+04:00", ZONE_MOSCOW); } else { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:" + min + ":00.000+04:00", ZONE_MOSCOW); } } } public void test_DateTime_constructor_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 2, 30, ZONE_MOSCOW); assertEquals("2007-10-28T02:30:00.000+04:00", dt.toString()); } public void test_DateTime_plusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 27, 19, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-27T19:00:00.000+04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-10-28T01:00:00.000+04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-10-28T02:00:00.000+04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-10-28T02:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-10-28T03:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 9, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-28T09:00:00.000+03:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-10-28T03:00:00.000+03:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-10-28T02:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-10-28T02:00:00.000+04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-10-28T01:00:00.000+04:00", minus9.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/Guatemala cutover from 23:59 to 23:00 on 2006-09-30 */ private static long CUTOVER_GUATEMALA_AUTUMN = 1159678800000L; // 2006-09-30T23:00:00.000-06:00 private static final DateTimeZone ZONE_GUATEMALA = DateTimeZone.forID("America/Guatemala"); //----------------------------------------------------------------------- public void test_GuatemataIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_GUATEMALA_AUTUMN - 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GUATEMALA_AUTUMN, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.000-06:00", at.toString()); DateTime post = new DateTime(CUTOVER_GUATEMALA_AUTUMN + 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.001-06:00", post.toString()); } public void test_getOffsetFromLocal_Guatemata_Autumn() { doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0, 0, "2006-10-01T00:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0,30, "2006-10-01T00:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1, 0, "2006-10-01T01:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1,30, "2006-10-01T01:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2, 0, "2006-10-01T02:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2,30, "2006-10-01T02:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3, 0, "2006-10-01T03:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3,30, "2006-10-01T03:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4, 0, "2006-10-01T04:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4,30, "2006-10-01T04:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5, 0, "2006-10-01T05:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5,30, "2006-10-01T05:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6, 0, "2006-10-01T06:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6,30, "2006-10-01T06:30:00.000-06:00", ZONE_GUATEMALA); } public void test_DateTime_plusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 9, 30, 20, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-09-30T20:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusHours(1); assertEquals("2006-09-30T21:00:00.000-05:00", plus1.toString()); DateTime plus2 = dt.plusHours(2); assertEquals("2006-09-30T22:00:00.000-05:00", plus2.toString()); DateTime plus3 = dt.plusHours(3); assertEquals("2006-09-30T23:00:00.000-05:00", plus3.toString()); DateTime plus4 = dt.plusHours(4); assertEquals("2006-09-30T23:00:00.000-06:00", plus4.toString()); DateTime plus5 = dt.plusHours(5); assertEquals("2006-10-01T00:00:00.000-06:00", plus5.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2006-10-01T01:00:00.000-06:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2006-10-01T02:00:00.000-06:00", plus7.toString()); } public void test_DateTime_minusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 10, 1, 2, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-10-01T02:00:00.000-06:00", dt.toString()); DateTime minus1 = dt.minusHours(1); assertEquals("2006-10-01T01:00:00.000-06:00", minus1.toString()); DateTime minus2 = dt.minusHours(2); assertEquals("2006-10-01T00:00:00.000-06:00", minus2.toString()); DateTime minus3 = dt.minusHours(3); assertEquals("2006-09-30T23:00:00.000-06:00", minus3.toString()); DateTime minus4 = dt.minusHours(4); assertEquals("2006-09-30T23:00:00.000-05:00", minus4.toString()); DateTime minus5 = dt.minusHours(5); assertEquals("2006-09-30T22:00:00.000-05:00", minus5.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2006-09-30T21:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2006-09-30T20:00:00.000-05:00", minus7.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_DateTime_JustAfterLastEverOverlap() { // based on America/Argentina/Catamarca in file 2009s DateTimeZone zone = new DateTimeZoneBuilder() .setStandardOffset(-3 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("SUMMER", 1 * DateTimeConstants.MILLIS_PER_HOUR, 2000, 2008, 'w', 4, 10, 0, true, 23 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("WINTER", 0, 2000, 2008, 'w', 8, 10, 0, true, 0 * DateTimeConstants.MILLIS_PER_HOUR) .toDateTimeZone("Zone", false); LocalDate date = new LocalDate(2008, 8, 10); assertEquals("2008-08-10", date.toString()); DateTime dt = date.toDateTimeAtStartOfDay(zone); assertEquals("2008-08-10T00:00:00.000-03:00", dt.toString()); } // public void test_toDateMidnight_SaoPaolo() { // // RFE: 1684259 // DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); // LocalDate baseDate = new LocalDate(2006, 11, 5); // DateMidnight dm = baseDate.toDateMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dm.toString()); // DateTime dt = baseDate.toDateTimeAtMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dt.toString()); // } //----------------------------------------------------------------------- private static final DateTimeZone ZONE_PARIS = DateTimeZone.forID("Europe/Paris"); public void testWithMinuteOfHourInDstChange_mockZone() { DateTime cutover = new DateTime(2010, 10, 31, 1, 15, DateTimeZone.forOffsetHoursMinutes(0, 30)); assertEquals("2010-10-31T01:15:00.000+00:30", cutover.toString()); DateTimeZone halfHourZone = new MockZone(cutover.getMillis(), 3600000, -1800); DateTime pre = new DateTime(2010, 10, 31, 1, 0, halfHourZone); assertEquals("2010-10-31T01:00:00.000+01:00", pre.toString()); DateTime post = new DateTime(2010, 10, 31, 1, 59, halfHourZone); assertEquals("2010-10-31T01:59:00.000+00:30", post.toString()); DateTime testPre1 = pre.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+01:00", testPre1.toString()); // retain offset DateTime testPre2 = pre.withMinuteOfHour(50); assertEquals("2010-10-31T01:50:00.000+00:30", testPre2.toString()); DateTime testPost1 = post.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+00:30", testPost1.toString()); // retain offset DateTime testPost2 = post.withMinuteOfHour(10); assertEquals("2010-10-31T01:10:00.000+01:00", testPost2.toString()); } public void testWithHourOfDayInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withHourOfDay(2); assertEquals("2010-10-31T02:30:10.123+02:00", test.toString()); } public void testWithMinuteOfHourInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMinuteOfHour(0); assertEquals("2010-10-31T02:00:10.123+02:00", test.toString()); } public void testWithSecondOfMinuteInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withSecondOfMinute(0); assertEquals("2010-10-31T02:30:00.123+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_summer() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_winter() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+01:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+01:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+01:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_summer() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-04:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-04:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-04:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_winter() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-05:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-05:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-05:00", test.toString()); } public void testPlusMinutesInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMinutes(1); assertEquals("2010-10-31T02:31:10.123+02:00", test.toString()); } public void testPlusSecondsInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusSeconds(1); assertEquals("2010-10-31T02:30:11.123+02:00", test.toString()); } public void testPlusMillisInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMillis(1); assertEquals("2010-10-31T02:30:10.124+02:00", test.toString()); } public void testBug2182444_usCentral() { Chronology chronUSCentral = GregorianChronology.getInstance(DateTimeZone.forID("US/Central")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime usCentralStandardInUTC = new DateTime(2008, 11, 2, 7, 0, 0, 0, chronUTC); DateTime usCentralDaylightInUTC = new DateTime(2008, 11, 2, 6, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronUSCentral.getZone().isStandardOffset(usCentralStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronUSCentral.getZone().isStandardOffset(usCentralDaylightInUTC.getMillis())); DateTime usCentralStandardInUSCentral = usCentralStandardInUTC.toDateTime(chronUSCentral); DateTime usCentralDaylightInUSCentral = usCentralDaylightInUTC.toDateTime(chronUSCentral); assertEquals(1, usCentralStandardInUSCentral.getHourOfDay()); assertEquals(usCentralStandardInUSCentral.getHourOfDay(), usCentralDaylightInUSCentral.getHourOfDay()); assertTrue(usCentralStandardInUSCentral.getMillis() != usCentralDaylightInUSCentral.getMillis()); assertEquals(usCentralStandardInUSCentral, usCentralStandardInUSCentral.withHourOfDay(1)); assertEquals(usCentralStandardInUSCentral.getMillis() + 3, usCentralStandardInUSCentral.withMillisOfSecond(3).getMillis()); assertEquals(usCentralDaylightInUSCentral, usCentralDaylightInUSCentral.withHourOfDay(1)); assertEquals(usCentralDaylightInUSCentral.getMillis() + 3, usCentralDaylightInUSCentral.withMillisOfSecond(3).getMillis()); } public void testBug2182444_ausNSW() { Chronology chronAusNSW = GregorianChronology.getInstance(DateTimeZone.forID("Australia/NSW")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime australiaNSWStandardInUTC = new DateTime(2008, 4, 5, 16, 0, 0, 0, chronUTC); DateTime australiaNSWDaylightInUTC = new DateTime(2008, 4, 5, 15, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronAusNSW.getZone().isStandardOffset(australiaNSWStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronAusNSW.getZone().isStandardOffset(australiaNSWDaylightInUTC.getMillis())); DateTime australiaNSWStandardInAustraliaNSW = australiaNSWStandardInUTC.toDateTime(chronAusNSW); DateTime australiaNSWDaylightInAusraliaNSW = australiaNSWDaylightInUTC.toDateTime(chronAusNSW); assertEquals(2, australiaNSWStandardInAustraliaNSW.getHourOfDay()); assertEquals(australiaNSWStandardInAustraliaNSW.getHourOfDay(), australiaNSWDaylightInAusraliaNSW.getHourOfDay()); assertTrue(australiaNSWStandardInAustraliaNSW.getMillis() != australiaNSWDaylightInAusraliaNSW.getMillis()); assertEquals(australiaNSWStandardInAustraliaNSW, australiaNSWStandardInAustraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWStandardInAustraliaNSW.getMillis() + 3, australiaNSWStandardInAustraliaNSW.withMillisOfSecond(3).getMillis()); assertEquals(australiaNSWDaylightInAusraliaNSW, australiaNSWDaylightInAusraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWDaylightInAusraliaNSW.getMillis() + 3, australiaNSWDaylightInAusraliaNSW.withMillisOfSecond(3).getMillis()); } public void testPeriod() { DateTime a = new DateTime("2010-10-31T02:00:00.000+02:00", ZONE_PARIS); DateTime b = new DateTime("2010-10-31T02:01:00.000+02:00", ZONE_PARIS); Period period = new Period(a, b, PeriodType.standard()); assertEquals("PT1M", period.toString()); } public void testForum4013394_retainOffsetWhenRetainFields_sameOffsetsDifferentZones() { final DateTimeZone fromDTZ = DateTimeZone.forID("Europe/London"); final DateTimeZone toDTZ = DateTimeZone.forID("Europe/Lisbon"); DateTime baseBefore = new DateTime(2007, 10, 28, 1, 15, fromDTZ).minusHours(1); DateTime baseAfter = new DateTime(2007, 10, 28, 1, 15, fromDTZ); DateTime testBefore = baseBefore.withZoneRetainFields(toDTZ); DateTime testAfter = baseAfter.withZoneRetainFields(toDTZ); // toString ignores time-zone but includes offset assertEquals(baseBefore.toString(), testBefore.toString()); assertEquals(baseAfter.toString(), testAfter.toString()); } //------------------------------------------------------------------------- public void testBug3192457_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2007, 10, 28, 3, 15, zone); DateTime baseBefore = base.minusHours(2); DateTime baseAfter = base.minusHours(1); assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); } public void testBug3476684_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); DateTime base = new DateTime(2012, 2, 25, 22, 15, zone); DateTime baseBefore = base.plusHours(1); // 23:15 (first) DateTime baseAfter = base.plusHours(2); // 23:15 (second) assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); } public void testBug3476684_adjustOffset_springGap() { final DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); DateTime base = new DateTime(2011, 10, 15, 22, 15, zone); DateTime baseBefore = base.plusHours(1); // 23:15 DateTime baseAfter = base.plusHours(2); // 01:15 assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseBefore, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseAfter, baseAfter.withEarlierOffsetAtOverlap()); } // ensure Summer time picked //----------------------------------------------------------------------- public void testDateTimeCreation_athens() { DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime base = new DateTime(2011, 10, 30, 3, 15, zone); assertEquals("2011-10-30T03:15:00.000+03:00", base.toString()); assertEquals("2011-10-30T03:15:00.000+02:00", base.plusHours(1).toString()); } public void testDateTimeCreation_paris() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2011, 10, 30, 2, 15, zone); assertEquals("2011-10-30T02:15:00.000+02:00", base.toString()); assertEquals("2011-10-30T02:15:00.000+01:00", base.plusHours(1).toString()); } public void testDateTimeCreation_london() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); DateTime base = new DateTime(2011, 10, 30, 1, 15, zone); assertEquals("2011-10-30T01:15:00.000+01:00", base.toString()); assertEquals("2011-10-30T01:15:00.000Z", base.plusHours(1).toString()); } public void testDateTimeCreation_newYork() { DateTimeZone zone = DateTimeZone.forID("America/New_York"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-04:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-05:00", base.plusHours(1).toString()); } public void testDateTimeCreation_losAngeles() { DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-07:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-08:00", base.plusHours(1).toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, sec, milli, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(year, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { DateTime dt = new DateTime(year, month, day, hour, min, sec, milli, DateTimeZone.UTC); int offset = zone.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, zone); assertEquals(res.toString(), expected, res.toString()); } }
// You are a professional Java test case writer, please create a test case named `testBug3476684_adjustOffset` for the issue `Time-141`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Time-141 // // ## Issue-Title: // #141 Bug on withLaterOffsetAtOverlap method // // // // // // ## Issue-Description: // The method withLaterOffsetAtOverlap created to workaround the issue 3192457 seems to not be working at all. // // I won´t write many info about the problem to solve because the issue 3192457 have this info indeed. // // But If something is unclear I can answer on the comments. // // // Problem demonstration: // // TimeZone.setDefault(TimeZone.getTimeZone("America/Sao\_Paulo")); // // DateTimeZone.setDefault( DateTimeZone.forID("America/Sao\_Paulo") ); // // // // ``` // DateTime dtch; // { // dtch = new DateTime(2012,2,25,5,5,5,5).millisOfDay().withMaximumValue(); // System.out.println( dtch ); // prints: 2012-02-25T23:59:59.999-02:00 //Were are at the first 23:** of the day. // //At this point dtch have the -03:00 offset // } // { // dtch = dtch.plus(60001); // System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-03:00 //Were are at the first minute of the second 23:** of the day. Ok its correct // //At this point dtch have the -03:00 offset // } // { // dtch = dtch.withEarlierOffsetAtOverlap(); // System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-02:00 //Were are at the first minute of the first 23:** of the day. Ok its correct // //At this point dtch have the -02:00 offset ( because we called withEarlierOffsetAtOverlap() ) // This method is working perfectly // } // { // dtch = dtch.withLaterOffsetAtOverlap(); // System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-02:00 //Were are at the first minute of the first 23:** of the day. // // Here is the problem we should have a -03:00 offset here since we called withLaterOffsetAtOverlap() expecting to change to the second 23:** of the day // } // // ``` // // On the last two brackets we can see that withLaterOffsetAtOverlap is not undoing withEarlierOffsetAtOverlap as it should ( and not even working at all ) // // // // public void testBug3476684_adjustOffset() {
1,262
17
1,248
src/test/java/org/joda/time/TestDateTimeZoneCutover.java
src/test/java
```markdown ## Issue-ID: Time-141 ## Issue-Title: #141 Bug on withLaterOffsetAtOverlap method ## Issue-Description: The method withLaterOffsetAtOverlap created to workaround the issue 3192457 seems to not be working at all. I won´t write many info about the problem to solve because the issue 3192457 have this info indeed. But If something is unclear I can answer on the comments. Problem demonstration: TimeZone.setDefault(TimeZone.getTimeZone("America/Sao\_Paulo")); DateTimeZone.setDefault( DateTimeZone.forID("America/Sao\_Paulo") ); ``` DateTime dtch; { dtch = new DateTime(2012,2,25,5,5,5,5).millisOfDay().withMaximumValue(); System.out.println( dtch ); // prints: 2012-02-25T23:59:59.999-02:00 //Were are at the first 23:** of the day. //At this point dtch have the -03:00 offset } { dtch = dtch.plus(60001); System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-03:00 //Were are at the first minute of the second 23:** of the day. Ok its correct //At this point dtch have the -03:00 offset } { dtch = dtch.withEarlierOffsetAtOverlap(); System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-02:00 //Were are at the first minute of the first 23:** of the day. Ok its correct //At this point dtch have the -02:00 offset ( because we called withEarlierOffsetAtOverlap() ) // This method is working perfectly } { dtch = dtch.withLaterOffsetAtOverlap(); System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-02:00 //Were are at the first minute of the first 23:** of the day. // Here is the problem we should have a -03:00 offset here since we called withLaterOffsetAtOverlap() expecting to change to the second 23:** of the day } ``` On the last two brackets we can see that withLaterOffsetAtOverlap is not undoing withEarlierOffsetAtOverlap as it should ( and not even working at all ) ``` You are a professional Java test case writer, please create a test case named `testBug3476684_adjustOffset` for the issue `Time-141`, utilizing the provided issue report information and the following function signature. ```java public void testBug3476684_adjustOffset() { ```
1,248
[ "org.joda.time.DateTimeZone" ]
3364e07e2c87857a9618fc246e9cf1ce9781b6c471ae7da8cecba7984da3f0f9
public void testBug3476684_adjustOffset()
// You are a professional Java test case writer, please create a test case named `testBug3476684_adjustOffset` for the issue `Time-141`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Time-141 // // ## Issue-Title: // #141 Bug on withLaterOffsetAtOverlap method // // // // // // ## Issue-Description: // The method withLaterOffsetAtOverlap created to workaround the issue 3192457 seems to not be working at all. // // I won´t write many info about the problem to solve because the issue 3192457 have this info indeed. // // But If something is unclear I can answer on the comments. // // // Problem demonstration: // // TimeZone.setDefault(TimeZone.getTimeZone("America/Sao\_Paulo")); // // DateTimeZone.setDefault( DateTimeZone.forID("America/Sao\_Paulo") ); // // // // ``` // DateTime dtch; // { // dtch = new DateTime(2012,2,25,5,5,5,5).millisOfDay().withMaximumValue(); // System.out.println( dtch ); // prints: 2012-02-25T23:59:59.999-02:00 //Were are at the first 23:** of the day. // //At this point dtch have the -03:00 offset // } // { // dtch = dtch.plus(60001); // System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-03:00 //Were are at the first minute of the second 23:** of the day. Ok its correct // //At this point dtch have the -03:00 offset // } // { // dtch = dtch.withEarlierOffsetAtOverlap(); // System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-02:00 //Were are at the first minute of the first 23:** of the day. Ok its correct // //At this point dtch have the -02:00 offset ( because we called withEarlierOffsetAtOverlap() ) // This method is working perfectly // } // { // dtch = dtch.withLaterOffsetAtOverlap(); // System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-02:00 //Were are at the first minute of the first 23:** of the day. // // Here is the problem we should have a -03:00 offset here since we called withLaterOffsetAtOverlap() expecting to change to the second 23:** of the day // } // // ``` // // On the last two brackets we can see that withLaterOffsetAtOverlap is not undoing withEarlierOffsetAtOverlap as it should ( and not even working at all ) // // // //
Time
/* * Copyright 2001-2012 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.tz.DateTimeZoneBuilder; /** * This class is a JUnit test for DateTimeZone. * * @author Stephen Colebourne */ public class TestDateTimeZoneCutover extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeZoneCutover.class); } public TestDateTimeZoneCutover(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- // The behaviour of getOffsetFromLocal is defined in its javadoc // However, this definition doesn't work for all DateTimeField operations /** Mock zone simulating Asia/Gaza cutover at midnight 2007-04-01 */ private static long CUTOVER_GAZA = 1175378400000L; private static int OFFSET_GAZA = 7200000; // +02:00 private static final DateTimeZone MOCK_GAZA = new MockZone(CUTOVER_GAZA, OFFSET_GAZA, 3600); //----------------------------------------------------------------------- public void test_MockGazaIsCorrect() { DateTime pre = new DateTime(CUTOVER_GAZA - 1L, MOCK_GAZA); assertEquals("2007-03-31T23:59:59.999+02:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_GAZA + 1L, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Gaza() { doTest_getOffsetFromLocal_Gaza(-1, 23, 0, "2007-03-31T23:00:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(-1, 23, 30, "2007-03-31T23:30:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 2, 0, "2007-04-01T02:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 3, 0, "2007-04-01T03:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 4, 0, "2007-04-01T04:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 5, 0, "2007-04-01T05:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 6, 0, "2007-04-01T06:00:00.000+03:00"); } private void doTest_getOffsetFromLocal_Gaza(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_GAZA.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_GAZA); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_roundCeiling_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T20:00:00.000+02:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_setHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_DateTime_minusHour_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000+02:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000+02:00", minus9.toString()); } public void test_DateTime_plusHour_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T16:00:00.000+02:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000+02:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000+02:00", minus2.toString()); } public void test_DateTime_plusDay_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:00:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:30:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000+03:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Gaza() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-30T00:00:00.000+03:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_MutableDateTime_withZoneRetainFields_Gaza() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", dt.toString()); } public void test_LocalDate_new_Gaza() { LocalDate date1 = new LocalDate(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_GAZA - 1, MOCK_GAZA); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Gaza() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Gaza() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Gaza() { new DateTime(2007, 3, 31, 19, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 21, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 22, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_GAZA); } public void test_DateTime_parse_Gaza() { try { new DateTime("2007-04-01T00:00", MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- /** Mock zone simulating America/Grand_Turk cutover at midnight 2007-04-01 */ private static long CUTOVER_TURK = 1175403600000L; private static int OFFSET_TURK = -18000000; // -05:00 private static final DateTimeZone MOCK_TURK = new MockZone(CUTOVER_TURK, OFFSET_TURK, 3600); //----------------------------------------------------------------------- public void test_MockTurkIsCorrect() { DateTime pre = new DateTime(CUTOVER_TURK - 1L, MOCK_TURK); assertEquals("2007-03-31T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_TURK + 1L, MOCK_TURK); assertEquals("2007-04-01T01:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_Turk() { doTest_getOffsetFromLocal_Turk(-1, 23, 0, "2007-03-31T23:00:00.000-05:00"); doTest_getOffsetFromLocal_Turk(-1, 23, 30, "2007-03-31T23:30:00.000-05:00"); doTest_getOffsetFromLocal_Turk(0, 0, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 0, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 2, 0, "2007-04-01T02:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 3, 0, "2007-04-01T03:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 4, 0, "2007-04-01T04:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 5, 0, "2007-04-01T05:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 6, 0, "2007-04-01T06:00:00.000-04:00"); } private void doTest_getOffsetFromLocal_Turk(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_TURK.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_TURK); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloorNotDST_Turk() { DateTime dt = new DateTime(2007, 4, 2, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-02T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_Turk() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T20:00:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_setHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_DateTime_minusHour_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000-04:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000-05:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000-05:00", minus9.toString()); } public void test_DateTime_plusHour_Turk() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T16:00:00.000-05:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000-05:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000-04:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000-04:00", plus9.toString()); } public void test_DateTime_minusDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000-05:00", minus2.toString()); } public void test_DateTime_plusDay_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:30:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000-04:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Turk() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-30T00:00:00.000-04:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Turk() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_MutableDateTime_setZoneRetainFields_Turk() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", dt.toString()); } public void test_LocalDate_new_Turk() { LocalDate date1 = new LocalDate(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_TURK - 1, MOCK_TURK); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Turk() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Turk() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Turk() { new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 4, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 5, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 6, 0, 0, 0, MOCK_TURK); } public void test_DateTime_parse_Turk() { try { new DateTime("2007-04-01T00:00", MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 03:00 on 2007-03-11 */ private static long CUTOVER_NEW_YORK_SPRING = 1173596400000L; // 2007-03-11T03:00:00.000-04:00 private static final DateTimeZone ZONE_NEW_YORK = DateTimeZone.forID("America/New_York"); // DateTime x = new DateTime(2007, 1, 1, 0, 0, 0, 0, ZONE_NEW_YORK); // System.out.println(ZONE_NEW_YORK.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_NEW_YORK.nextTransition(x.getMillis()), ZONE_NEW_YORK); // System.out.println(y); //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Spring() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_SPRING - 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T01:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_SPRING, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_SPRING + 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Spring() { doTest_getOffsetFromLocal(3, 11, 1, 0, "2007-03-11T01:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 1,30, "2007-03-11T01:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 4, 0, "2007-03-11T04:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 5, 0, "2007-03-11T05:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 6, 0, "2007-03-11T06:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 7, 0, "2007-03-11T07:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 8, 0, "2007-03-11T08:00:00.000-04:00", ZONE_NEW_YORK); } public void test_DateTime_setHourAcross_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-11T04:00:00.000-04:00", res.toString()); } public void test_DateTime_setHourForward_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T03:30:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T04:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T03:31:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 01:00 on 2007-11-04 */ private static long CUTOVER_NEW_YORK_AUTUMN = 1194156000000L; // 2007-11-04T01:00:00.000-05:00 //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_AUTUMN - 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:59:59.999-04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_AUTUMN, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.000-05:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_AUTUMN + 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.001-05:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Autumn() { doTest_getOffsetFromLocal(11, 4, 0, 0, "2007-11-04T00:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 0,30, "2007-11-04T00:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1, 0, "2007-11-04T01:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1,30, "2007-11-04T01:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2, 0, "2007-11-04T02:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2,30, "2007-11-04T02:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3, 0, "2007-11-04T03:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3,30, "2007-11-04T03:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 4, 0, "2007-11-04T04:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 5, 0, "2007-11-04T05:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 6, 0, "2007-11-04T06:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 7, 0, "2007-11-04T07:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 8, 0, "2007-11-04T08:00:00.000-05:00", ZONE_NEW_YORK); } public void test_DateTime_constructor_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); } public void test_DateTime_plusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 3, 18, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-03T18:00:00.000-04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-11-04T00:00:00.000-04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-11-04T01:00:00.000-04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-11-04T01:00:00.000-05:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-11-04T02:00:00.000-05:00", plus9.toString()); } public void test_DateTime_minusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T08:00:00.000-05:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-11-04T02:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-11-04T01:00:00.000-05:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-11-04T01:00:00.000-04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-11-04T00:00:00.000-04:00", minus9.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T02:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- /** Europe/Moscow cutover from 01:59 to 03:00 on 2007-03-25 */ private static long CUTOVER_MOSCOW_SPRING = 1174777200000L; // 2007-03-25T03:00:00.000+04:00 private static final DateTimeZone ZONE_MOSCOW = DateTimeZone.forID("Europe/Moscow"); //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Spring() { // DateTime x = new DateTime(2007, 7, 1, 0, 0, 0, 0, ZONE_MOSCOW); // System.out.println(ZONE_MOSCOW.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_MOSCOW.nextTransition(x.getMillis()), ZONE_MOSCOW); // System.out.println(y); DateTime pre = new DateTime(CUTOVER_MOSCOW_SPRING - 1L, ZONE_MOSCOW); assertEquals("2007-03-25T01:59:59.999+03:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_SPRING, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.000+04:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_SPRING + 1L, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.001+04:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Spring() { doTest_getOffsetFromLocal(3, 25, 1, 0, "2007-03-25T01:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 1,30, "2007-03-25T01:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 4, 0, "2007-03-25T04:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 5, 0, "2007-03-25T05:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 6, 0, "2007-03-25T06:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 7, 0, "2007-03-25T07:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 8, 0, "2007-03-25T08:00:00.000+04:00", ZONE_MOSCOW); } public void test_DateTime_setHourAcross_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-25T04:00:00.000+04:00", res.toString()); } public void test_DateTime_setHourForward_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 8, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T08:00:00.000+04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- /** America/New_York cutover from 02:59 to 02:00 on 2007-10-28 */ private static long CUTOVER_MOSCOW_AUTUMN = 1193526000000L; // 2007-10-28T02:00:00.000+03:00 //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_MOSCOW_AUTUMN - 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:59:59.999+04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_AUTUMN, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_AUTUMN + 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Autumn() { doTest_getOffsetFromLocal(10, 28, 0, 0, "2007-10-28T00:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 0,30, "2007-10-28T00:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1, 0, "2007-10-28T01:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1,30, "2007-10-28T01:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2, 0, "2007-10-28T02:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30, "2007-10-28T02:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30,59,999, "2007-10-28T02:30:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,998, "2007-10-28T02:59:59.998+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,999, "2007-10-28T02:59:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3, 0, "2007-10-28T03:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3,30, "2007-10-28T03:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 4, 0, "2007-10-28T04:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 5, 0, "2007-10-28T05:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 6, 0, "2007-10-28T06:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 7, 0, "2007-10-28T07:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 8, 0, "2007-10-28T08:00:00.000+03:00", ZONE_MOSCOW); } public void test_getOffsetFromLocal_Moscow_Autumn_overlap_mins() { for (int min = 0; min < 60; min++) { if (min < 10) { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:0" + min + ":00.000+04:00", ZONE_MOSCOW); } else { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:" + min + ":00.000+04:00", ZONE_MOSCOW); } } } public void test_DateTime_constructor_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 2, 30, ZONE_MOSCOW); assertEquals("2007-10-28T02:30:00.000+04:00", dt.toString()); } public void test_DateTime_plusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 27, 19, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-27T19:00:00.000+04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-10-28T01:00:00.000+04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-10-28T02:00:00.000+04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-10-28T02:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-10-28T03:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 9, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-28T09:00:00.000+03:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-10-28T03:00:00.000+03:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-10-28T02:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-10-28T02:00:00.000+04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-10-28T01:00:00.000+04:00", minus9.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/Guatemala cutover from 23:59 to 23:00 on 2006-09-30 */ private static long CUTOVER_GUATEMALA_AUTUMN = 1159678800000L; // 2006-09-30T23:00:00.000-06:00 private static final DateTimeZone ZONE_GUATEMALA = DateTimeZone.forID("America/Guatemala"); //----------------------------------------------------------------------- public void test_GuatemataIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_GUATEMALA_AUTUMN - 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GUATEMALA_AUTUMN, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.000-06:00", at.toString()); DateTime post = new DateTime(CUTOVER_GUATEMALA_AUTUMN + 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.001-06:00", post.toString()); } public void test_getOffsetFromLocal_Guatemata_Autumn() { doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0, 0, "2006-10-01T00:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0,30, "2006-10-01T00:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1, 0, "2006-10-01T01:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1,30, "2006-10-01T01:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2, 0, "2006-10-01T02:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2,30, "2006-10-01T02:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3, 0, "2006-10-01T03:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3,30, "2006-10-01T03:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4, 0, "2006-10-01T04:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4,30, "2006-10-01T04:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5, 0, "2006-10-01T05:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5,30, "2006-10-01T05:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6, 0, "2006-10-01T06:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6,30, "2006-10-01T06:30:00.000-06:00", ZONE_GUATEMALA); } public void test_DateTime_plusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 9, 30, 20, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-09-30T20:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusHours(1); assertEquals("2006-09-30T21:00:00.000-05:00", plus1.toString()); DateTime plus2 = dt.plusHours(2); assertEquals("2006-09-30T22:00:00.000-05:00", plus2.toString()); DateTime plus3 = dt.plusHours(3); assertEquals("2006-09-30T23:00:00.000-05:00", plus3.toString()); DateTime plus4 = dt.plusHours(4); assertEquals("2006-09-30T23:00:00.000-06:00", plus4.toString()); DateTime plus5 = dt.plusHours(5); assertEquals("2006-10-01T00:00:00.000-06:00", plus5.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2006-10-01T01:00:00.000-06:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2006-10-01T02:00:00.000-06:00", plus7.toString()); } public void test_DateTime_minusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 10, 1, 2, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-10-01T02:00:00.000-06:00", dt.toString()); DateTime minus1 = dt.minusHours(1); assertEquals("2006-10-01T01:00:00.000-06:00", minus1.toString()); DateTime minus2 = dt.minusHours(2); assertEquals("2006-10-01T00:00:00.000-06:00", minus2.toString()); DateTime minus3 = dt.minusHours(3); assertEquals("2006-09-30T23:00:00.000-06:00", minus3.toString()); DateTime minus4 = dt.minusHours(4); assertEquals("2006-09-30T23:00:00.000-05:00", minus4.toString()); DateTime minus5 = dt.minusHours(5); assertEquals("2006-09-30T22:00:00.000-05:00", minus5.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2006-09-30T21:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2006-09-30T20:00:00.000-05:00", minus7.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_DateTime_JustAfterLastEverOverlap() { // based on America/Argentina/Catamarca in file 2009s DateTimeZone zone = new DateTimeZoneBuilder() .setStandardOffset(-3 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("SUMMER", 1 * DateTimeConstants.MILLIS_PER_HOUR, 2000, 2008, 'w', 4, 10, 0, true, 23 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("WINTER", 0, 2000, 2008, 'w', 8, 10, 0, true, 0 * DateTimeConstants.MILLIS_PER_HOUR) .toDateTimeZone("Zone", false); LocalDate date = new LocalDate(2008, 8, 10); assertEquals("2008-08-10", date.toString()); DateTime dt = date.toDateTimeAtStartOfDay(zone); assertEquals("2008-08-10T00:00:00.000-03:00", dt.toString()); } // public void test_toDateMidnight_SaoPaolo() { // // RFE: 1684259 // DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); // LocalDate baseDate = new LocalDate(2006, 11, 5); // DateMidnight dm = baseDate.toDateMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dm.toString()); // DateTime dt = baseDate.toDateTimeAtMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dt.toString()); // } //----------------------------------------------------------------------- private static final DateTimeZone ZONE_PARIS = DateTimeZone.forID("Europe/Paris"); public void testWithMinuteOfHourInDstChange_mockZone() { DateTime cutover = new DateTime(2010, 10, 31, 1, 15, DateTimeZone.forOffsetHoursMinutes(0, 30)); assertEquals("2010-10-31T01:15:00.000+00:30", cutover.toString()); DateTimeZone halfHourZone = new MockZone(cutover.getMillis(), 3600000, -1800); DateTime pre = new DateTime(2010, 10, 31, 1, 0, halfHourZone); assertEquals("2010-10-31T01:00:00.000+01:00", pre.toString()); DateTime post = new DateTime(2010, 10, 31, 1, 59, halfHourZone); assertEquals("2010-10-31T01:59:00.000+00:30", post.toString()); DateTime testPre1 = pre.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+01:00", testPre1.toString()); // retain offset DateTime testPre2 = pre.withMinuteOfHour(50); assertEquals("2010-10-31T01:50:00.000+00:30", testPre2.toString()); DateTime testPost1 = post.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+00:30", testPost1.toString()); // retain offset DateTime testPost2 = post.withMinuteOfHour(10); assertEquals("2010-10-31T01:10:00.000+01:00", testPost2.toString()); } public void testWithHourOfDayInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withHourOfDay(2); assertEquals("2010-10-31T02:30:10.123+02:00", test.toString()); } public void testWithMinuteOfHourInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMinuteOfHour(0); assertEquals("2010-10-31T02:00:10.123+02:00", test.toString()); } public void testWithSecondOfMinuteInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withSecondOfMinute(0); assertEquals("2010-10-31T02:30:00.123+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_summer() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_winter() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+01:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+01:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+01:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_summer() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-04:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-04:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-04:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_winter() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-05:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-05:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-05:00", test.toString()); } public void testPlusMinutesInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMinutes(1); assertEquals("2010-10-31T02:31:10.123+02:00", test.toString()); } public void testPlusSecondsInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusSeconds(1); assertEquals("2010-10-31T02:30:11.123+02:00", test.toString()); } public void testPlusMillisInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMillis(1); assertEquals("2010-10-31T02:30:10.124+02:00", test.toString()); } public void testBug2182444_usCentral() { Chronology chronUSCentral = GregorianChronology.getInstance(DateTimeZone.forID("US/Central")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime usCentralStandardInUTC = new DateTime(2008, 11, 2, 7, 0, 0, 0, chronUTC); DateTime usCentralDaylightInUTC = new DateTime(2008, 11, 2, 6, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronUSCentral.getZone().isStandardOffset(usCentralStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronUSCentral.getZone().isStandardOffset(usCentralDaylightInUTC.getMillis())); DateTime usCentralStandardInUSCentral = usCentralStandardInUTC.toDateTime(chronUSCentral); DateTime usCentralDaylightInUSCentral = usCentralDaylightInUTC.toDateTime(chronUSCentral); assertEquals(1, usCentralStandardInUSCentral.getHourOfDay()); assertEquals(usCentralStandardInUSCentral.getHourOfDay(), usCentralDaylightInUSCentral.getHourOfDay()); assertTrue(usCentralStandardInUSCentral.getMillis() != usCentralDaylightInUSCentral.getMillis()); assertEquals(usCentralStandardInUSCentral, usCentralStandardInUSCentral.withHourOfDay(1)); assertEquals(usCentralStandardInUSCentral.getMillis() + 3, usCentralStandardInUSCentral.withMillisOfSecond(3).getMillis()); assertEquals(usCentralDaylightInUSCentral, usCentralDaylightInUSCentral.withHourOfDay(1)); assertEquals(usCentralDaylightInUSCentral.getMillis() + 3, usCentralDaylightInUSCentral.withMillisOfSecond(3).getMillis()); } public void testBug2182444_ausNSW() { Chronology chronAusNSW = GregorianChronology.getInstance(DateTimeZone.forID("Australia/NSW")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime australiaNSWStandardInUTC = new DateTime(2008, 4, 5, 16, 0, 0, 0, chronUTC); DateTime australiaNSWDaylightInUTC = new DateTime(2008, 4, 5, 15, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronAusNSW.getZone().isStandardOffset(australiaNSWStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronAusNSW.getZone().isStandardOffset(australiaNSWDaylightInUTC.getMillis())); DateTime australiaNSWStandardInAustraliaNSW = australiaNSWStandardInUTC.toDateTime(chronAusNSW); DateTime australiaNSWDaylightInAusraliaNSW = australiaNSWDaylightInUTC.toDateTime(chronAusNSW); assertEquals(2, australiaNSWStandardInAustraliaNSW.getHourOfDay()); assertEquals(australiaNSWStandardInAustraliaNSW.getHourOfDay(), australiaNSWDaylightInAusraliaNSW.getHourOfDay()); assertTrue(australiaNSWStandardInAustraliaNSW.getMillis() != australiaNSWDaylightInAusraliaNSW.getMillis()); assertEquals(australiaNSWStandardInAustraliaNSW, australiaNSWStandardInAustraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWStandardInAustraliaNSW.getMillis() + 3, australiaNSWStandardInAustraliaNSW.withMillisOfSecond(3).getMillis()); assertEquals(australiaNSWDaylightInAusraliaNSW, australiaNSWDaylightInAusraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWDaylightInAusraliaNSW.getMillis() + 3, australiaNSWDaylightInAusraliaNSW.withMillisOfSecond(3).getMillis()); } public void testPeriod() { DateTime a = new DateTime("2010-10-31T02:00:00.000+02:00", ZONE_PARIS); DateTime b = new DateTime("2010-10-31T02:01:00.000+02:00", ZONE_PARIS); Period period = new Period(a, b, PeriodType.standard()); assertEquals("PT1M", period.toString()); } public void testForum4013394_retainOffsetWhenRetainFields_sameOffsetsDifferentZones() { final DateTimeZone fromDTZ = DateTimeZone.forID("Europe/London"); final DateTimeZone toDTZ = DateTimeZone.forID("Europe/Lisbon"); DateTime baseBefore = new DateTime(2007, 10, 28, 1, 15, fromDTZ).minusHours(1); DateTime baseAfter = new DateTime(2007, 10, 28, 1, 15, fromDTZ); DateTime testBefore = baseBefore.withZoneRetainFields(toDTZ); DateTime testAfter = baseAfter.withZoneRetainFields(toDTZ); // toString ignores time-zone but includes offset assertEquals(baseBefore.toString(), testBefore.toString()); assertEquals(baseAfter.toString(), testAfter.toString()); } //------------------------------------------------------------------------- public void testBug3192457_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2007, 10, 28, 3, 15, zone); DateTime baseBefore = base.minusHours(2); DateTime baseAfter = base.minusHours(1); assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); } public void testBug3476684_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); DateTime base = new DateTime(2012, 2, 25, 22, 15, zone); DateTime baseBefore = base.plusHours(1); // 23:15 (first) DateTime baseAfter = base.plusHours(2); // 23:15 (second) assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); } public void testBug3476684_adjustOffset_springGap() { final DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); DateTime base = new DateTime(2011, 10, 15, 22, 15, zone); DateTime baseBefore = base.plusHours(1); // 23:15 DateTime baseAfter = base.plusHours(2); // 01:15 assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertEquals(baseBefore, baseBefore.withLaterOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseAfter, baseAfter.withEarlierOffsetAtOverlap()); } // ensure Summer time picked //----------------------------------------------------------------------- public void testDateTimeCreation_athens() { DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime base = new DateTime(2011, 10, 30, 3, 15, zone); assertEquals("2011-10-30T03:15:00.000+03:00", base.toString()); assertEquals("2011-10-30T03:15:00.000+02:00", base.plusHours(1).toString()); } public void testDateTimeCreation_paris() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2011, 10, 30, 2, 15, zone); assertEquals("2011-10-30T02:15:00.000+02:00", base.toString()); assertEquals("2011-10-30T02:15:00.000+01:00", base.plusHours(1).toString()); } public void testDateTimeCreation_london() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); DateTime base = new DateTime(2011, 10, 30, 1, 15, zone); assertEquals("2011-10-30T01:15:00.000+01:00", base.toString()); assertEquals("2011-10-30T01:15:00.000Z", base.plusHours(1).toString()); } public void testDateTimeCreation_newYork() { DateTimeZone zone = DateTimeZone.forID("America/New_York"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-04:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-05:00", base.plusHours(1).toString()); } public void testDateTimeCreation_losAngeles() { DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-07:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-08:00", base.plusHours(1).toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, sec, milli, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(year, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { DateTime dt = new DateTime(year, month, day, hour, min, sec, milli, DateTimeZone.UTC); int offset = zone.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, zone); assertEquals(res.toString(), expected, res.toString()); } }