parser_test.go 36 KB

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