parser_test.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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. test("`", "(anonymous): Line 1:2 Unexpected end of input")
  316. test(" `", "(anonymous): Line 1:3 Unexpected end of input")
  317. test("` ", "(anonymous): Line 1:3 Unexpected end of input")
  318. })
  319. }
  320. func TestParser(t *testing.T) {
  321. tt(t, func() {
  322. test := func(source string, chk interface{}) *ast.Program {
  323. _, program, err := testParse(source)
  324. is(firstErr(err), chk)
  325. return program
  326. }
  327. test(`new (() => {});`, nil)
  328. test(`
  329. abc
  330. --
  331. []
  332. `, "(anonymous): Line 3:13 Invalid left-hand side in assignment")
  333. test(`
  334. abc--
  335. []
  336. `, nil)
  337. test("1\n[]\n", "(anonymous): Line 2:2 Unexpected token ]")
  338. test(`
  339. function abc() {
  340. }
  341. abc()
  342. `, nil)
  343. test("", nil)
  344. test("//", nil)
  345. test("/* */", nil)
  346. test("/** **/", nil)
  347. test("/*****/", nil)
  348. test("/*", "(anonymous): Line 1:3 Unexpected end of input")
  349. test("#", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  350. test("/**/#", "(anonymous): Line 1:5 Unexpected token ILLEGAL")
  351. test("new +", "(anonymous): Line 1:5 Unexpected token +")
  352. program := test(";", nil)
  353. is(len(program.Body), 1)
  354. is(program.Body[0].(*ast.EmptyStatement).Semicolon, file.Idx(1))
  355. program = test(";;", nil)
  356. is(len(program.Body), 2)
  357. is(program.Body[0].(*ast.EmptyStatement).Semicolon, file.Idx(1))
  358. is(program.Body[1].(*ast.EmptyStatement).Semicolon, file.Idx(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("/* */1.2", nil)
  363. is(len(program.Body), 1)
  364. is(program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.NumberLiteral).Literal, "1.2")
  365. program = test("\n", nil)
  366. is(len(program.Body), 0)
  367. test(`
  368. if (0) {
  369. abc = 0
  370. }
  371. else abc = 0
  372. `, nil)
  373. test("if (0) abc = 0 else abc = 0", "(anonymous): Line 1:16 Unexpected token else")
  374. test(`
  375. if (0) {
  376. abc = 0
  377. } else abc = 0
  378. `, nil)
  379. test(`
  380. if (0) {
  381. abc = 1
  382. } else {
  383. }
  384. `, nil)
  385. test(`
  386. do {
  387. } while (true)
  388. `, nil)
  389. test(`
  390. try {
  391. } finally {
  392. }
  393. `, nil)
  394. test(`
  395. try {
  396. } catch (abc) {
  397. } finally {
  398. }
  399. `, nil)
  400. test(`
  401. try {
  402. }
  403. catch (abc) {
  404. }
  405. finally {
  406. }
  407. `, nil)
  408. test(`try {} catch (abc) {} finally {}`, nil)
  409. test("try {} catch {}", nil)
  410. test(`
  411. do {
  412. do {
  413. } while (0)
  414. } while (0)
  415. `, nil)
  416. test(`
  417. (function(){
  418. try {
  419. if (
  420. 1
  421. ) {
  422. return 1
  423. }
  424. return 0
  425. } finally {
  426. }
  427. })()
  428. `, nil)
  429. test("abc = ''\ndef", nil)
  430. test("abc = 1\ndef", nil)
  431. test("abc = Math\ndef", nil)
  432. test(`"\'"`, nil)
  433. test(`
  434. abc = function(){
  435. }
  436. abc = 0
  437. `, nil)
  438. test("abc.null = 0", nil)
  439. test("0x41", nil)
  440. test(`"\d"`, nil)
  441. test(`(function(){return this})`, nil)
  442. test(`
  443. Object.defineProperty(Array.prototype, "0", {
  444. value: 100,
  445. writable: false,
  446. configurable: true
  447. });
  448. abc = [101];
  449. abc.hasOwnProperty("0") && abc[0] === 101;
  450. `, nil)
  451. test(`new abc()`, nil)
  452. test(`new {}`, nil)
  453. test(`
  454. limit = 4
  455. result = 0
  456. while (limit) {
  457. limit = limit - 1
  458. if (limit) {
  459. }
  460. else {
  461. break
  462. }
  463. result = result + 1
  464. }
  465. `, nil)
  466. test(`
  467. while (0) {
  468. if (0) {
  469. continue
  470. }
  471. }
  472. `, nil)
  473. test("var \u0061\u0062\u0063 = 0", nil)
  474. // 7_3_1
  475. test("var test7_3_1\nabc = 66;", nil)
  476. test("var test7_3_1\u2028abc = 66;", nil)
  477. // 7_3_3
  478. test("//\u2028 =;", "(anonymous): Line 2:2 Unexpected token =")
  479. // 7_3_10
  480. test("var abc = \u2029;", "(anonymous): Line 2:1 Unexpected token ;")
  481. test("var abc = \\u2029;", "(anonymous): Line 1:11 Unexpected token ILLEGAL")
  482. test("var \\u0061\\u0062\\u0063 = 0;", nil)
  483. test("'", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  484. test("'\nstr\ning\n'", "(anonymous): Line 1:1 Unexpected token ILLEGAL")
  485. // S7.6_A4.3_T1
  486. test(`var $\u0030 = 0;`, nil)
  487. // S7.6.1.1_A1.1
  488. test(`switch = 1`, "(anonymous): Line 1:8 Unexpected token =")
  489. // S7.8.3_A2.1_T1
  490. test(`.0 === 0.0`, nil)
  491. // 7.8.5-1
  492. test("var regExp = /\\\rn/;", "(anonymous): Line 1:14 Invalid regular expression: missing /")
  493. // S7.8.5_A1.1_T2
  494. test("var regExp = /=/;", nil)
  495. // S7.8.5_A1.2_T1
  496. test("/*/", "(anonymous): Line 1:4 Unexpected end of input")
  497. // Sbp_7.9_A9_T3
  498. test(`
  499. do {
  500. ;
  501. } while (false) true
  502. `, nil)
  503. // S7.9_A10_T10
  504. test(`
  505. {a:1
  506. } 3
  507. `, nil)
  508. test(`
  509. abc
  510. ++def
  511. `, nil)
  512. // S7.9_A5.2_T1
  513. test(`
  514. for(false;false
  515. ) {
  516. break;
  517. }
  518. `, "(anonymous): Line 3:13 Unexpected token )")
  519. // S7.9_A9_T8
  520. test(`
  521. do {};
  522. while (false)
  523. `, "(anonymous): Line 2:18 Unexpected token ;")
  524. // S8.4_A5
  525. test(`
  526. "x\0y"
  527. `, nil)
  528. // S9.3.1_A6_T1
  529. test(`
  530. 10e10000
  531. `, nil)
  532. // 10.4.2-1-5
  533. test(`
  534. "abc\
  535. def"
  536. `, nil)
  537. test("'\\\n'", nil)
  538. test("'\\\r\n'", nil)
  539. //// 11.13.1-1-1
  540. test("42 = 42;", "(anonymous): Line 1:1 Invalid left-hand side in assignment")
  541. test("s &^= 42;", "(anonymous): Line 1:4 Unexpected token ^=")
  542. // S11.13.2_A4.2_T1.3
  543. test(`
  544. abc /= "1"
  545. `, nil)
  546. // 12.1-1
  547. test(`
  548. try{};catch(){}
  549. `, "(anonymous): Line 2:13 Missing catch or finally after try")
  550. // 12.1-3
  551. test(`
  552. try{};finally{}
  553. `, "(anonymous): Line 2:13 Missing catch or finally after try")
  554. // S12.6.3_A11.1_T3
  555. test(`
  556. while (true) {
  557. break abc;
  558. }
  559. `, "(anonymous): Line 3:17 Undefined label 'abc'")
  560. // S15.3_A2_T1
  561. test(`var x / = 1;`, "(anonymous): Line 1:7 Unexpected token /")
  562. test(`
  563. function abc() {
  564. if (0)
  565. return;
  566. else {
  567. }
  568. }
  569. `, nil)
  570. test("//\u2028 var =;", "(anonymous): Line 2:6 Unexpected token =")
  571. test(`
  572. throw
  573. {}
  574. `, "(anonymous): Line 2:13 Illegal newline after throw")
  575. // S7.6.1.1_A1.11
  576. test(`
  577. function = 1
  578. `, "(anonymous): Line 2:22 Unexpected token =")
  579. // S7.8.3_A1.2_T1
  580. test(`0e1`, nil)
  581. test("abc = 1; abc\n++", "(anonymous): Line 2:3 Unexpected end of input")
  582. // ---
  583. test("({ get abc() {} })", nil)
  584. test(`for (abc.def in {}) {}`, nil)
  585. test(`while (true) { break }`, nil)
  586. test(`while (true) { continue }`, nil)
  587. test(`abc=/^(?:(\w+:)\/{2}(\w+(?:\.\w+)*\/?)|(.{0,2}\/{1}))?([/.]*?(?:[^?]+)?\/)?((?:[^/?]+)\.(\w+))(?:\?(\S+)?)?$/,def=/^(?:(\w+:)\/{2})|(.{0,2}\/{1})?([/.]*?(?:[^?]+)?\/?)?$/`, nil)
  588. test(`(function() { try {} catch (err) {} finally {} return })`, nil)
  589. test(`0xde0b6b3a7640080.toFixed(0)`, nil)
  590. test(`/[^-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u37f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/`, nil)
  591. test(`/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]/`, nil)
  592. test("var abc = 1;\ufeff", nil)
  593. test("\ufeff/* var abc = 1; */", nil)
  594. test(`if (-0x8000000000000000<=abc&&abc<=0x8000000000000000) {}`, nil)
  595. test(`(function(){debugger;return this;})`, nil)
  596. test(`
  597. `, nil)
  598. test(`
  599. var abc = ""
  600. debugger
  601. `, nil)
  602. test(`
  603. var abc = /\[\]$/
  604. debugger
  605. `, nil)
  606. test(`
  607. var abc = 1 /
  608. 2
  609. debugger
  610. `, nil)
  611. test("'ё\\\u2029'", nil)
  612. test(`[a, b] = [1, 2]`, nil)
  613. test(`({"a b": {}} = {})`, nil)
  614. test(`ref = (a, b = 39,) => {
  615. };`, nil)
  616. test(`(a,) => {}`, nil)
  617. })
  618. }
  619. func TestParseDestruct(t *testing.T) {
  620. parser := newParser("", `({a: (a.b), ...spread,} = {})`)
  621. prg, err := parser.parse()
  622. if err != nil {
  623. t.Fatal(err)
  624. }
  625. _ = prg
  626. }
  627. func Test_parseStringLiteral(t *testing.T) {
  628. tt(t, func() {
  629. test := func(have string, want unistring.String) {
  630. parser := newParser("", have)
  631. parser.read()
  632. parser.read()
  633. _, res, err := parser.scanString(0, true)
  634. is(err, "")
  635. is(res, want)
  636. }
  637. test(`""`, "")
  638. test(`/=/`, "=")
  639. test("'1(\\\\d+)'", "1(\\d+)")
  640. test("'\\u2029'", "\u2029")
  641. test("'abc\\uFFFFabc'", "abc\uFFFFabc")
  642. test("'[First line \\\nSecond line \\\n Third line\\\n. ]'",
  643. "[First line Second line Third line. ]")
  644. test("'\\u007a\\x79\\u000a\\x78'", "zy\nx")
  645. // S7.8.4_A4.2_T3
  646. test("'\\a'", "a")
  647. test("'\u0410'", "\u0410")
  648. // S7.8.4_A5.1_T1
  649. test("'\\0'", "\u0000")
  650. // S8.4_A5
  651. test("'\u0000'", "\u0000")
  652. // 15.5.4.20
  653. test("\"'abc'\\\n'def'\"", "'abc''def'")
  654. // 15.5.4.20-4-1
  655. test("\"'abc'\\\r\n'def'\"", "'abc''def'")
  656. // Octal
  657. test("'\\0'", "\000")
  658. test("'\\00'", "\000")
  659. test("'\\000'", "\000")
  660. test("'\\09'", "\0009")
  661. test("'\\009'", "\0009")
  662. test("'\\0009'", "\0009")
  663. test("'\\1'", "\001")
  664. test("'\\01'", "\001")
  665. test("'\\001'", "\001")
  666. test("'\\0011'", "\0011")
  667. test("'\\1abc'", "\001abc")
  668. test("'\\\u4e16'", "\u4e16")
  669. // err
  670. test = func(have string, want unistring.String) {
  671. parser := newParser("", have)
  672. parser.read()
  673. parser.read()
  674. _, res, err := parser.scanString(0, true)
  675. is(err, want)
  676. is(res, "")
  677. }
  678. test(`"\u"`, `invalid escape: \u: len("") != 4`)
  679. test(`"\u0"`, `invalid escape: \u: len("0") != 4`)
  680. test(`"\u00"`, `invalid escape: \u: len("00") != 4`)
  681. test(`"\u000"`, `invalid escape: \u: len("000") != 4`)
  682. test(`"\x"`, `invalid escape: \x: len("") != 2`)
  683. test(`"\x0"`, `invalid escape: \x: len("0") != 2`)
  684. })
  685. }
  686. func Test_parseNumberLiteral(t *testing.T) {
  687. tt(t, func() {
  688. test := func(input string, expect interface{}) {
  689. result, err := parseNumberLiteral(input)
  690. is(err, nil)
  691. is(result, expect)
  692. }
  693. test("0", 0)
  694. test("0x8000000000000000", float64(9.223372036854776e+18))
  695. })
  696. }
  697. func TestPosition(t *testing.T) {
  698. tt(t, func() {
  699. parser := newParser("", "// Lorem ipsum")
  700. // Out of range, idx0 (error condition)
  701. is(parser.slice(0, 1), "")
  702. is(parser.slice(0, 10), "")
  703. // Out of range, idx1 (error condition)
  704. is(parser.slice(1, 128), "")
  705. is(parser.str[0:0], "")
  706. is(parser.slice(1, 1), "")
  707. is(parser.str[0:1], "/")
  708. is(parser.slice(1, 2), "/")
  709. is(parser.str[0:14], "// Lorem ipsum")
  710. is(parser.slice(1, 15), "// Lorem ipsum")
  711. parser = newParser("", "(function(){ return 0; })")
  712. program, err := parser.parse()
  713. is(err, nil)
  714. var node ast.Node
  715. node = program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral)
  716. is(node.Idx0(), file.Idx(2))
  717. is(node.Idx1(), file.Idx(25))
  718. is(parser.slice(node.Idx0(), node.Idx1()), "function(){ return 0; }")
  719. is(parser.slice(node.Idx0(), node.Idx1()+1), "function(){ return 0; })")
  720. is(parser.slice(node.Idx0(), node.Idx1()+2), "")
  721. is(node.(*ast.FunctionLiteral).Source, "function(){ return 0; }")
  722. node = program
  723. is(node.Idx0(), file.Idx(2))
  724. is(node.Idx1(), file.Idx(25))
  725. is(parser.slice(node.Idx0(), node.Idx1()), "function(){ return 0; }")
  726. parser = newParser("", "(function(){ return abc; })")
  727. program, err = parser.parse()
  728. is(err, nil)
  729. node = program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral)
  730. is(node.(*ast.FunctionLiteral).Source, "function(){ return abc; }")
  731. })
  732. }
  733. func TestExtractSourceMapLine(t *testing.T) {
  734. tt(t, func() {
  735. is(extractSourceMapLine(""), "")
  736. is(extractSourceMapLine("\n"), "")
  737. is(extractSourceMapLine(" "), "")
  738. is(extractSourceMapLine("1\n2\n3\n4\n"), "")
  739. src := `"use strict";
  740. var x = {};
  741. //# sourceMappingURL=delme.js.map`
  742. modSrc := `(function(exports, require, module) {` + src + `
  743. })`
  744. is(extractSourceMapLine(modSrc), "//# sourceMappingURL=delme.js.map")
  745. is(extractSourceMapLine(modSrc+"\n\n\n\n"), "//# sourceMappingURL=delme.js.map")
  746. })
  747. }
  748. func TestSourceMapOptions(t *testing.T) {
  749. tt(t, func() {
  750. count := 0
  751. requestedPath := ""
  752. loader := func(p string) ([]byte, error) {
  753. count++
  754. requestedPath = p
  755. return nil, nil
  756. }
  757. src := `"use strict";
  758. var x = {};
  759. //# sourceMappingURL=delme.js.map`
  760. _, err := ParseFile(nil, "delme.js", src, 0, WithSourceMapLoader(loader))
  761. is(err, nil)
  762. is(count, 1)
  763. is(requestedPath, "delme.js.map")
  764. count = 0
  765. _, err = ParseFile(nil, "", 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, "delme.js", src, 0, WithDisableSourceMaps)
  771. is(err, nil)
  772. is(count, 0)
  773. _, err = ParseFile(nil, "/home/user/src/delme.js", src, 0, WithSourceMapLoader(loader))
  774. is(err, nil)
  775. is(count, 1)
  776. is(requestedPath, "/home/user/src/delme.js.map")
  777. count = 0
  778. _, err = ParseFile(nil, "https://site.com/delme.js", src, 0, WithSourceMapLoader(loader))
  779. is(err, nil)
  780. is(count, 1)
  781. is(requestedPath, "https://site.com/delme.js.map")
  782. })
  783. }
  784. func TestParseTemplateCharacters(t *testing.T) {
  785. parser := newParser("", "`test\\\r\\\n${a}`")
  786. parser.next()
  787. if parser.token != token.BACKTICK {
  788. t.Fatalf("Token: %s", parser.token)
  789. }
  790. checkParseTemplateChars := func(expectedLiteral string, expectedParsed unistring.String, expectedFinished, expectParseErr, expectErr bool) {
  791. literal, parsed, finished, parseErr, err := parser.parseTemplateCharacters()
  792. if err != "" != expectErr {
  793. t.Fatal(err)
  794. }
  795. if literal != expectedLiteral {
  796. t.Fatalf("Literal: %q", literal)
  797. }
  798. if parsed != expectedParsed {
  799. t.Fatalf("Parsed: %q", parsed)
  800. }
  801. if finished != expectedFinished {
  802. t.Fatal(finished)
  803. }
  804. if parseErr != "" != expectParseErr {
  805. t.Fatalf("parseErr: %v", parseErr)
  806. }
  807. }
  808. checkParseTemplateChars("test\\\n\\\n", "test", false, false, false)
  809. parser.next()
  810. parser.expect(token.IDENTIFIER)
  811. if len(parser.errors) > 0 {
  812. t.Fatal(parser.errors)
  813. }
  814. if parser.token != token.RIGHT_BRACE {
  815. t.Fatal("Expected }")
  816. }
  817. if len(parser.errors) > 0 {
  818. t.Fatal(parser.errors)
  819. }
  820. checkParseTemplateChars("", "", true, false, false)
  821. if parser.chr != -1 {
  822. t.Fatal("Expected EOF")
  823. }
  824. }
  825. func TestParseTemplateLiteral(t *testing.T) {
  826. parser := newParser("", "f()\n`test${a}`")
  827. prg, err := parser.parse()
  828. if err != nil {
  829. t.Fatal(err)
  830. }
  831. if st, ok := prg.Body[0].(*ast.ExpressionStatement); ok {
  832. if expr, ok := st.Expression.(*ast.TemplateLiteral); ok {
  833. if expr.Tag == nil {
  834. t.Fatal("tag is nil")
  835. }
  836. if idx0 := expr.Tag.Idx0(); idx0 != 1 {
  837. t.Fatalf("Tag.Idx0(): %d", idx0)
  838. }
  839. if expr.OpenQuote != 5 {
  840. t.Fatalf("OpenQuote: %d", expr.OpenQuote)
  841. }
  842. if expr.CloseQuote != 14 {
  843. t.Fatalf("CloseQuote: %d", expr.CloseQuote)
  844. }
  845. if l := len(expr.Elements); l != 2 {
  846. t.Fatalf("len elements: %d", l)
  847. }
  848. if l := len(expr.Expressions); l != 1 {
  849. t.Fatalf("len expressions: %d", l)
  850. }
  851. } else {
  852. t.Fatal(st)
  853. }
  854. } else {
  855. t.Fatal(prg.Body[0])
  856. }
  857. }
  858. func TestParseTemplateLiteralWithTail(t *testing.T) {
  859. parser := newParser("", "f()\n`test${a}tail` ")
  860. prg, err := parser.parse()
  861. if err != nil {
  862. t.Fatal(err)
  863. }
  864. if st, ok := prg.Body[0].(*ast.ExpressionStatement); ok {
  865. if expr, ok := st.Expression.(*ast.TemplateLiteral); ok {
  866. if expr.CloseQuote != 18 {
  867. t.Fatalf("CloseQuote: %d", expr.CloseQuote)
  868. }
  869. } else {
  870. t.Fatal(st)
  871. }
  872. } else {
  873. t.Fatal(prg.Body[0])
  874. }
  875. }