parser_test.go 31 KB

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