parser_test.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. package parser
  2. import (
  3. "errors"
  4. "regexp"
  5. "strings"
  6. "testing"
  7. "github.com/dop251/goja/ast"
  8. "github.com/dop251/goja/file"
  9. "github.com/dop251/goja/token"
  10. "github.com/dop251/goja/unistring"
  11. )
  12. func firstErr(err error) error {
  13. switch err := err.(type) {
  14. case ErrorList:
  15. return err[0]
  16. }
  17. return err
  18. }
  19. var matchBeforeAfterSeparator = regexp.MustCompile(`(?m)^[ \t]*---$`)
  20. func testParse(src string) (parser *_parser, program *ast.Program, err error) {
  21. defer func() {
  22. if tmp := recover(); tmp != nil {
  23. switch tmp := tmp.(type) {
  24. case string:
  25. if strings.HasPrefix(tmp, "SyntaxError:") {
  26. parser = nil
  27. program = nil
  28. err = errors.New(tmp)
  29. return
  30. }
  31. }
  32. panic(tmp)
  33. }
  34. }()
  35. parser = newParser("", src)
  36. program, err = parser.parse()
  37. return
  38. }
  39. func TestParseFile(t *testing.T) {
  40. tt(t, func() {
  41. _, err := ParseFile(nil, "", `/abc/`, 0)
  42. is(err, nil)
  43. _, err = ParseFile(nil, "", `/(?!def)abc/`, IgnoreRegExpErrors)
  44. is(err, nil)
  45. _, err = ParseFile(nil, "", `/(?!def)abc/; return`, IgnoreRegExpErrors)
  46. is(err, "(anonymous): Line 1:15 Illegal return statement")
  47. })
  48. }
  49. func TestParseFunction(t *testing.T) {
  50. tt(t, func() {
  51. test := func(prm, bdy string, expect interface{}) *ast.FunctionLiteral {
  52. function, err := ParseFunction(prm, bdy)
  53. is(firstErr(err), expect)
  54. return function
  55. }
  56. test("a, b,c,d", "", nil)
  57. test("a, b;,c,d", "", "(anonymous): Line 1:15 Unexpected token ;")
  58. test("this", "", "(anonymous): Line 1:11 Unexpected token this")
  59. test("a, b, c, null", "", "(anonymous): Line 1:20 Unexpected token null")
  60. test("a, b,c,d", "return;", nil)
  61. test("a, b,c,d", "break;", "(anonymous): Line 2:1 Illegal break statement")
  62. test("a, b,c,d", "{}", nil)
  63. })
  64. }
  65. func TestParserErr(t *testing.T) {
  66. tt(t, func() {
  67. test := func(input string, expect interface{}) (*ast.Program, *_parser) {
  68. parser := newParser("", input)
  69. program, err := parser.parse()
  70. is(firstErr(err), expect)
  71. return program, parser
  72. }
  73. test("", nil)
  74. program, parser := test(`
  75. var abc;
  76. break; do {
  77. } while(true);
  78. `, "(anonymous): Line 3:9 Illegal break statement")
  79. {
  80. stmt := program.Body[1].(*ast.BadStatement)
  81. is(parser.position(stmt.From).Column, 9)
  82. is(parser.position(stmt.To).Column, 16)
  83. is(parser.slice(stmt.From, stmt.To), "break; ")
  84. }
  85. s := string([]byte{0x22, 0x25, 0x21, 0x63, 0x28, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3d, 0x25, 0x63, 0x25, 0x9c, 0x29, 0x25, 0x21, 0x5c, 0x28, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3d, 0x5c, 0xe2, 0x80, 0xa9, 0x29, 0x78, 0x39, 0x63, 0x22})
  86. test(s, `(anonymous): Line 1:16 Invalid UTF-8 character`)
  87. test("{", "(anonymous): Line 1:2 Unexpected end of input")
  88. test("}", "(anonymous): Line 1:1 Unexpected token }")
  89. test("3ea", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  90. test("3in", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  91. test("3in []", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  92. test("3e", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  93. test("3e+", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  94. test("3e-", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  95. test("3x", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  96. test("3x0", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  97. test("0x", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  98. test("09", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  99. test("018", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  100. test("01.0", "(anonymous): Line 1:3 Unexpected number")
  101. test(".0.9", "(anonymous): Line 1:3 Unexpected number")
  102. test("0o3e1", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  103. test("01a", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  104. test("0x3in[]", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  105. test("\"Hello\nWorld\"", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  106. test("\u203f = 10", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  107. test("x\\", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  108. test("x\\\\", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  109. test("x\\u005c", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  110. test("x\\u002a", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  111. test("x\\\\u002a", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  112. test("/\n", "(anonymous): Line 1:1 Invalid regular expression: missing /")
  113. test("0 = 1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
  114. test("func() = 1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
  115. test("(1 + 1) = 2", "(anonymous): Line 1:2 Invalid left-hand side in assignment")
  116. test("1++", "(anonymous): Line 1:2 Invalid left-hand side in assignment")
  117. test("1--", "(anonymous): Line 1:2 Invalid left-hand side in assignment")
  118. test("--1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
  119. test("for((1 + 1) in abc) def();", "(anonymous): Line 1:1 Invalid left-hand side in for-in or for-of")
  120. test("[", "(anonymous): Line 1:2 Unexpected end of input")
  121. test("[,", "(anonymous): Line 1:3 Unexpected end of input")
  122. test("1 + {", "(anonymous): Line 1:6 Unexpected end of input")
  123. test("1 + { abc:abc", "(anonymous): Line 1:14 Unexpected end of input")
  124. test("1 + { abc:abc,", "(anonymous): Line 1:15 Unexpected end of input")
  125. test("var abc = /\n/", "(anonymous): Line 1:11 Invalid regular expression: missing /")
  126. test("var abc = \"\n", "(anonymous): Line 1:11 Unexpected token ILLEGAL")
  127. test("var if = 0", "(anonymous): Line 1:5 Unexpected token if")
  128. test("abc + 0 = 1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
  129. test("+abc = 1", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
  130. test("1 + (", "(anonymous): Line 1:6 Unexpected end of input")
  131. test("\n\n\n{", "(anonymous): Line 4:2 Unexpected end of input")
  132. test("\n/* Some multiline\ncomment */\n)", "(anonymous): Line 4:1 Unexpected token )")
  133. test("+1 ** 2", "(anonymous): Line 1:4 Unexpected token **")
  134. test("typeof 1 ** 2", "(anonymous): Line 1:10 Unexpected token **")
  135. // TODO
  136. //{ set 1 }
  137. //{ get 2 }
  138. //({ set: s(if) { } })
  139. //({ set s(.) { } })
  140. //({ set: s() { } })
  141. //({ set: s(a, b) { } })
  142. //({ get: g(d) { } })
  143. //({ get i() { }, i: 42 })
  144. //({ i: 42, get i() { } })
  145. //({ set i(x) { }, i: 42 })
  146. //({ i: 42, set i(x) { } })
  147. //({ get i() { }, get i() { } })
  148. //({ set i(x) { }, set i(x) { } })
  149. test("function abc(if) {}", "(anonymous): Line 1:14 Unexpected token if")
  150. test("function abc(true) {}", "(anonymous): Line 1:14 Unexpected token true")
  151. test("function abc(false) {}", "(anonymous): Line 1:14 Unexpected token false")
  152. test("function abc(null) {}", "(anonymous): Line 1:14 Unexpected token null")
  153. test("function null() {}", "(anonymous): Line 1:10 Unexpected token null")
  154. test("function true() {}", "(anonymous): Line 1:10 Unexpected token true")
  155. test("function false() {}", "(anonymous): Line 1:10 Unexpected token false")
  156. test("function if() {}", "(anonymous): Line 1:10 Unexpected token if")
  157. test("a b;", "(anonymous): Line 1:3 Unexpected identifier")
  158. test("if.a", "(anonymous): Line 1:3 Unexpected token .")
  159. test("a if", "(anonymous): Line 1:3 Unexpected token if")
  160. test("a class", "(anonymous): Line 1:3 Unexpected reserved word")
  161. test("break\n", "(anonymous): Line 1:1 Illegal break statement")
  162. test("break 1;", "(anonymous): Line 1:7 Unexpected number")
  163. test("for (;;) { break 1; }", "(anonymous): Line 1:18 Unexpected number")
  164. test("continue\n", "(anonymous): Line 1:1 Illegal continue statement")
  165. test("continue 1;", "(anonymous): Line 1:10 Unexpected number")
  166. test("for (;;) { continue 1; }", "(anonymous): Line 1:21 Unexpected number")
  167. test("throw", "(anonymous): Line 1:1 Unexpected end of input")
  168. test("throw;", "(anonymous): Line 1:6 Unexpected token ;")
  169. test("throw \n", "(anonymous): Line 1:1 Unexpected end of input")
  170. test("for (var abc, def in {});", "(anonymous): Line 1:19 Unexpected token in")
  171. test("for ((abc in {});;);", nil)
  172. test("for ((abc in {}));", "(anonymous): Line 1:17 Unexpected token )")
  173. test("for (+abc in {});", "(anonymous): Line 1:1 Invalid left-hand side in for-in or for-of")
  174. test("if (false)", "(anonymous): Line 1:11 Unexpected end of input")
  175. test("if (false) abc(); else", "(anonymous): Line 1:23 Unexpected end of input")
  176. test("do", "(anonymous): Line 1:3 Unexpected end of input")
  177. test("while (false)", "(anonymous): Line 1:14 Unexpected end of input")
  178. test("for (;;)", "(anonymous): Line 1:9 Unexpected end of input")
  179. test("with (abc)", "(anonymous): Line 1:11 Unexpected end of input")
  180. test("try {}", "(anonymous): Line 1:1 Missing catch or finally after try")
  181. test("try {} catch () {}", "(anonymous): Line 1:15 Unexpected token )")
  182. test("\u203f = 1", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  183. // TODO
  184. // const x = 12, y;
  185. // const x, y = 12;
  186. // const x;
  187. // if(true) let a = 1;
  188. // if(true) const a = 1;
  189. test(`new abc()."def"`, "(anonymous): Line 1:11 Unexpected string")
  190. test("/*", "(anonymous): Line 1:3 Unexpected end of input")
  191. test("/**", "(anonymous): Line 1:4 Unexpected end of input")
  192. test("/*\n\n\n", "(anonymous): Line 4:1 Unexpected end of input")
  193. test("/*\n\n\n*", "(anonymous): Line 4:2 Unexpected end of input")
  194. test("/*abc", "(anonymous): Line 1:6 Unexpected end of input")
  195. test("/*abc *", "(anonymous): Line 1:9 Unexpected end of input")
  196. test("\n]", "(anonymous): Line 2:1 Unexpected token ]")
  197. test("\r\n]", "(anonymous): Line 2:1 Unexpected token ]")
  198. test("\n\r]", "(anonymous): Line 3:1 Unexpected token ]")
  199. test("//\r\n]", "(anonymous): Line 2:1 Unexpected token ]")
  200. test("//\n\r]", "(anonymous): Line 3:1 Unexpected token ]")
  201. test("/abc\\\n/", "(anonymous): Line 1:1 Invalid regular expression: missing /")
  202. test("//\r \n]", "(anonymous): Line 3:1 Unexpected token ]")
  203. test("/*\r\n*/]", "(anonymous): Line 2:3 Unexpected token ]")
  204. test("/*\r \n*/]", "(anonymous): Line 3:3 Unexpected token ]")
  205. test("\\\\", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  206. test("\\u005c", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  207. test("\\abc", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  208. test("\\u0000", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  209. test("\\u200c = []", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  210. test("\\u200D = []", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  211. test(`"\`, "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  212. test(`"\u`, "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  213. test("return", "(anonymous): Line 1:1 Illegal return statement")
  214. test("continue", "(anonymous): Line 1:1 Illegal continue statement")
  215. test("break", "(anonymous): Line 1:1 Illegal break statement")
  216. test("switch (abc) { default: continue; }", "(anonymous): Line 1:25 Illegal continue statement")
  217. test("do { abc } *", "(anonymous): Line 1:12 Unexpected token *")
  218. test("while (true) { break abc; }", "(anonymous): Line 1:16 Undefined label 'abc'")
  219. test("while (true) { continue abc; }", "(anonymous): Line 1:16 Undefined label 'abc'")
  220. test("abc: while (true) { (function(){ break abc; }); }", "(anonymous): Line 1:34 Undefined label 'abc'")
  221. test("abc: while (true) { (function(){ abc: break abc; }); }", nil)
  222. test("abc: while (true) { (function(){ continue abc; }); }", "(anonymous): Line 1:34 Undefined label 'abc'")
  223. test(`abc: if (0) break abc; else {}`, nil)
  224. test(`abc: if (0) { break abc; } else {}`, nil)
  225. test(`abc: if (0) { break abc } else {}`, nil)
  226. test("abc: while (true) { abc: while (true) {} }", "(anonymous): Line 1:21 Label 'abc' already exists")
  227. test(`if(0) { do { } while(0) } else { do { } while(0) }`, nil)
  228. test(`if(0) do { } while(0); else do { } while(0)`, nil)
  229. test("_: _: while (true) {]", "(anonymous): Line 1:4 Label '_' already exists")
  230. test("_:\n_:\nwhile (true) {]", "(anonymous): Line 2:1 Label '_' already exists")
  231. test("_:\n _:\nwhile (true) {]", "(anonymous): Line 2:4 Label '_' already exists")
  232. test("function(){}", "(anonymous): Line 1:9 Unexpected token (")
  233. test("\n/*/", "(anonymous): Line 2:4 Unexpected end of input")
  234. test("/*/.source", "(anonymous): Line 1:11 Unexpected end of input")
  235. test("var class", "(anonymous): Line 1:5 Unexpected reserved word")
  236. test("var if", "(anonymous): Line 1:5 Unexpected token if")
  237. test("object Object", "(anonymous): Line 1:8 Unexpected identifier")
  238. test("[object Object]", "(anonymous): Line 1:9 Unexpected identifier")
  239. test("\\u0xyz", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  240. test(`for (var abc, def in {}) {}`, "(anonymous): Line 1:19 Unexpected token in")
  241. test(`for (abc, def in {}) {}`, "(anonymous): Line 1:1 Invalid left-hand side in for-in or for-of")
  242. test(`for (var abc=def, ghi=("abc" in {}); true;) {}`, nil)
  243. {
  244. // Semicolon insertion
  245. test("this\nif (1);", nil)
  246. test("while (1) { break\nif (1); }", nil)
  247. test("throw\nif (1);", "(anonymous): Line 1:1 Illegal newline after throw")
  248. test("(function(){ return\nif (1); })", nil)
  249. test("while (1) { continue\nif (1); }", nil)
  250. test("debugger\nif (1);", nil)
  251. }
  252. { // Reserved words
  253. test("class", "(anonymous): Line 1:1 Unexpected reserved word")
  254. test("abc.class = 1", nil)
  255. test("var class;", "(anonymous): Line 1:5 Unexpected reserved word")
  256. test("const", "(anonymous): Line 1:6 Unexpected end of input")
  257. test("abc.const = 1", nil)
  258. test("var const;", "(anonymous): Line 1:5 Unexpected token const")
  259. test("enum", "(anonymous): Line 1:1 Unexpected reserved word")
  260. test("abc.enum = 1", nil)
  261. test("var enum;", "(anonymous): Line 1:5 Unexpected reserved word")
  262. test("export", "(anonymous): Line 1:1 Unexpected reserved word")
  263. test("abc.export = 1", nil)
  264. test("var export;", "(anonymous): Line 1:5 Unexpected reserved word")
  265. test("extends", "(anonymous): Line 1:1 Unexpected reserved word")
  266. test("abc.extends = 1", nil)
  267. test("var extends;", "(anonymous): Line 1:5 Unexpected reserved word")
  268. test("import", "(anonymous): Line 1:1 Unexpected reserved word")
  269. test("abc.import = 1", nil)
  270. test("var import;", "(anonymous): Line 1:5 Unexpected reserved word")
  271. test("super", "(anonymous): Line 1:1 Unexpected reserved word")
  272. test("abc.super = 1", nil)
  273. test("var super;", "(anonymous): Line 1:5 Unexpected reserved word")
  274. test(`
  275. obj = {
  276. aaa: 1
  277. bbb: "string"
  278. };`, "(anonymous): Line 4:6 Unexpected identifier")
  279. test("{}", nil)
  280. test("{a: 1}", nil)
  281. test("{a: 1,}", "(anonymous): Line 1:7 Unexpected token }")
  282. test("{a: 1, b: 2}", "(anonymous): Line 1:9 Unexpected token :")
  283. test("{a: 1, b: 2,}", "(anonymous): Line 1:9 Unexpected token :")
  284. test(`let f = () => new import('');`, "(anonymous): Line 1:19 Unexpected reserved word")
  285. }
  286. { // Reserved words (strict)
  287. test(`implements`, nil)
  288. test(`abc.implements = 1`, nil)
  289. test(`var implements;`, nil)
  290. test(`interface`, nil)
  291. test(`abc.interface = 1`, nil)
  292. test(`var interface;`, nil)
  293. test(`let`, nil)
  294. test(`abc.let = 1`, nil)
  295. test(`var let;`, nil)
  296. test(`package`, nil)
  297. test(`abc.package = 1`, nil)
  298. test(`var package;`, nil)
  299. test(`private`, nil)
  300. test(`abc.private = 1`, nil)
  301. test(`var private;`, nil)
  302. test(`protected`, nil)
  303. test(`abc.protected = 1`, nil)
  304. test(`var protected;`, nil)
  305. test(`public`, nil)
  306. test(`abc.public = 1`, nil)
  307. test(`var public;`, nil)
  308. test(`static`, nil)
  309. test(`abc.static = 1`, nil)
  310. test(`var static;`, nil)
  311. test(`yield`, nil)
  312. test(`abc.yield = 1`, nil)
  313. test(`var yield;`, nil)
  314. }
  315. test(`0, { get a(param = null) {} };`, "(anonymous): Line 1:11 Getter must not have any formal parameters.")
  316. test(`let{f(`, "(anonymous): Line 1:7 Unexpected end of input")
  317. test("`", "(anonymous): Line 1:2 Unexpected end of input")
  318. test(" `", "(anonymous): Line 1:3 Unexpected end of input")
  319. test("` ", "(anonymous): Line 1:3 Unexpected end of input")
  320. test(`var{..(`, "(anonymous): Line 1:7 Unexpected token ILLEGAL")
  321. test(`var{get..(`, "(anonymous): Line 1:10 Unexpected token ILLEGAL")
  322. test(`var{set..(`, "(anonymous): Line 1:10 Unexpected token ILLEGAL")
  323. })
  324. }
  325. func TestParser(t *testing.T) {
  326. tt(t, func() {
  327. test := func(source string, chk interface{}) *ast.Program {
  328. _, program, err := testParse(source)
  329. is(firstErr(err), chk)
  330. return program
  331. }
  332. test(`new (() => {});`, nil)
  333. test(`
  334. abc
  335. --
  336. []
  337. `, "(anonymous): Line 3:13 Invalid left-hand side in assignment")
  338. test(`
  339. abc--
  340. []
  341. `, nil)
  342. test("1\n[]\n", "(anonymous): Line 2:2 Unexpected token ]")
  343. test(`
  344. function abc() {
  345. }
  346. abc()
  347. `, nil)
  348. test("", nil)
  349. test("//", nil)
  350. test("/* */", nil)
  351. test("/** **/", nil)
  352. test("/*****/", nil)
  353. test("/*", "(anonymous): Line 1:3 Unexpected end of input")
  354. test("#", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  355. test("/**/#", "(anonymous): Line 1:5 Unexpected token ILLEGAL")
  356. test("new +", "(anonymous): Line 1:5 Unexpected token +")
  357. program := test(";", nil)
  358. is(len(program.Body), 1)
  359. is(program.Body[0].(*ast.EmptyStatement).Semicolon, file.Idx(1))
  360. program = test(";;", nil)
  361. is(len(program.Body), 2)
  362. is(program.Body[0].(*ast.EmptyStatement).Semicolon, file.Idx(1))
  363. is(program.Body[1].(*ast.EmptyStatement).Semicolon, file.Idx(2))
  364. program = test("1.2", nil)
  365. is(len(program.Body), 1)
  366. is(program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.NumberLiteral).Literal, "1.2")
  367. program = test("/* */1.2", nil)
  368. is(len(program.Body), 1)
  369. is(program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.NumberLiteral).Literal, "1.2")
  370. program = test("\n", nil)
  371. is(len(program.Body), 0)
  372. test(`
  373. if (0) {
  374. abc = 0
  375. }
  376. else abc = 0
  377. `, nil)
  378. test("if (0) abc = 0 else abc = 0", "(anonymous): Line 1:16 Unexpected token else")
  379. test(`
  380. if (0) {
  381. abc = 0
  382. } else abc = 0
  383. `, nil)
  384. test(`
  385. if (0) {
  386. abc = 1
  387. } else {
  388. }
  389. `, nil)
  390. test(`
  391. do {
  392. } while (true)
  393. `, nil)
  394. test(`
  395. try {
  396. } finally {
  397. }
  398. `, nil)
  399. test(`
  400. try {
  401. } catch (abc) {
  402. } finally {
  403. }
  404. `, nil)
  405. test(`
  406. try {
  407. }
  408. catch (abc) {
  409. }
  410. finally {
  411. }
  412. `, nil)
  413. test(`try {} catch (abc) {} finally {}`, nil)
  414. test("try {} catch {}", nil)
  415. test(`
  416. do {
  417. do {
  418. } while (0)
  419. } while (0)
  420. `, nil)
  421. test(`
  422. (function(){
  423. try {
  424. if (
  425. 1
  426. ) {
  427. return 1
  428. }
  429. return 0
  430. } finally {
  431. }
  432. })()
  433. `, nil)
  434. test("abc = ''\ndef", nil)
  435. test("abc = 1\ndef", nil)
  436. test("abc = Math\ndef", nil)
  437. test(`"\'"`, nil)
  438. test(`
  439. abc = function(){
  440. }
  441. abc = 0
  442. `, nil)
  443. test("abc.null = 0", nil)
  444. test("0x41", nil)
  445. test(`"\d"`, nil)
  446. test(`(function(){return this})`, nil)
  447. test(`
  448. Object.defineProperty(Array.prototype, "0", {
  449. value: 100,
  450. writable: false,
  451. configurable: true
  452. });
  453. abc = [101];
  454. abc.hasOwnProperty("0") && abc[0] === 101;
  455. `, nil)
  456. test(`new abc()`, nil)
  457. test(`new {}`, nil)
  458. test(`
  459. limit = 4
  460. result = 0
  461. while (limit) {
  462. limit = limit - 1
  463. if (limit) {
  464. }
  465. else {
  466. break
  467. }
  468. result = result + 1
  469. }
  470. `, nil)
  471. test(`
  472. while (0) {
  473. if (0) {
  474. continue
  475. }
  476. }
  477. `, nil)
  478. test("var \u0061\u0062\u0063 = 0", nil)
  479. // 7_3_1
  480. test("var test7_3_1\nabc = 66;", nil)
  481. test("var test7_3_1\u2028abc = 66;", nil)
  482. // 7_3_3
  483. test("//\u2028 =;", "(anonymous): Line 2:2 Unexpected token =")
  484. // 7_3_10
  485. test("var abc = \u2029;", "(anonymous): Line 2:1 Unexpected token ;")
  486. test("var abc = \\u2029;", "(anonymous): Line 1:11 Unexpected token ILLEGAL")
  487. test("var \\u0061\\u0062\\u0063 = 0;", nil)
  488. test("'", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  489. test("'\nstr\ning\n'", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  490. // S7.6_A4.3_T1
  491. test(`var $\u0030 = 0;`, nil)
  492. // S7.6.1.1_A1.1
  493. test(`switch = 1`, "(anonymous): Line 1:8 Unexpected token =")
  494. // S7.8.3_A2.1_T1
  495. test(`.0 === 0.0`, nil)
  496. // 7.8.5-1
  497. test("var regExp = /\\\rn/;", "(anonymous): Line 1:14 Invalid regular expression: missing /")
  498. // S7.8.5_A1.1_T2
  499. test("var regExp = /=/;", nil)
  500. // S7.8.5_A1.2_T1
  501. test("/*/", "(anonymous): Line 1:4 Unexpected end of input")
  502. // Sbp_7.9_A9_T3
  503. test(`
  504. do {
  505. ;
  506. } while (false) true
  507. `, nil)
  508. // S7.9_A10_T10
  509. test(`
  510. {a:1
  511. } 3
  512. `, nil)
  513. test(`
  514. abc
  515. ++def
  516. `, nil)
  517. // S7.9_A5.2_T1
  518. test(`
  519. for(false;false
  520. ) {
  521. break;
  522. }
  523. `, "(anonymous): Line 3:13 Unexpected token )")
  524. // S7.9_A9_T8
  525. test(`
  526. do {};
  527. while (false)
  528. `, "(anonymous): Line 2:18 Unexpected token ;")
  529. // S8.4_A5
  530. test(`
  531. "x\0y"
  532. `, nil)
  533. // S9.3.1_A6_T1
  534. test(`
  535. 10e10000
  536. `, nil)
  537. // 10.4.2-1-5
  538. test(`
  539. "abc\
  540. def"
  541. `, nil)
  542. test("'\\\n'", nil)
  543. test("'\\\r\n'", nil)
  544. //// 11.13.1-1-1
  545. test("42 = 42;", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
  546. test("s &^= 42;", "(anonymous): Line 1:4 Unexpected token ^=")
  547. // S11.13.2_A4.2_T1.3
  548. test(`
  549. abc /= "1"
  550. `, nil)
  551. // 12.1-1
  552. test(`
  553. try{};catch(){}
  554. `, "(anonymous): Line 2:13 Missing catch or finally after try")
  555. // 12.1-3
  556. test(`
  557. try{};finally{}
  558. `, "(anonymous): Line 2:13 Missing catch or finally after try")
  559. // S12.6.3_A11.1_T3
  560. test(`
  561. while (true) {
  562. break abc;
  563. }
  564. `, "(anonymous): Line 3:17 Undefined label 'abc'")
  565. // S15.3_A2_T1
  566. test(`var x / = 1;`, "(anonymous): Line 1:7 Unexpected token /")
  567. test(`
  568. function abc() {
  569. if (0)
  570. return;
  571. else {
  572. }
  573. }
  574. `, nil)
  575. test("//\u2028 var =;", "(anonymous): Line 2:6 Unexpected token =")
  576. test(`
  577. throw
  578. {}
  579. `, "(anonymous): Line 2:13 Illegal newline after throw")
  580. // S7.6.1.1_A1.11
  581. test(`
  582. function = 1
  583. `, "(anonymous): Line 2:22 Unexpected token =")
  584. // S7.8.3_A1.2_T1
  585. test(`0e1`, nil)
  586. test("abc = 1; abc\n++", "(anonymous): Line 2:3 Unexpected end of input")
  587. // ---
  588. test("({ get abc() {} })", nil)
  589. test(`for (abc.def in {}) {}`, nil)
  590. test(`while (true) { break }`, nil)
  591. test(`while (true) { continue }`, nil)
  592. test(`abc=/^(?:(\w+:)\/{2}(\w+(?:\.\w+)*\/?)|(.{0,2}\/{1}))?([/.]*?(?:[^?]+)?\/)?((?:[^/?]+)\.(\w+))(?:\?(\S+)?)?$/,def=/^(?:(\w+:)\/{2})|(.{0,2}\/{1})?([/.]*?(?:[^?]+)?\/?)?$/`, nil)
  593. test(`(function() { try {} catch (err) {} finally {} return })`, nil)
  594. test(`0xde0b6b3a7640080.toFixed(0)`, nil)
  595. test(`/[^-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u37f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/`, nil)
  596. test(`/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]/`, nil)
  597. test("var abc = 1;\ufeff", nil)
  598. test("\ufeff/* var abc = 1; */", nil)
  599. test(`if (-0x8000000000000000<=abc&&abc<=0x8000000000000000) {}`, nil)
  600. test(`(function(){debugger;return this;})`, nil)
  601. test(`
  602. `, nil)
  603. test(`
  604. var abc = ""
  605. debugger
  606. `, nil)
  607. test(`
  608. var abc = /\[\]$/
  609. debugger
  610. `, nil)
  611. test(`
  612. var abc = 1 /
  613. 2
  614. debugger
  615. `, nil)
  616. test("'ё\\\u2029'", nil)
  617. test(`[a, b] = [1, 2]`, nil)
  618. test(`({"a b": {}} = {})`, nil)
  619. test(`ref = (a, b = 39,) => {
  620. };`, nil)
  621. test(`(a,) => {}`, nil)
  622. })
  623. }
  624. func TestParseDestruct(t *testing.T) {
  625. parser := newParser("", `({a: (a.b), ...spread,} = {})`)
  626. prg, err := parser.parse()
  627. if err != nil {
  628. t.Fatal(err)
  629. }
  630. _ = prg
  631. }
  632. func Test_parseStringLiteral(t *testing.T) {
  633. tt(t, func() {
  634. test := func(have string, want unistring.String) {
  635. parser := newParser("", have)
  636. parser.read()
  637. parser.read()
  638. _, res, err := parser.scanString(0, true)
  639. is(err, "")
  640. is(res, want)
  641. }
  642. test(`""`, "")
  643. test(`/=/`, "=")
  644. test("'1(\\\\d+)'", "1(\\d+)")
  645. test("'\\u2029'", "\u2029")
  646. test("'abc\\uFFFFabc'", "abc\uFFFFabc")
  647. test("'[First line \\\nSecond line \\\n Third line\\\n. ]'",
  648. "[First line Second line Third line. ]")
  649. test("'\\u007a\\x79\\u000a\\x78'", "zy\nx")
  650. // S7.8.4_A4.2_T3
  651. test("'\\a'", "a")
  652. test("'\u0410'", "\u0410")
  653. // S7.8.4_A5.1_T1
  654. test("'\\0'", "\u0000")
  655. // S8.4_A5
  656. test("'\u0000'", "\u0000")
  657. // 15.5.4.20
  658. test("\"'abc'\\\n'def'\"", "'abc''def'")
  659. // 15.5.4.20-4-1
  660. test("\"'abc'\\\r\n'def'\"", "'abc''def'")
  661. // Octal
  662. test("'\\0'", "\000")
  663. test("'\\00'", "\000")
  664. test("'\\000'", "\000")
  665. test("'\\09'", "\0009")
  666. test("'\\009'", "\0009")
  667. test("'\\0009'", "\0009")
  668. test("'\\1'", "\001")
  669. test("'\\01'", "\001")
  670. test("'\\001'", "\001")
  671. test("'\\0011'", "\0011")
  672. test("'\\1abc'", "\001abc")
  673. test("'\\\u4e16'", "\u4e16")
  674. // err
  675. test = func(have string, want unistring.String) {
  676. parser := newParser("", have)
  677. parser.read()
  678. parser.read()
  679. _, res, err := parser.scanString(0, true)
  680. is(err, want)
  681. is(res, "")
  682. }
  683. test(`"\u"`, `invalid escape: \u: len("") != 4`)
  684. test(`"\u0"`, `invalid escape: \u: len("0") != 4`)
  685. test(`"\u00"`, `invalid escape: \u: len("00") != 4`)
  686. test(`"\u000"`, `invalid escape: \u: len("000") != 4`)
  687. test(`"\x"`, `invalid escape: \x: len("") != 2`)
  688. test(`"\x0"`, `invalid escape: \x: len("0") != 2`)
  689. })
  690. }
  691. func Test_parseNumberLiteral(t *testing.T) {
  692. tt(t, func() {
  693. test := func(input string, expect interface{}) {
  694. result, err := parseNumberLiteral(input)
  695. is(err, nil)
  696. is(result, expect)
  697. }
  698. test("0", 0)
  699. test("0x8000000000000000", float64(9.223372036854776e+18))
  700. })
  701. }
  702. func TestPosition(t *testing.T) {
  703. tt(t, func() {
  704. parser := newParser("", "// Lorem ipsum")
  705. // Out of range, idx0 (error condition)
  706. is(parser.slice(0, 1), "")
  707. is(parser.slice(0, 10), "")
  708. // Out of range, idx1 (error condition)
  709. is(parser.slice(1, 128), "")
  710. is(parser.str[0:0], "")
  711. is(parser.slice(1, 1), "")
  712. is(parser.str[0:1], "/")
  713. is(parser.slice(1, 2), "/")
  714. is(parser.str[0:14], "// Lorem ipsum")
  715. is(parser.slice(1, 15), "// Lorem ipsum")
  716. parser = newParser("", "(function(){ return 0; })")
  717. program, err := parser.parse()
  718. is(err, nil)
  719. var node ast.Node
  720. node = program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral)
  721. is(node.Idx0(), file.Idx(2))
  722. is(node.Idx1(), file.Idx(25))
  723. is(parser.slice(node.Idx0(), node.Idx1()), "function(){ return 0; }")
  724. is(parser.slice(node.Idx0(), node.Idx1()+1), "function(){ return 0; })")
  725. is(parser.slice(node.Idx0(), node.Idx1()+2), "")
  726. is(node.(*ast.FunctionLiteral).Source, "function(){ return 0; }")
  727. node = program
  728. is(node.Idx0(), file.Idx(2))
  729. is(node.Idx1(), file.Idx(25))
  730. is(parser.slice(node.Idx0(), node.Idx1()), "function(){ return 0; }")
  731. parser = newParser("", "(function(){ return abc; })")
  732. program, err = parser.parse()
  733. is(err, nil)
  734. node = program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral)
  735. is(node.(*ast.FunctionLiteral).Source, "function(){ return abc; }")
  736. })
  737. }
  738. func TestExtractSourceMapLine(t *testing.T) {
  739. tt(t, func() {
  740. is(extractSourceMapLine(""), "")
  741. is(extractSourceMapLine("\n"), "")
  742. is(extractSourceMapLine(" "), "")
  743. is(extractSourceMapLine("1\n2\n3\n4\n"), "")
  744. src := `"use strict";
  745. var x = {};
  746. //# sourceMappingURL=delme.js.map`
  747. modSrc := `(function(exports, require, module) {` + src + `
  748. })`
  749. is(extractSourceMapLine(modSrc), "//# sourceMappingURL=delme.js.map")
  750. is(extractSourceMapLine(modSrc+"\n\n\n\n"), "//# sourceMappingURL=delme.js.map")
  751. })
  752. }
  753. func TestSourceMapOptions(t *testing.T) {
  754. tt(t, func() {
  755. count := 0
  756. requestedPath := ""
  757. loader := func(p string) ([]byte, error) {
  758. count++
  759. requestedPath = p
  760. return nil, nil
  761. }
  762. src := `"use strict";
  763. var x = {};
  764. //# sourceMappingURL=delme.js.map`
  765. _, err := ParseFile(nil, "delme.js", src, 0, WithSourceMapLoader(loader))
  766. is(err, nil)
  767. is(count, 1)
  768. is(requestedPath, "delme.js.map")
  769. count = 0
  770. _, err = ParseFile(nil, "", src, 0, WithSourceMapLoader(loader))
  771. is(err, nil)
  772. is(count, 1)
  773. is(requestedPath, "delme.js.map")
  774. count = 0
  775. _, err = ParseFile(nil, "delme.js", src, 0, WithDisableSourceMaps)
  776. is(err, nil)
  777. is(count, 0)
  778. _, err = ParseFile(nil, "/home/user/src/delme.js", src, 0, WithSourceMapLoader(loader))
  779. is(err, nil)
  780. is(count, 1)
  781. is(requestedPath, "/home/user/src/delme.js.map")
  782. count = 0
  783. _, err = ParseFile(nil, "https://site.com/delme.js", src, 0, WithSourceMapLoader(loader))
  784. is(err, nil)
  785. is(count, 1)
  786. is(requestedPath, "https://site.com/delme.js.map")
  787. })
  788. }
  789. func TestParseTemplateCharacters(t *testing.T) {
  790. parser := newParser("", "`test\\\r\\\n${a}`")
  791. parser.next()
  792. if parser.token != token.BACKTICK {
  793. t.Fatalf("Token: %s", parser.token)
  794. }
  795. checkParseTemplateChars := func(expectedLiteral string, expectedParsed unistring.String, expectedFinished, expectParseErr, expectErr bool) {
  796. literal, parsed, finished, parseErr, err := parser.parseTemplateCharacters()
  797. if err != "" != expectErr {
  798. t.Fatal(err)
  799. }
  800. if literal != expectedLiteral {
  801. t.Fatalf("Literal: %q", literal)
  802. }
  803. if parsed != expectedParsed {
  804. t.Fatalf("Parsed: %q", parsed)
  805. }
  806. if finished != expectedFinished {
  807. t.Fatal(finished)
  808. }
  809. if parseErr != "" != expectParseErr {
  810. t.Fatalf("parseErr: %v", parseErr)
  811. }
  812. }
  813. checkParseTemplateChars("test\\\n\\\n", "test", false, false, false)
  814. parser.next()
  815. parser.expect(token.IDENTIFIER)
  816. if len(parser.errors) > 0 {
  817. t.Fatal(parser.errors)
  818. }
  819. if parser.token != token.RIGHT_BRACE {
  820. t.Fatal("Expected }")
  821. }
  822. if len(parser.errors) > 0 {
  823. t.Fatal(parser.errors)
  824. }
  825. checkParseTemplateChars("", "", true, false, false)
  826. if parser.chr != -1 {
  827. t.Fatal("Expected EOF")
  828. }
  829. }
  830. func TestParseTemplateLiteral(t *testing.T) {
  831. parser := newParser("", "f()\n`test${a}`")
  832. prg, err := parser.parse()
  833. if err != nil {
  834. t.Fatal(err)
  835. }
  836. if st, ok := prg.Body[0].(*ast.ExpressionStatement); ok {
  837. if expr, ok := st.Expression.(*ast.TemplateLiteral); ok {
  838. if expr.Tag == nil {
  839. t.Fatal("tag is nil")
  840. }
  841. if idx0 := expr.Tag.Idx0(); idx0 != 1 {
  842. t.Fatalf("Tag.Idx0(): %d", idx0)
  843. }
  844. if expr.OpenQuote != 5 {
  845. t.Fatalf("OpenQuote: %d", expr.OpenQuote)
  846. }
  847. if expr.CloseQuote != 14 {
  848. t.Fatalf("CloseQuote: %d", expr.CloseQuote)
  849. }
  850. if l := len(expr.Elements); l != 2 {
  851. t.Fatalf("len elements: %d", l)
  852. }
  853. if l := len(expr.Expressions); l != 1 {
  854. t.Fatalf("len expressions: %d", l)
  855. }
  856. } else {
  857. t.Fatal(st)
  858. }
  859. } else {
  860. t.Fatal(prg.Body[0])
  861. }
  862. }
  863. func TestParseTemplateLiteralWithTail(t *testing.T) {
  864. parser := newParser("", "f()\n`test${a}tail` ")
  865. prg, err := parser.parse()
  866. if err != nil {
  867. t.Fatal(err)
  868. }
  869. if st, ok := prg.Body[0].(*ast.ExpressionStatement); ok {
  870. if expr, ok := st.Expression.(*ast.TemplateLiteral); ok {
  871. if expr.CloseQuote != 18 {
  872. t.Fatalf("CloseQuote: %d", expr.CloseQuote)
  873. }
  874. } else {
  875. t.Fatal(st)
  876. }
  877. } else {
  878. t.Fatal(prg.Body[0])
  879. }
  880. }