2
0

compiler_expr.go 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417
  1. package goja
  2. import (
  3. "fmt"
  4. "github.com/dop251/goja/ast"
  5. "github.com/dop251/goja/file"
  6. "github.com/dop251/goja/token"
  7. "github.com/dop251/goja/unistring"
  8. )
  9. type compiledExpr interface {
  10. emitGetter(putOnStack bool)
  11. emitSetter(valueExpr compiledExpr, putOnStack bool)
  12. emitRef()
  13. emitUnary(prepare, body func(), postfix, putOnStack bool)
  14. deleteExpr() compiledExpr
  15. constant() bool
  16. addSrcMap()
  17. }
  18. type compiledExprOrRef interface {
  19. compiledExpr
  20. emitGetterOrRef()
  21. }
  22. type compiledCallExpr struct {
  23. baseCompiledExpr
  24. args []compiledExpr
  25. callee compiledExpr
  26. isVariadic bool
  27. }
  28. type compiledNewExpr struct {
  29. compiledCallExpr
  30. }
  31. type compiledObjectLiteral struct {
  32. baseCompiledExpr
  33. expr *ast.ObjectLiteral
  34. }
  35. type compiledArrayLiteral struct {
  36. baseCompiledExpr
  37. expr *ast.ArrayLiteral
  38. }
  39. type compiledRegexpLiteral struct {
  40. baseCompiledExpr
  41. expr *ast.RegExpLiteral
  42. }
  43. type compiledLiteral struct {
  44. baseCompiledExpr
  45. val Value
  46. }
  47. type compiledTemplateLiteral struct {
  48. baseCompiledExpr
  49. tag compiledExpr
  50. elements []*ast.TemplateElement
  51. expressions []compiledExpr
  52. }
  53. type compiledAssignExpr struct {
  54. baseCompiledExpr
  55. left, right compiledExpr
  56. operator token.Token
  57. }
  58. type compiledObjectAssignmentPattern struct {
  59. baseCompiledExpr
  60. expr *ast.ObjectPattern
  61. }
  62. type compiledArrayAssignmentPattern struct {
  63. baseCompiledExpr
  64. expr *ast.ArrayPattern
  65. }
  66. type deleteGlobalExpr struct {
  67. baseCompiledExpr
  68. name unistring.String
  69. }
  70. type deleteVarExpr struct {
  71. baseCompiledExpr
  72. name unistring.String
  73. }
  74. type deletePropExpr struct {
  75. baseCompiledExpr
  76. left compiledExpr
  77. name unistring.String
  78. }
  79. type deleteElemExpr struct {
  80. baseCompiledExpr
  81. left, member compiledExpr
  82. }
  83. type constantExpr struct {
  84. baseCompiledExpr
  85. val Value
  86. }
  87. type baseCompiledExpr struct {
  88. c *compiler
  89. offset int
  90. }
  91. type compiledIdentifierExpr struct {
  92. baseCompiledExpr
  93. name unistring.String
  94. }
  95. type compiledFunctionLiteral struct {
  96. baseCompiledExpr
  97. name *ast.Identifier
  98. parameterList *ast.ParameterList
  99. body []ast.Statement
  100. source string
  101. declarationList []*ast.VariableDeclaration
  102. lhsName unistring.String
  103. strict *ast.StringLiteral
  104. isExpr bool
  105. isArrow bool
  106. isMethod bool
  107. }
  108. type compiledBracketExpr struct {
  109. baseCompiledExpr
  110. left, member compiledExpr
  111. }
  112. type compiledThisExpr struct {
  113. baseCompiledExpr
  114. }
  115. type compiledNewTarget struct {
  116. baseCompiledExpr
  117. }
  118. type compiledSequenceExpr struct {
  119. baseCompiledExpr
  120. sequence []compiledExpr
  121. }
  122. type compiledUnaryExpr struct {
  123. baseCompiledExpr
  124. operand compiledExpr
  125. operator token.Token
  126. postfix bool
  127. }
  128. type compiledConditionalExpr struct {
  129. baseCompiledExpr
  130. test, consequent, alternate compiledExpr
  131. }
  132. type compiledLogicalOr struct {
  133. baseCompiledExpr
  134. left, right compiledExpr
  135. }
  136. type compiledLogicalAnd struct {
  137. baseCompiledExpr
  138. left, right compiledExpr
  139. }
  140. type compiledBinaryExpr struct {
  141. baseCompiledExpr
  142. left, right compiledExpr
  143. operator token.Token
  144. }
  145. type compiledEnumGetExpr struct {
  146. baseCompiledExpr
  147. }
  148. type defaultDeleteExpr struct {
  149. baseCompiledExpr
  150. expr compiledExpr
  151. }
  152. type compiledSpreadCallArgument struct {
  153. baseCompiledExpr
  154. expr compiledExpr
  155. }
  156. type compiledOptionalChain struct {
  157. baseCompiledExpr
  158. expr compiledExpr
  159. }
  160. type compiledOptional struct {
  161. baseCompiledExpr
  162. expr compiledExpr
  163. }
  164. func (e *defaultDeleteExpr) emitGetter(putOnStack bool) {
  165. e.expr.emitGetter(false)
  166. if putOnStack {
  167. e.c.emit(loadVal(e.c.p.defineLiteralValue(valueTrue)))
  168. }
  169. }
  170. func (c *compiler) compileExpression(v ast.Expression) compiledExpr {
  171. // log.Printf("compileExpression: %T", v)
  172. switch v := v.(type) {
  173. case nil:
  174. return nil
  175. case *ast.AssignExpression:
  176. return c.compileAssignExpression(v)
  177. case *ast.NumberLiteral:
  178. return c.compileNumberLiteral(v)
  179. case *ast.StringLiteral:
  180. return c.compileStringLiteral(v)
  181. case *ast.TemplateLiteral:
  182. return c.compileTemplateLiteral(v)
  183. case *ast.BooleanLiteral:
  184. return c.compileBooleanLiteral(v)
  185. case *ast.NullLiteral:
  186. r := &compiledLiteral{
  187. val: _null,
  188. }
  189. r.init(c, v.Idx0())
  190. return r
  191. case *ast.Identifier:
  192. return c.compileIdentifierExpression(v)
  193. case *ast.CallExpression:
  194. return c.compileCallExpression(v)
  195. case *ast.ObjectLiteral:
  196. return c.compileObjectLiteral(v)
  197. case *ast.ArrayLiteral:
  198. return c.compileArrayLiteral(v)
  199. case *ast.RegExpLiteral:
  200. return c.compileRegexpLiteral(v)
  201. case *ast.BinaryExpression:
  202. return c.compileBinaryExpression(v)
  203. case *ast.UnaryExpression:
  204. return c.compileUnaryExpression(v)
  205. case *ast.ConditionalExpression:
  206. return c.compileConditionalExpression(v)
  207. case *ast.FunctionLiteral:
  208. return c.compileFunctionLiteral(v, true)
  209. case *ast.ArrowFunctionLiteral:
  210. return c.compileArrowFunctionLiteral(v)
  211. case *ast.DotExpression:
  212. r := &compiledDotExpr{
  213. left: c.compileExpression(v.Left),
  214. name: v.Identifier.Name,
  215. }
  216. r.init(c, v.Idx0())
  217. return r
  218. case *ast.BracketExpression:
  219. r := &compiledBracketExpr{
  220. left: c.compileExpression(v.Left),
  221. member: c.compileExpression(v.Member),
  222. }
  223. r.init(c, v.Idx0())
  224. return r
  225. case *ast.ThisExpression:
  226. r := &compiledThisExpr{}
  227. r.init(c, v.Idx0())
  228. return r
  229. case *ast.SequenceExpression:
  230. return c.compileSequenceExpression(v)
  231. case *ast.NewExpression:
  232. return c.compileNewExpression(v)
  233. case *ast.MetaProperty:
  234. return c.compileMetaProperty(v)
  235. case *ast.ObjectPattern:
  236. return c.compileObjectAssignmentPattern(v)
  237. case *ast.ArrayPattern:
  238. return c.compileArrayAssignmentPattern(v)
  239. case *ast.OptionalChain:
  240. r := &compiledOptionalChain{
  241. expr: c.compileExpression(v.Expression),
  242. }
  243. r.init(c, v.Idx0())
  244. return r
  245. case *ast.Optional:
  246. r := &compiledOptional{
  247. expr: c.compileExpression(v.Expression),
  248. }
  249. r.init(c, v.Idx0())
  250. return r
  251. default:
  252. panic(fmt.Errorf("Unknown expression type: %T", v))
  253. }
  254. }
  255. func (e *baseCompiledExpr) constant() bool {
  256. return false
  257. }
  258. func (e *baseCompiledExpr) init(c *compiler, idx file.Idx) {
  259. e.c = c
  260. e.offset = int(idx) - 1
  261. }
  262. func (e *baseCompiledExpr) emitSetter(compiledExpr, bool) {
  263. e.c.throwSyntaxError(e.offset, "Not a valid left-value expression")
  264. }
  265. func (e *baseCompiledExpr) emitRef() {
  266. e.c.throwSyntaxError(e.offset, "Cannot emit reference for this type of expression")
  267. }
  268. func (e *baseCompiledExpr) deleteExpr() compiledExpr {
  269. r := &constantExpr{
  270. val: valueTrue,
  271. }
  272. r.init(e.c, file.Idx(e.offset+1))
  273. return r
  274. }
  275. func (e *baseCompiledExpr) emitUnary(func(), func(), bool, bool) {
  276. e.c.throwSyntaxError(e.offset, "Not a valid left-value expression")
  277. }
  278. func (e *baseCompiledExpr) addSrcMap() {
  279. if e.offset >= 0 {
  280. e.c.p.addSrcMap(e.offset)
  281. }
  282. }
  283. func (e *constantExpr) emitGetter(putOnStack bool) {
  284. if putOnStack {
  285. e.addSrcMap()
  286. e.c.emit(loadVal(e.c.p.defineLiteralValue(e.val)))
  287. }
  288. }
  289. func (e *compiledIdentifierExpr) emitGetter(putOnStack bool) {
  290. e.addSrcMap()
  291. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  292. if b != nil {
  293. if putOnStack {
  294. b.emitGet()
  295. } else {
  296. b.emitGetP()
  297. }
  298. } else {
  299. panic("No dynamics and not found")
  300. }
  301. } else {
  302. if b != nil {
  303. b.emitGetVar(false)
  304. } else {
  305. e.c.emit(loadDynamic(e.name))
  306. }
  307. if !putOnStack {
  308. e.c.emit(pop)
  309. }
  310. }
  311. }
  312. func (e *compiledIdentifierExpr) emitGetterOrRef() {
  313. e.addSrcMap()
  314. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  315. if b != nil {
  316. b.emitGet()
  317. } else {
  318. panic("No dynamics and not found")
  319. }
  320. } else {
  321. if b != nil {
  322. b.emitGetVar(false)
  323. } else {
  324. e.c.emit(loadDynamicRef(e.name))
  325. }
  326. }
  327. }
  328. func (e *compiledIdentifierExpr) emitGetterAndCallee() {
  329. e.addSrcMap()
  330. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  331. if b != nil {
  332. e.c.emit(loadUndef)
  333. b.emitGet()
  334. } else {
  335. panic("No dynamics and not found")
  336. }
  337. } else {
  338. if b != nil {
  339. b.emitGetVar(true)
  340. } else {
  341. e.c.emit(loadDynamicCallee(e.name))
  342. }
  343. }
  344. }
  345. func (e *compiledIdentifierExpr) emitVarSetter1(putOnStack bool, emitRight func(isRef bool)) {
  346. e.addSrcMap()
  347. c := e.c
  348. if b, noDynamics := c.scope.lookupName(e.name); noDynamics {
  349. if c.scope.strict {
  350. c.checkIdentifierLName(e.name, e.offset)
  351. }
  352. emitRight(false)
  353. if b != nil {
  354. if putOnStack {
  355. b.emitSet()
  356. } else {
  357. b.emitSetP()
  358. }
  359. } else {
  360. if c.scope.strict {
  361. c.emit(setGlobalStrict(e.name))
  362. } else {
  363. c.emit(setGlobal(e.name))
  364. }
  365. if !putOnStack {
  366. c.emit(pop)
  367. }
  368. }
  369. } else {
  370. c.emitVarRef(e.name, e.offset, b)
  371. emitRight(true)
  372. if putOnStack {
  373. c.emit(putValue)
  374. } else {
  375. c.emit(putValueP)
  376. }
  377. }
  378. }
  379. func (e *compiledIdentifierExpr) emitVarSetter(valueExpr compiledExpr, putOnStack bool) {
  380. e.emitVarSetter1(putOnStack, func(bool) {
  381. e.c.emitNamedOrConst(valueExpr, e.name)
  382. })
  383. }
  384. func (c *compiler) emitVarRef(name unistring.String, offset int, b *binding) {
  385. if c.scope.strict {
  386. c.checkIdentifierLName(name, offset)
  387. }
  388. if b != nil {
  389. b.emitResolveVar(c.scope.strict)
  390. } else {
  391. if c.scope.strict {
  392. c.emit(resolveVar1Strict(name))
  393. } else {
  394. c.emit(resolveVar1(name))
  395. }
  396. }
  397. }
  398. func (e *compiledIdentifierExpr) emitRef() {
  399. b, _ := e.c.scope.lookupName(e.name)
  400. e.c.emitVarRef(e.name, e.offset, b)
  401. }
  402. func (e *compiledIdentifierExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  403. e.emitVarSetter(valueExpr, putOnStack)
  404. }
  405. func (e *compiledIdentifierExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  406. if putOnStack {
  407. e.emitVarSetter1(true, func(isRef bool) {
  408. e.c.emit(loadUndef)
  409. if isRef {
  410. e.c.emit(getValue)
  411. } else {
  412. e.emitGetter(true)
  413. }
  414. if prepare != nil {
  415. prepare()
  416. }
  417. if !postfix {
  418. body()
  419. }
  420. e.c.emit(rdupN(1))
  421. if postfix {
  422. body()
  423. }
  424. })
  425. e.c.emit(pop)
  426. } else {
  427. e.emitVarSetter1(false, func(isRef bool) {
  428. if isRef {
  429. e.c.emit(getValue)
  430. } else {
  431. e.emitGetter(true)
  432. }
  433. body()
  434. })
  435. }
  436. }
  437. func (e *compiledIdentifierExpr) deleteExpr() compiledExpr {
  438. if e.c.scope.strict {
  439. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  440. panic("Unreachable")
  441. }
  442. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  443. if b == nil {
  444. r := &deleteGlobalExpr{
  445. name: e.name,
  446. }
  447. r.init(e.c, file.Idx(0))
  448. return r
  449. }
  450. } else {
  451. if b == nil {
  452. r := &deleteVarExpr{
  453. name: e.name,
  454. }
  455. r.init(e.c, file.Idx(e.offset+1))
  456. return r
  457. }
  458. }
  459. r := &compiledLiteral{
  460. val: valueFalse,
  461. }
  462. r.init(e.c, file.Idx(e.offset+1))
  463. return r
  464. }
  465. type compiledDotExpr struct {
  466. baseCompiledExpr
  467. left compiledExpr
  468. name unistring.String
  469. }
  470. func (e *compiledDotExpr) emitGetter(putOnStack bool) {
  471. e.left.emitGetter(true)
  472. e.addSrcMap()
  473. e.c.emit(getProp(e.name))
  474. if !putOnStack {
  475. e.c.emit(pop)
  476. }
  477. }
  478. func (e *compiledDotExpr) emitRef() {
  479. e.left.emitGetter(true)
  480. if e.c.scope.strict {
  481. e.c.emit(getPropRefStrict(e.name))
  482. } else {
  483. e.c.emit(getPropRef(e.name))
  484. }
  485. }
  486. func (e *compiledDotExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  487. e.left.emitGetter(true)
  488. valueExpr.emitGetter(true)
  489. if e.c.scope.strict {
  490. if putOnStack {
  491. e.c.emit(setPropStrict(e.name))
  492. } else {
  493. e.c.emit(setPropStrictP(e.name))
  494. }
  495. } else {
  496. if putOnStack {
  497. e.c.emit(setProp(e.name))
  498. } else {
  499. e.c.emit(setPropP(e.name))
  500. }
  501. }
  502. }
  503. func (e *compiledDotExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  504. if !putOnStack {
  505. e.left.emitGetter(true)
  506. e.c.emit(dup)
  507. e.c.emit(getProp(e.name))
  508. body()
  509. if e.c.scope.strict {
  510. e.c.emit(setPropStrict(e.name), pop)
  511. } else {
  512. e.c.emit(setProp(e.name), pop)
  513. }
  514. } else {
  515. if !postfix {
  516. e.left.emitGetter(true)
  517. e.c.emit(dup)
  518. e.c.emit(getProp(e.name))
  519. if prepare != nil {
  520. prepare()
  521. }
  522. body()
  523. if e.c.scope.strict {
  524. e.c.emit(setPropStrict(e.name))
  525. } else {
  526. e.c.emit(setProp(e.name))
  527. }
  528. } else {
  529. e.c.emit(loadUndef)
  530. e.left.emitGetter(true)
  531. e.c.emit(dup)
  532. e.c.emit(getProp(e.name))
  533. if prepare != nil {
  534. prepare()
  535. }
  536. e.c.emit(rdupN(2))
  537. body()
  538. if e.c.scope.strict {
  539. e.c.emit(setPropStrict(e.name))
  540. } else {
  541. e.c.emit(setProp(e.name))
  542. }
  543. e.c.emit(pop)
  544. }
  545. }
  546. }
  547. func (e *compiledDotExpr) deleteExpr() compiledExpr {
  548. r := &deletePropExpr{
  549. left: e.left,
  550. name: e.name,
  551. }
  552. r.init(e.c, file.Idx(0))
  553. return r
  554. }
  555. func (e *compiledBracketExpr) emitGetter(putOnStack bool) {
  556. e.left.emitGetter(true)
  557. e.member.emitGetter(true)
  558. e.addSrcMap()
  559. e.c.emit(getElem)
  560. if !putOnStack {
  561. e.c.emit(pop)
  562. }
  563. }
  564. func (e *compiledBracketExpr) emitRef() {
  565. e.left.emitGetter(true)
  566. e.member.emitGetter(true)
  567. if e.c.scope.strict {
  568. e.c.emit(getElemRefStrict)
  569. } else {
  570. e.c.emit(getElemRef)
  571. }
  572. }
  573. func (e *compiledBracketExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  574. e.left.emitGetter(true)
  575. e.member.emitGetter(true)
  576. valueExpr.emitGetter(true)
  577. if e.c.scope.strict {
  578. if putOnStack {
  579. e.c.emit(setElemStrict)
  580. } else {
  581. e.c.emit(setElemStrictP)
  582. }
  583. } else {
  584. if putOnStack {
  585. e.c.emit(setElem)
  586. } else {
  587. e.c.emit(setElemP)
  588. }
  589. }
  590. }
  591. func (e *compiledBracketExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  592. if !putOnStack {
  593. e.left.emitGetter(true)
  594. e.member.emitGetter(true)
  595. e.c.emit(dupN(1), dupN(1))
  596. e.c.emit(getElem)
  597. body()
  598. if e.c.scope.strict {
  599. e.c.emit(setElemStrict, pop)
  600. } else {
  601. e.c.emit(setElem, pop)
  602. }
  603. } else {
  604. if !postfix {
  605. e.left.emitGetter(true)
  606. e.member.emitGetter(true)
  607. e.c.emit(dupN(1), dupN(1))
  608. e.c.emit(getElem)
  609. if prepare != nil {
  610. prepare()
  611. }
  612. body()
  613. if e.c.scope.strict {
  614. e.c.emit(setElemStrict)
  615. } else {
  616. e.c.emit(setElem)
  617. }
  618. } else {
  619. e.c.emit(loadUndef)
  620. e.left.emitGetter(true)
  621. e.member.emitGetter(true)
  622. e.c.emit(dupN(1), dupN(1))
  623. e.c.emit(getElem)
  624. if prepare != nil {
  625. prepare()
  626. }
  627. e.c.emit(rdupN(3))
  628. body()
  629. if e.c.scope.strict {
  630. e.c.emit(setElemStrict, pop)
  631. } else {
  632. e.c.emit(setElem, pop)
  633. }
  634. }
  635. }
  636. }
  637. func (e *compiledBracketExpr) deleteExpr() compiledExpr {
  638. r := &deleteElemExpr{
  639. left: e.left,
  640. member: e.member,
  641. }
  642. r.init(e.c, file.Idx(0))
  643. return r
  644. }
  645. func (e *deleteElemExpr) emitGetter(putOnStack bool) {
  646. e.left.emitGetter(true)
  647. e.member.emitGetter(true)
  648. e.addSrcMap()
  649. if e.c.scope.strict {
  650. e.c.emit(deleteElemStrict)
  651. } else {
  652. e.c.emit(deleteElem)
  653. }
  654. if !putOnStack {
  655. e.c.emit(pop)
  656. }
  657. }
  658. func (e *deletePropExpr) emitGetter(putOnStack bool) {
  659. e.left.emitGetter(true)
  660. e.addSrcMap()
  661. if e.c.scope.strict {
  662. e.c.emit(deletePropStrict(e.name))
  663. } else {
  664. e.c.emit(deleteProp(e.name))
  665. }
  666. if !putOnStack {
  667. e.c.emit(pop)
  668. }
  669. }
  670. func (e *deleteVarExpr) emitGetter(putOnStack bool) {
  671. /*if e.c.scope.strict {
  672. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  673. return
  674. }*/
  675. e.c.emit(deleteVar(e.name))
  676. if !putOnStack {
  677. e.c.emit(pop)
  678. }
  679. }
  680. func (e *deleteGlobalExpr) emitGetter(putOnStack bool) {
  681. /*if e.c.scope.strict {
  682. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  683. return
  684. }*/
  685. e.c.emit(deleteGlobal(e.name))
  686. if !putOnStack {
  687. e.c.emit(pop)
  688. }
  689. }
  690. func (e *compiledAssignExpr) emitGetter(putOnStack bool) {
  691. switch e.operator {
  692. case token.ASSIGN:
  693. e.left.emitSetter(e.right, putOnStack)
  694. case token.PLUS:
  695. e.left.emitUnary(nil, func() {
  696. e.right.emitGetter(true)
  697. e.c.emit(add)
  698. }, false, putOnStack)
  699. case token.MINUS:
  700. e.left.emitUnary(nil, func() {
  701. e.right.emitGetter(true)
  702. e.c.emit(sub)
  703. }, false, putOnStack)
  704. case token.MULTIPLY:
  705. e.left.emitUnary(nil, func() {
  706. e.right.emitGetter(true)
  707. e.c.emit(mul)
  708. }, false, putOnStack)
  709. case token.SLASH:
  710. e.left.emitUnary(nil, func() {
  711. e.right.emitGetter(true)
  712. e.c.emit(div)
  713. }, false, putOnStack)
  714. case token.REMAINDER:
  715. e.left.emitUnary(nil, func() {
  716. e.right.emitGetter(true)
  717. e.c.emit(mod)
  718. }, false, putOnStack)
  719. case token.OR:
  720. e.left.emitUnary(nil, func() {
  721. e.right.emitGetter(true)
  722. e.c.emit(or)
  723. }, false, putOnStack)
  724. case token.AND:
  725. e.left.emitUnary(nil, func() {
  726. e.right.emitGetter(true)
  727. e.c.emit(and)
  728. }, false, putOnStack)
  729. case token.EXCLUSIVE_OR:
  730. e.left.emitUnary(nil, func() {
  731. e.right.emitGetter(true)
  732. e.c.emit(xor)
  733. }, false, putOnStack)
  734. case token.SHIFT_LEFT:
  735. e.left.emitUnary(nil, func() {
  736. e.right.emitGetter(true)
  737. e.c.emit(sal)
  738. }, false, putOnStack)
  739. case token.SHIFT_RIGHT:
  740. e.left.emitUnary(nil, func() {
  741. e.right.emitGetter(true)
  742. e.c.emit(sar)
  743. }, false, putOnStack)
  744. case token.UNSIGNED_SHIFT_RIGHT:
  745. e.left.emitUnary(nil, func() {
  746. e.right.emitGetter(true)
  747. e.c.emit(shr)
  748. }, false, putOnStack)
  749. default:
  750. panic(fmt.Errorf("Unknown assign operator: %s", e.operator.String()))
  751. }
  752. }
  753. func (e *compiledLiteral) emitGetter(putOnStack bool) {
  754. if putOnStack {
  755. e.c.emit(loadVal(e.c.p.defineLiteralValue(e.val)))
  756. }
  757. }
  758. func (e *compiledLiteral) constant() bool {
  759. return true
  760. }
  761. func (e *compiledTemplateLiteral) emitGetter(putOnStack bool) {
  762. if e.tag == nil {
  763. if len(e.elements) == 0 {
  764. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringEmpty)))
  765. } else {
  766. tail := e.elements[len(e.elements)-1].Parsed
  767. if len(e.elements) == 1 {
  768. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(tail))))
  769. } else {
  770. stringCount := 0
  771. if head := e.elements[0].Parsed; head != "" {
  772. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(head))))
  773. stringCount++
  774. }
  775. e.expressions[0].emitGetter(true)
  776. e.c.emit(_toString{})
  777. stringCount++
  778. for i := 1; i < len(e.elements)-1; i++ {
  779. if elt := e.elements[i].Parsed; elt != "" {
  780. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(elt))))
  781. stringCount++
  782. }
  783. e.expressions[i].emitGetter(true)
  784. e.c.emit(_toString{})
  785. stringCount++
  786. }
  787. if tail != "" {
  788. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(tail))))
  789. stringCount++
  790. }
  791. e.c.emit(concatStrings(stringCount))
  792. }
  793. }
  794. } else {
  795. cooked := make([]Value, len(e.elements))
  796. raw := make([]Value, len(e.elements))
  797. for i, elt := range e.elements {
  798. raw[i] = &valueProperty{
  799. enumerable: true,
  800. value: newStringValue(elt.Literal),
  801. }
  802. var cookedVal Value
  803. if elt.Valid {
  804. cookedVal = stringValueFromRaw(elt.Parsed)
  805. } else {
  806. cookedVal = _undefined
  807. }
  808. cooked[i] = &valueProperty{
  809. enumerable: true,
  810. value: cookedVal,
  811. }
  812. }
  813. e.c.emitCallee(e.tag)
  814. e.c.emit(&getTaggedTmplObject{
  815. raw: raw,
  816. cooked: cooked,
  817. })
  818. for _, expr := range e.expressions {
  819. expr.emitGetter(true)
  820. }
  821. e.c.emit(call(len(e.expressions) + 1))
  822. }
  823. if !putOnStack {
  824. e.c.emit(pop)
  825. }
  826. }
  827. func (c *compiler) compileParameterBindingIdentifier(name unistring.String, offset int) (*binding, bool) {
  828. if c.scope.strict {
  829. c.checkIdentifierName(name, offset)
  830. c.checkIdentifierLName(name, offset)
  831. }
  832. return c.scope.bindNameShadow(name)
  833. }
  834. func (c *compiler) compileParameterPatternIdBinding(name unistring.String, offset int) {
  835. if _, unique := c.compileParameterBindingIdentifier(name, offset); !unique {
  836. c.throwSyntaxError(offset, "Duplicate parameter name not allowed in this context")
  837. }
  838. }
  839. func (c *compiler) compileParameterPatternBinding(item ast.Expression) {
  840. c.createBindings(item, c.compileParameterPatternIdBinding)
  841. }
  842. func (e *compiledFunctionLiteral) emitGetter(putOnStack bool) {
  843. savedPrg := e.c.p
  844. e.c.p = &Program{
  845. src: e.c.p.src,
  846. }
  847. e.c.newScope()
  848. s := e.c.scope
  849. s.function = true
  850. s.arrow = e.isArrow
  851. var name unistring.String
  852. if e.name != nil {
  853. name = e.name.Name
  854. } else {
  855. name = e.lhsName
  856. }
  857. if name != "" {
  858. e.c.p.funcName = name
  859. }
  860. savedBlock := e.c.block
  861. defer func() {
  862. e.c.block = savedBlock
  863. }()
  864. e.c.block = &block{
  865. typ: blockScope,
  866. }
  867. if !s.strict {
  868. s.strict = e.strict != nil
  869. }
  870. hasPatterns := false
  871. hasInits := false
  872. firstDupIdx := -1
  873. length := 0
  874. if e.parameterList.Rest != nil {
  875. hasPatterns = true // strictly speaking not, but we need to activate all the checks
  876. }
  877. // First, make sure that the first bindings correspond to the formal parameters
  878. for _, item := range e.parameterList.List {
  879. switch tgt := item.Target.(type) {
  880. case *ast.Identifier:
  881. offset := int(tgt.Idx) - 1
  882. b, unique := e.c.compileParameterBindingIdentifier(tgt.Name, offset)
  883. if !unique {
  884. firstDupIdx = offset
  885. }
  886. b.isArg = true
  887. case ast.Pattern:
  888. b := s.addBinding(int(item.Idx0()) - 1)
  889. b.isArg = true
  890. hasPatterns = true
  891. default:
  892. e.c.throwSyntaxError(int(item.Idx0())-1, "Unsupported BindingElement type: %T", item)
  893. return
  894. }
  895. if item.Initializer != nil {
  896. hasInits = true
  897. }
  898. if firstDupIdx >= 0 && (hasPatterns || hasInits || s.strict || e.isArrow || e.isMethod) {
  899. e.c.throwSyntaxError(firstDupIdx, "Duplicate parameter name not allowed in this context")
  900. return
  901. }
  902. if (hasPatterns || hasInits) && e.strict != nil {
  903. e.c.throwSyntaxError(int(e.strict.Idx)-1, "Illegal 'use strict' directive in function with non-simple parameter list")
  904. return
  905. }
  906. if !hasInits {
  907. length++
  908. }
  909. }
  910. // create pattern bindings
  911. if hasPatterns {
  912. for _, item := range e.parameterList.List {
  913. switch tgt := item.Target.(type) {
  914. case *ast.Identifier:
  915. // we already created those in the previous loop, skipping
  916. default:
  917. e.c.compileParameterPatternBinding(tgt)
  918. }
  919. }
  920. if rest := e.parameterList.Rest; rest != nil {
  921. e.c.compileParameterPatternBinding(rest)
  922. }
  923. }
  924. paramsCount := len(e.parameterList.List)
  925. s.numArgs = paramsCount
  926. body := e.body
  927. funcs := e.c.extractFunctions(body)
  928. var calleeBinding *binding
  929. preambleLen := 4 // enter, boxThis, createArgs, set
  930. e.c.p.code = make([]instruction, preambleLen, 8)
  931. emitArgsRestMark := -1
  932. firstForwardRef := -1
  933. enterFunc2Mark := -1
  934. if hasPatterns || hasInits {
  935. if e.isExpr && e.name != nil {
  936. if b, created := s.bindNameLexical(e.name.Name, false, 0); created {
  937. b.isConst = true
  938. calleeBinding = b
  939. }
  940. }
  941. if calleeBinding != nil {
  942. e.c.emit(loadCallee)
  943. calleeBinding.emitInit()
  944. }
  945. for i, item := range e.parameterList.List {
  946. if pattern, ok := item.Target.(ast.Pattern); ok {
  947. i := i
  948. e.c.compilePatternInitExpr(func() {
  949. if firstForwardRef == -1 {
  950. s.bindings[i].emitGet()
  951. } else {
  952. e.c.emit(loadStackLex(-i - 1))
  953. }
  954. }, item.Initializer, item.Target.Idx0()).emitGetter(true)
  955. e.c.emitPattern(pattern, func(target, init compiledExpr) {
  956. e.c.emitPatternLexicalAssign(target, init)
  957. }, false)
  958. } else if item.Initializer != nil {
  959. markGet := len(e.c.p.code)
  960. e.c.emit(nil)
  961. mark := len(e.c.p.code)
  962. e.c.emit(nil)
  963. e.c.emitExpr(e.c.compileExpression(item.Initializer), true)
  964. if firstForwardRef == -1 && (s.isDynamic() || s.bindings[i].useCount() > 0) {
  965. firstForwardRef = i
  966. }
  967. if firstForwardRef == -1 {
  968. s.bindings[i].emitGetAt(markGet)
  969. } else {
  970. e.c.p.code[markGet] = loadStackLex(-i - 1)
  971. }
  972. s.bindings[i].emitInit()
  973. e.c.p.code[mark] = jdefP(len(e.c.p.code) - mark)
  974. } else {
  975. if firstForwardRef == -1 && s.bindings[i].useCount() > 0 {
  976. firstForwardRef = i
  977. }
  978. if firstForwardRef != -1 {
  979. e.c.emit(loadStackLex(-i - 1))
  980. s.bindings[i].emitInit()
  981. }
  982. }
  983. }
  984. if rest := e.parameterList.Rest; rest != nil {
  985. e.c.emitAssign(rest, e.c.compileEmitterExpr(
  986. func() {
  987. emitArgsRestMark = len(e.c.p.code)
  988. e.c.emit(createArgsRestStack(paramsCount))
  989. }, rest.Idx0()),
  990. func(target, init compiledExpr) {
  991. e.c.emitPatternLexicalAssign(target, init)
  992. })
  993. }
  994. if firstForwardRef != -1 {
  995. for _, b := range s.bindings {
  996. b.inStash = true
  997. }
  998. s.argsInStash = true
  999. s.needStash = true
  1000. }
  1001. e.c.newBlockScope()
  1002. varScope := e.c.scope
  1003. varScope.variable = true
  1004. enterFunc2Mark = len(e.c.p.code)
  1005. e.c.emit(nil)
  1006. e.c.compileDeclList(e.declarationList, false)
  1007. e.c.createFunctionBindings(funcs)
  1008. e.c.compileLexicalDeclarationsFuncBody(body, calleeBinding)
  1009. for _, b := range varScope.bindings {
  1010. if b.isVar {
  1011. if parentBinding := s.boundNames[b.name]; parentBinding != nil && parentBinding != calleeBinding {
  1012. parentBinding.emitGet()
  1013. b.emitSetP()
  1014. }
  1015. }
  1016. }
  1017. } else {
  1018. // To avoid triggering variable conflict when binding from non-strict direct eval().
  1019. // Parameters are supposed to be in a parent scope, hence no conflict.
  1020. for _, b := range s.bindings[:paramsCount] {
  1021. b.isVar = true
  1022. }
  1023. e.c.compileDeclList(e.declarationList, true)
  1024. e.c.createFunctionBindings(funcs)
  1025. e.c.compileLexicalDeclarations(body, true)
  1026. if e.isExpr && e.name != nil {
  1027. if b, created := s.bindNameLexical(e.name.Name, false, 0); created {
  1028. b.isConst = true
  1029. calleeBinding = b
  1030. }
  1031. }
  1032. if calleeBinding != nil {
  1033. e.c.emit(loadCallee)
  1034. calleeBinding.emitInit()
  1035. }
  1036. }
  1037. e.c.compileFunctions(funcs)
  1038. e.c.compileStatements(body, false)
  1039. var last ast.Statement
  1040. if l := len(body); l > 0 {
  1041. last = body[l-1]
  1042. }
  1043. if _, ok := last.(*ast.ReturnStatement); !ok {
  1044. e.c.emit(loadUndef, ret)
  1045. }
  1046. delta := 0
  1047. code := e.c.p.code
  1048. if calleeBinding != nil && !s.isDynamic() && calleeBinding.useCount() == 1 {
  1049. s.deleteBinding(calleeBinding)
  1050. preambleLen += 2
  1051. }
  1052. if !s.argsInStash && (s.argsNeeded || s.isDynamic()) {
  1053. s.moveArgsToStash()
  1054. }
  1055. if s.argsNeeded {
  1056. b, created := s.bindNameLexical("arguments", false, 0)
  1057. if !created && !b.isVar {
  1058. s.argsNeeded = false
  1059. } else {
  1060. if s.strict {
  1061. b.isConst = true
  1062. } else {
  1063. b.isVar = e.c.scope.function
  1064. }
  1065. pos := preambleLen - 2
  1066. delta += 2
  1067. if s.strict || hasPatterns || hasInits {
  1068. code[pos] = createArgsUnmapped(paramsCount)
  1069. } else {
  1070. code[pos] = createArgsMapped(paramsCount)
  1071. }
  1072. pos++
  1073. b.markAccessPointAtScope(s, pos)
  1074. code[pos] = storeStashP(0)
  1075. }
  1076. }
  1077. stashSize, stackSize := s.finaliseVarAlloc(0)
  1078. if !s.strict && s.thisNeeded {
  1079. delta++
  1080. code[preambleLen-delta] = boxThis
  1081. }
  1082. delta++
  1083. delta = preambleLen - delta
  1084. var enter instruction
  1085. if stashSize > 0 || s.argsInStash {
  1086. if firstForwardRef == -1 {
  1087. enter1 := enterFunc{
  1088. numArgs: uint32(paramsCount),
  1089. argsToStash: s.argsInStash,
  1090. stashSize: uint32(stashSize),
  1091. stackSize: uint32(stackSize),
  1092. extensible: s.dynamic,
  1093. }
  1094. if s.isDynamic() {
  1095. enter1.names = s.makeNamesMap()
  1096. }
  1097. enter = &enter1
  1098. if enterFunc2Mark != -1 {
  1099. ef2 := &enterFuncBody{
  1100. extensible: e.c.scope.dynamic,
  1101. }
  1102. e.c.updateEnterBlock(&ef2.enterBlock)
  1103. e.c.p.code[enterFunc2Mark] = ef2
  1104. }
  1105. } else {
  1106. enter1 := enterFunc1{
  1107. stashSize: uint32(stashSize),
  1108. numArgs: uint32(paramsCount),
  1109. argsToCopy: uint32(firstForwardRef),
  1110. extensible: s.dynamic,
  1111. }
  1112. if s.isDynamic() {
  1113. enter1.names = s.makeNamesMap()
  1114. }
  1115. enter = &enter1
  1116. if enterFunc2Mark != -1 {
  1117. ef2 := &enterFuncBody{
  1118. adjustStack: true,
  1119. extensible: e.c.scope.dynamic,
  1120. }
  1121. e.c.updateEnterBlock(&ef2.enterBlock)
  1122. e.c.p.code[enterFunc2Mark] = ef2
  1123. }
  1124. }
  1125. if emitArgsRestMark != -1 && s.argsInStash {
  1126. e.c.p.code[emitArgsRestMark] = createArgsRestStash
  1127. }
  1128. } else {
  1129. enter = &enterFuncStashless{
  1130. stackSize: uint32(stackSize),
  1131. args: uint32(paramsCount),
  1132. }
  1133. if enterFunc2Mark != -1 {
  1134. ef2 := &enterFuncBody{
  1135. extensible: e.c.scope.dynamic,
  1136. }
  1137. e.c.updateEnterBlock(&ef2.enterBlock)
  1138. e.c.p.code[enterFunc2Mark] = ef2
  1139. }
  1140. }
  1141. code[delta] = enter
  1142. if delta != 0 {
  1143. e.c.p.code = code[delta:]
  1144. for i := range e.c.p.srcMap {
  1145. e.c.p.srcMap[i].pc -= delta
  1146. }
  1147. s.adjustBase(-delta)
  1148. }
  1149. strict := s.strict
  1150. p := e.c.p
  1151. // e.c.p.dumpCode()
  1152. if enterFunc2Mark != -1 {
  1153. e.c.popScope()
  1154. }
  1155. e.c.popScope()
  1156. e.c.p = savedPrg
  1157. if e.isArrow {
  1158. e.c.emit(&newArrowFunc{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}})
  1159. } else {
  1160. if e.isMethod {
  1161. e.c.emit(&newMethod{prg: p, length: length, name: name, source: e.source, strict: strict})
  1162. } else {
  1163. e.c.emit(&newFunc{prg: p, length: length, name: name, source: e.source, strict: strict})
  1164. }
  1165. }
  1166. if !putOnStack {
  1167. e.c.emit(pop)
  1168. }
  1169. }
  1170. func (c *compiler) compileFunctionLiteral(v *ast.FunctionLiteral, isExpr bool) *compiledFunctionLiteral {
  1171. strictBody := c.isStrictStatement(v.Body)
  1172. if v.Name != nil && (c.scope.strict || strictBody != nil) {
  1173. c.checkIdentifierLName(v.Name.Name, int(v.Name.Idx)-1)
  1174. }
  1175. r := &compiledFunctionLiteral{
  1176. name: v.Name,
  1177. parameterList: v.ParameterList,
  1178. body: v.Body.List,
  1179. source: v.Source,
  1180. declarationList: v.DeclarationList,
  1181. isExpr: isExpr,
  1182. strict: strictBody,
  1183. }
  1184. r.init(c, v.Idx0())
  1185. return r
  1186. }
  1187. func (c *compiler) compileArrowFunctionLiteral(v *ast.ArrowFunctionLiteral) *compiledFunctionLiteral {
  1188. var strictBody *ast.StringLiteral
  1189. var body []ast.Statement
  1190. switch b := v.Body.(type) {
  1191. case *ast.BlockStatement:
  1192. strictBody = c.isStrictStatement(b)
  1193. body = b.List
  1194. case *ast.ExpressionBody:
  1195. body = []ast.Statement{
  1196. &ast.ReturnStatement{
  1197. Argument: b.Expression,
  1198. },
  1199. }
  1200. default:
  1201. c.throwSyntaxError(int(b.Idx0())-1, "Unsupported ConciseBody type: %T", b)
  1202. }
  1203. r := &compiledFunctionLiteral{
  1204. parameterList: v.ParameterList,
  1205. body: body,
  1206. source: v.Source,
  1207. declarationList: v.DeclarationList,
  1208. isExpr: true,
  1209. isArrow: true,
  1210. strict: strictBody,
  1211. }
  1212. r.init(c, v.Idx0())
  1213. return r
  1214. }
  1215. func (e *compiledThisExpr) emitGetter(putOnStack bool) {
  1216. if putOnStack {
  1217. e.addSrcMap()
  1218. scope := e.c.scope
  1219. for ; scope != nil && (scope.arrow || !scope.function && !scope.eval); scope = scope.outer {
  1220. }
  1221. if scope != nil {
  1222. scope.thisNeeded = true
  1223. e.c.emit(loadStack(0))
  1224. } else {
  1225. e.c.emit(loadGlobalObject)
  1226. }
  1227. }
  1228. }
  1229. func (e *compiledNewExpr) emitGetter(putOnStack bool) {
  1230. if e.isVariadic {
  1231. e.c.emit(startVariadic)
  1232. }
  1233. e.callee.emitGetter(true)
  1234. for _, expr := range e.args {
  1235. expr.emitGetter(true)
  1236. }
  1237. e.addSrcMap()
  1238. if e.isVariadic {
  1239. e.c.emit(newVariadic, endVariadic)
  1240. } else {
  1241. e.c.emit(_new(len(e.args)))
  1242. }
  1243. if !putOnStack {
  1244. e.c.emit(pop)
  1245. }
  1246. }
  1247. func (c *compiler) compileCallArgs(list []ast.Expression) (args []compiledExpr, isVariadic bool) {
  1248. args = make([]compiledExpr, len(list))
  1249. for i, argExpr := range list {
  1250. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  1251. args[i] = c.compileSpreadCallArgument(spread)
  1252. isVariadic = true
  1253. } else {
  1254. args[i] = c.compileExpression(argExpr)
  1255. }
  1256. }
  1257. return
  1258. }
  1259. func (c *compiler) compileNewExpression(v *ast.NewExpression) compiledExpr {
  1260. args, isVariadic := c.compileCallArgs(v.ArgumentList)
  1261. r := &compiledNewExpr{
  1262. compiledCallExpr: compiledCallExpr{
  1263. callee: c.compileExpression(v.Callee),
  1264. args: args,
  1265. isVariadic: isVariadic,
  1266. },
  1267. }
  1268. r.init(c, v.Idx0())
  1269. return r
  1270. }
  1271. func (e *compiledNewTarget) emitGetter(putOnStack bool) {
  1272. if putOnStack {
  1273. e.addSrcMap()
  1274. e.c.emit(loadNewTarget)
  1275. }
  1276. }
  1277. func (c *compiler) compileMetaProperty(v *ast.MetaProperty) compiledExpr {
  1278. if v.Meta.Name == "new" || v.Property.Name != "target" {
  1279. r := &compiledNewTarget{}
  1280. r.init(c, v.Idx0())
  1281. return r
  1282. }
  1283. c.throwSyntaxError(int(v.Idx)-1, "Unsupported meta property: %s.%s", v.Meta.Name, v.Property.Name)
  1284. return nil
  1285. }
  1286. func (e *compiledSequenceExpr) emitGetter(putOnStack bool) {
  1287. if len(e.sequence) > 0 {
  1288. for i := 0; i < len(e.sequence)-1; i++ {
  1289. e.sequence[i].emitGetter(false)
  1290. }
  1291. e.sequence[len(e.sequence)-1].emitGetter(putOnStack)
  1292. }
  1293. }
  1294. func (c *compiler) compileSequenceExpression(v *ast.SequenceExpression) compiledExpr {
  1295. s := make([]compiledExpr, len(v.Sequence))
  1296. for i, expr := range v.Sequence {
  1297. s[i] = c.compileExpression(expr)
  1298. }
  1299. r := &compiledSequenceExpr{
  1300. sequence: s,
  1301. }
  1302. var idx file.Idx
  1303. if len(v.Sequence) > 0 {
  1304. idx = v.Idx0()
  1305. }
  1306. r.init(c, idx)
  1307. return r
  1308. }
  1309. func (c *compiler) emitThrow(v Value) {
  1310. if o, ok := v.(*Object); ok {
  1311. t := nilSafe(o.self.getStr("name", nil)).toString().String()
  1312. switch t {
  1313. case "TypeError":
  1314. c.emit(loadDynamic(t))
  1315. msg := o.self.getStr("message", nil)
  1316. if msg != nil {
  1317. c.emit(loadVal(c.p.defineLiteralValue(msg)))
  1318. c.emit(_new(1))
  1319. } else {
  1320. c.emit(_new(0))
  1321. }
  1322. c.emit(throw)
  1323. return
  1324. }
  1325. }
  1326. panic(fmt.Errorf("unknown exception type thrown while evaliating constant expression: %s", v.String()))
  1327. }
  1328. func (c *compiler) emitConst(expr compiledExpr, putOnStack bool) {
  1329. v, ex := c.evalConst(expr)
  1330. if ex == nil {
  1331. if putOnStack {
  1332. c.emit(loadVal(c.p.defineLiteralValue(v)))
  1333. }
  1334. } else {
  1335. c.emitThrow(ex.val)
  1336. }
  1337. }
  1338. func (c *compiler) evalConst(expr compiledExpr) (Value, *Exception) {
  1339. if expr, ok := expr.(*compiledLiteral); ok {
  1340. return expr.val, nil
  1341. }
  1342. if c.evalVM == nil {
  1343. c.evalVM = New().vm
  1344. }
  1345. var savedPrg *Program
  1346. createdPrg := false
  1347. if c.evalVM.prg == nil {
  1348. c.evalVM.prg = &Program{}
  1349. savedPrg = c.p
  1350. c.p = c.evalVM.prg
  1351. createdPrg = true
  1352. }
  1353. savedPc := len(c.p.code)
  1354. expr.emitGetter(true)
  1355. c.emit(halt)
  1356. c.evalVM.pc = savedPc
  1357. ex := c.evalVM.runTry()
  1358. if createdPrg {
  1359. c.evalVM.prg = nil
  1360. c.evalVM.pc = 0
  1361. c.p = savedPrg
  1362. } else {
  1363. c.evalVM.prg.code = c.evalVM.prg.code[:savedPc]
  1364. c.p.code = c.evalVM.prg.code
  1365. }
  1366. if ex == nil {
  1367. return c.evalVM.pop(), nil
  1368. }
  1369. return nil, ex
  1370. }
  1371. func (e *compiledUnaryExpr) constant() bool {
  1372. return e.operand.constant()
  1373. }
  1374. func (e *compiledUnaryExpr) emitGetter(putOnStack bool) {
  1375. var prepare, body func()
  1376. toNumber := func() {
  1377. e.addSrcMap()
  1378. e.c.emit(toNumber)
  1379. }
  1380. switch e.operator {
  1381. case token.NOT:
  1382. e.operand.emitGetter(true)
  1383. e.c.emit(not)
  1384. goto end
  1385. case token.BITWISE_NOT:
  1386. e.operand.emitGetter(true)
  1387. e.c.emit(bnot)
  1388. goto end
  1389. case token.TYPEOF:
  1390. if o, ok := e.operand.(compiledExprOrRef); ok {
  1391. o.emitGetterOrRef()
  1392. } else {
  1393. e.operand.emitGetter(true)
  1394. }
  1395. e.c.emit(typeof)
  1396. goto end
  1397. case token.DELETE:
  1398. e.operand.deleteExpr().emitGetter(putOnStack)
  1399. return
  1400. case token.MINUS:
  1401. e.c.emitExpr(e.operand, true)
  1402. e.c.emit(neg)
  1403. goto end
  1404. case token.PLUS:
  1405. e.c.emitExpr(e.operand, true)
  1406. e.c.emit(plus)
  1407. goto end
  1408. case token.INCREMENT:
  1409. prepare = toNumber
  1410. body = func() {
  1411. e.c.emit(inc)
  1412. }
  1413. case token.DECREMENT:
  1414. prepare = toNumber
  1415. body = func() {
  1416. e.c.emit(dec)
  1417. }
  1418. case token.VOID:
  1419. e.c.emitExpr(e.operand, false)
  1420. if putOnStack {
  1421. e.c.emit(loadUndef)
  1422. }
  1423. return
  1424. default:
  1425. panic(fmt.Errorf("Unknown unary operator: %s", e.operator.String()))
  1426. }
  1427. e.operand.emitUnary(prepare, body, e.postfix, putOnStack)
  1428. return
  1429. end:
  1430. if !putOnStack {
  1431. e.c.emit(pop)
  1432. }
  1433. }
  1434. func (c *compiler) compileUnaryExpression(v *ast.UnaryExpression) compiledExpr {
  1435. r := &compiledUnaryExpr{
  1436. operand: c.compileExpression(v.Operand),
  1437. operator: v.Operator,
  1438. postfix: v.Postfix,
  1439. }
  1440. r.init(c, v.Idx0())
  1441. return r
  1442. }
  1443. func (e *compiledConditionalExpr) emitGetter(putOnStack bool) {
  1444. e.test.emitGetter(true)
  1445. j := len(e.c.p.code)
  1446. e.c.emit(nil)
  1447. e.consequent.emitGetter(putOnStack)
  1448. j1 := len(e.c.p.code)
  1449. e.c.emit(nil)
  1450. e.c.p.code[j] = jne(len(e.c.p.code) - j)
  1451. e.alternate.emitGetter(putOnStack)
  1452. e.c.p.code[j1] = jump(len(e.c.p.code) - j1)
  1453. }
  1454. func (c *compiler) compileConditionalExpression(v *ast.ConditionalExpression) compiledExpr {
  1455. r := &compiledConditionalExpr{
  1456. test: c.compileExpression(v.Test),
  1457. consequent: c.compileExpression(v.Consequent),
  1458. alternate: c.compileExpression(v.Alternate),
  1459. }
  1460. r.init(c, v.Idx0())
  1461. return r
  1462. }
  1463. func (e *compiledLogicalOr) constant() bool {
  1464. if e.left.constant() {
  1465. if v, ex := e.c.evalConst(e.left); ex == nil {
  1466. if v.ToBoolean() {
  1467. return true
  1468. }
  1469. return e.right.constant()
  1470. } else {
  1471. return true
  1472. }
  1473. }
  1474. return false
  1475. }
  1476. func (e *compiledLogicalOr) emitGetter(putOnStack bool) {
  1477. if e.left.constant() {
  1478. if v, ex := e.c.evalConst(e.left); ex == nil {
  1479. if !v.ToBoolean() {
  1480. e.c.emitExpr(e.right, putOnStack)
  1481. } else {
  1482. if putOnStack {
  1483. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  1484. }
  1485. }
  1486. } else {
  1487. e.c.emitThrow(ex.val)
  1488. }
  1489. return
  1490. }
  1491. e.c.emitExpr(e.left, true)
  1492. j := len(e.c.p.code)
  1493. e.addSrcMap()
  1494. e.c.emit(nil)
  1495. e.c.emit(pop)
  1496. e.c.emitExpr(e.right, true)
  1497. e.c.p.code[j] = jeq1(len(e.c.p.code) - j)
  1498. if !putOnStack {
  1499. e.c.emit(pop)
  1500. }
  1501. }
  1502. func (e *compiledLogicalAnd) constant() bool {
  1503. if e.left.constant() {
  1504. if v, ex := e.c.evalConst(e.left); ex == nil {
  1505. if !v.ToBoolean() {
  1506. return true
  1507. } else {
  1508. return e.right.constant()
  1509. }
  1510. } else {
  1511. return true
  1512. }
  1513. }
  1514. return false
  1515. }
  1516. func (e *compiledLogicalAnd) emitGetter(putOnStack bool) {
  1517. var j int
  1518. if e.left.constant() {
  1519. if v, ex := e.c.evalConst(e.left); ex == nil {
  1520. if !v.ToBoolean() {
  1521. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  1522. } else {
  1523. e.c.emitExpr(e.right, putOnStack)
  1524. }
  1525. } else {
  1526. e.c.emitThrow(ex.val)
  1527. }
  1528. return
  1529. }
  1530. e.left.emitGetter(true)
  1531. j = len(e.c.p.code)
  1532. e.addSrcMap()
  1533. e.c.emit(nil)
  1534. e.c.emit(pop)
  1535. e.c.emitExpr(e.right, true)
  1536. e.c.p.code[j] = jneq1(len(e.c.p.code) - j)
  1537. if !putOnStack {
  1538. e.c.emit(pop)
  1539. }
  1540. }
  1541. func (e *compiledBinaryExpr) constant() bool {
  1542. return e.left.constant() && e.right.constant()
  1543. }
  1544. func (e *compiledBinaryExpr) emitGetter(putOnStack bool) {
  1545. e.c.emitExpr(e.left, true)
  1546. e.c.emitExpr(e.right, true)
  1547. e.addSrcMap()
  1548. switch e.operator {
  1549. case token.LESS:
  1550. e.c.emit(op_lt)
  1551. case token.GREATER:
  1552. e.c.emit(op_gt)
  1553. case token.LESS_OR_EQUAL:
  1554. e.c.emit(op_lte)
  1555. case token.GREATER_OR_EQUAL:
  1556. e.c.emit(op_gte)
  1557. case token.EQUAL:
  1558. e.c.emit(op_eq)
  1559. case token.NOT_EQUAL:
  1560. e.c.emit(op_neq)
  1561. case token.STRICT_EQUAL:
  1562. e.c.emit(op_strict_eq)
  1563. case token.STRICT_NOT_EQUAL:
  1564. e.c.emit(op_strict_neq)
  1565. case token.PLUS:
  1566. e.c.emit(add)
  1567. case token.MINUS:
  1568. e.c.emit(sub)
  1569. case token.MULTIPLY:
  1570. e.c.emit(mul)
  1571. case token.SLASH:
  1572. e.c.emit(div)
  1573. case token.REMAINDER:
  1574. e.c.emit(mod)
  1575. case token.AND:
  1576. e.c.emit(and)
  1577. case token.OR:
  1578. e.c.emit(or)
  1579. case token.EXCLUSIVE_OR:
  1580. e.c.emit(xor)
  1581. case token.INSTANCEOF:
  1582. e.c.emit(op_instanceof)
  1583. case token.IN:
  1584. e.c.emit(op_in)
  1585. case token.SHIFT_LEFT:
  1586. e.c.emit(sal)
  1587. case token.SHIFT_RIGHT:
  1588. e.c.emit(sar)
  1589. case token.UNSIGNED_SHIFT_RIGHT:
  1590. e.c.emit(shr)
  1591. default:
  1592. panic(fmt.Errorf("Unknown operator: %s", e.operator.String()))
  1593. }
  1594. if !putOnStack {
  1595. e.c.emit(pop)
  1596. }
  1597. }
  1598. func (c *compiler) compileBinaryExpression(v *ast.BinaryExpression) compiledExpr {
  1599. switch v.Operator {
  1600. case token.LOGICAL_OR:
  1601. return c.compileLogicalOr(v.Left, v.Right, v.Idx0())
  1602. case token.LOGICAL_AND:
  1603. return c.compileLogicalAnd(v.Left, v.Right, v.Idx0())
  1604. }
  1605. r := &compiledBinaryExpr{
  1606. left: c.compileExpression(v.Left),
  1607. right: c.compileExpression(v.Right),
  1608. operator: v.Operator,
  1609. }
  1610. r.init(c, v.Idx0())
  1611. return r
  1612. }
  1613. func (c *compiler) compileLogicalOr(left, right ast.Expression, idx file.Idx) compiledExpr {
  1614. r := &compiledLogicalOr{
  1615. left: c.compileExpression(left),
  1616. right: c.compileExpression(right),
  1617. }
  1618. r.init(c, idx)
  1619. return r
  1620. }
  1621. func (c *compiler) compileLogicalAnd(left, right ast.Expression, idx file.Idx) compiledExpr {
  1622. r := &compiledLogicalAnd{
  1623. left: c.compileExpression(left),
  1624. right: c.compileExpression(right),
  1625. }
  1626. r.init(c, idx)
  1627. return r
  1628. }
  1629. func (e *compiledObjectLiteral) emitGetter(putOnStack bool) {
  1630. e.addSrcMap()
  1631. e.c.emit(newObject)
  1632. hasProto := false
  1633. for _, prop := range e.expr.Value {
  1634. switch prop := prop.(type) {
  1635. case *ast.PropertyKeyed:
  1636. keyExpr := e.c.compileExpression(prop.Key)
  1637. computed := false
  1638. var key unistring.String
  1639. switch keyExpr := keyExpr.(type) {
  1640. case *compiledLiteral:
  1641. key = keyExpr.val.string()
  1642. default:
  1643. keyExpr.emitGetter(true)
  1644. computed = true
  1645. }
  1646. valueExpr := e.c.compileExpression(prop.Value)
  1647. var anonFn *compiledFunctionLiteral
  1648. if fn, ok := valueExpr.(*compiledFunctionLiteral); ok {
  1649. if fn.name == nil {
  1650. anonFn = fn
  1651. }
  1652. switch prop.Kind {
  1653. case ast.PropertyKindMethod, ast.PropertyKindGet, ast.PropertyKindSet:
  1654. fn.isMethod = true
  1655. }
  1656. }
  1657. if computed {
  1658. e.c.emit(_toPropertyKey{})
  1659. e.c.emitExpr(valueExpr, true)
  1660. switch prop.Kind {
  1661. case ast.PropertyKindValue, ast.PropertyKindMethod:
  1662. if anonFn != nil {
  1663. e.c.emit(setElem1Named)
  1664. } else {
  1665. e.c.emit(setElem1)
  1666. }
  1667. case ast.PropertyKindGet:
  1668. e.c.emit(setPropGetter1)
  1669. case ast.PropertyKindSet:
  1670. e.c.emit(setPropSetter1)
  1671. default:
  1672. panic(fmt.Errorf("unknown property kind: %s", prop.Kind))
  1673. }
  1674. } else {
  1675. isProto := key == __proto__ && !prop.Computed
  1676. if isProto {
  1677. if hasProto {
  1678. e.c.throwSyntaxError(int(prop.Idx0())-1, "Duplicate __proto__ fields are not allowed in object literals")
  1679. } else {
  1680. hasProto = true
  1681. }
  1682. }
  1683. if anonFn != nil && !isProto {
  1684. anonFn.lhsName = key
  1685. }
  1686. e.c.emitExpr(valueExpr, true)
  1687. switch prop.Kind {
  1688. case ast.PropertyKindValue:
  1689. if isProto {
  1690. e.c.emit(setProto)
  1691. } else {
  1692. e.c.emit(setProp1(key))
  1693. }
  1694. case ast.PropertyKindMethod:
  1695. e.c.emit(setProp1(key))
  1696. case ast.PropertyKindGet:
  1697. e.c.emit(setPropGetter(key))
  1698. case ast.PropertyKindSet:
  1699. e.c.emit(setPropSetter(key))
  1700. default:
  1701. panic(fmt.Errorf("unknown property kind: %s", prop.Kind))
  1702. }
  1703. }
  1704. case *ast.PropertyShort:
  1705. key := prop.Name.Name
  1706. if prop.Initializer != nil {
  1707. e.c.throwSyntaxError(int(prop.Initializer.Idx0())-1, "Invalid shorthand property initializer")
  1708. }
  1709. if e.c.scope.strict && key == "let" {
  1710. e.c.throwSyntaxError(e.offset, "'let' cannot be used as a shorthand property in strict mode")
  1711. }
  1712. e.c.compileIdentifierExpression(&prop.Name).emitGetter(true)
  1713. e.c.emit(setProp1(key))
  1714. case *ast.SpreadElement:
  1715. e.c.compileExpression(prop.Expression).emitGetter(true)
  1716. e.c.emit(copySpread)
  1717. default:
  1718. panic(fmt.Errorf("unknown Property type: %T", prop))
  1719. }
  1720. }
  1721. if !putOnStack {
  1722. e.c.emit(pop)
  1723. }
  1724. }
  1725. func (c *compiler) compileObjectLiteral(v *ast.ObjectLiteral) compiledExpr {
  1726. r := &compiledObjectLiteral{
  1727. expr: v,
  1728. }
  1729. r.init(c, v.Idx0())
  1730. return r
  1731. }
  1732. func (e *compiledArrayLiteral) emitGetter(putOnStack bool) {
  1733. e.addSrcMap()
  1734. hasSpread := false
  1735. mark := len(e.c.p.code)
  1736. e.c.emit(nil)
  1737. for _, v := range e.expr.Value {
  1738. if spread, ok := v.(*ast.SpreadElement); ok {
  1739. hasSpread = true
  1740. e.c.compileExpression(spread.Expression).emitGetter(true)
  1741. e.c.emit(pushArraySpread)
  1742. } else {
  1743. if v != nil {
  1744. e.c.emitExpr(e.c.compileExpression(v), true)
  1745. } else {
  1746. e.c.emit(loadNil)
  1747. }
  1748. e.c.emit(pushArrayItem)
  1749. }
  1750. }
  1751. var objCount uint32
  1752. if !hasSpread {
  1753. objCount = uint32(len(e.expr.Value))
  1754. }
  1755. e.c.p.code[mark] = newArray(objCount)
  1756. if !putOnStack {
  1757. e.c.emit(pop)
  1758. }
  1759. }
  1760. func (c *compiler) compileArrayLiteral(v *ast.ArrayLiteral) compiledExpr {
  1761. r := &compiledArrayLiteral{
  1762. expr: v,
  1763. }
  1764. r.init(c, v.Idx0())
  1765. return r
  1766. }
  1767. func (e *compiledRegexpLiteral) emitGetter(putOnStack bool) {
  1768. if putOnStack {
  1769. pattern, err := compileRegexp(e.expr.Pattern, e.expr.Flags)
  1770. if err != nil {
  1771. e.c.throwSyntaxError(e.offset, err.Error())
  1772. }
  1773. e.c.emit(&newRegexp{pattern: pattern, src: newStringValue(e.expr.Pattern)})
  1774. }
  1775. }
  1776. func (c *compiler) compileRegexpLiteral(v *ast.RegExpLiteral) compiledExpr {
  1777. r := &compiledRegexpLiteral{
  1778. expr: v,
  1779. }
  1780. r.init(c, v.Idx0())
  1781. return r
  1782. }
  1783. func (c *compiler) emitCallee(callee compiledExpr) (calleeName unistring.String) {
  1784. switch callee := callee.(type) {
  1785. case *compiledDotExpr:
  1786. callee.left.emitGetter(true)
  1787. c.emit(dup)
  1788. c.emit(getPropCallee(callee.name))
  1789. case *compiledBracketExpr:
  1790. callee.left.emitGetter(true)
  1791. c.emit(dup)
  1792. callee.member.emitGetter(true)
  1793. c.emit(getElemCallee)
  1794. case *compiledIdentifierExpr:
  1795. calleeName = callee.name
  1796. callee.emitGetterAndCallee()
  1797. case *compiledOptionalChain:
  1798. c.startOptChain()
  1799. c.emitCallee(callee.expr)
  1800. c.endOptChain()
  1801. case *compiledOptional:
  1802. c.emitCallee(callee.expr)
  1803. default:
  1804. c.emit(loadUndef)
  1805. callee.emitGetter(true)
  1806. }
  1807. return
  1808. }
  1809. func (e *compiledCallExpr) emitGetter(putOnStack bool) {
  1810. if e.isVariadic {
  1811. e.c.emit(startVariadic)
  1812. }
  1813. calleeName := e.c.emitCallee(e.callee)
  1814. for _, expr := range e.args {
  1815. expr.emitGetter(true)
  1816. }
  1817. e.addSrcMap()
  1818. if calleeName == "eval" {
  1819. foundFunc, foundVar := false, false
  1820. for sc := e.c.scope; sc != nil; sc = sc.outer {
  1821. if !foundFunc && sc.function && !sc.arrow {
  1822. foundFunc = true
  1823. sc.thisNeeded, sc.argsNeeded = true, true
  1824. }
  1825. if !foundVar && (sc.variable || sc.function) {
  1826. foundVar = true
  1827. if !sc.strict {
  1828. sc.dynamic = true
  1829. }
  1830. }
  1831. sc.dynLookup = true
  1832. }
  1833. if e.c.scope.strict {
  1834. if e.isVariadic {
  1835. e.c.emit(callEvalVariadicStrict)
  1836. } else {
  1837. e.c.emit(callEvalStrict(len(e.args)))
  1838. }
  1839. } else {
  1840. if e.isVariadic {
  1841. e.c.emit(callEvalVariadic)
  1842. } else {
  1843. e.c.emit(callEval(len(e.args)))
  1844. }
  1845. }
  1846. } else {
  1847. if e.isVariadic {
  1848. e.c.emit(callVariadic)
  1849. } else {
  1850. e.c.emit(call(len(e.args)))
  1851. }
  1852. }
  1853. if e.isVariadic {
  1854. e.c.emit(endVariadic)
  1855. }
  1856. if !putOnStack {
  1857. e.c.emit(pop)
  1858. }
  1859. }
  1860. func (e *compiledCallExpr) deleteExpr() compiledExpr {
  1861. r := &defaultDeleteExpr{
  1862. expr: e,
  1863. }
  1864. r.init(e.c, file.Idx(e.offset+1))
  1865. return r
  1866. }
  1867. func (c *compiler) compileSpreadCallArgument(spread *ast.SpreadElement) compiledExpr {
  1868. r := &compiledSpreadCallArgument{
  1869. expr: c.compileExpression(spread.Expression),
  1870. }
  1871. r.init(c, spread.Idx0())
  1872. return r
  1873. }
  1874. func (c *compiler) compileCallExpression(v *ast.CallExpression) compiledExpr {
  1875. args := make([]compiledExpr, len(v.ArgumentList))
  1876. isVariadic := false
  1877. for i, argExpr := range v.ArgumentList {
  1878. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  1879. args[i] = c.compileSpreadCallArgument(spread)
  1880. isVariadic = true
  1881. } else {
  1882. args[i] = c.compileExpression(argExpr)
  1883. }
  1884. }
  1885. r := &compiledCallExpr{
  1886. args: args,
  1887. callee: c.compileExpression(v.Callee),
  1888. isVariadic: isVariadic,
  1889. }
  1890. r.init(c, v.LeftParenthesis)
  1891. return r
  1892. }
  1893. func (c *compiler) compileIdentifierExpression(v *ast.Identifier) compiledExpr {
  1894. if c.scope.strict {
  1895. c.checkIdentifierName(v.Name, int(v.Idx)-1)
  1896. }
  1897. r := &compiledIdentifierExpr{
  1898. name: v.Name,
  1899. }
  1900. r.offset = int(v.Idx) - 1
  1901. r.init(c, v.Idx0())
  1902. return r
  1903. }
  1904. func (c *compiler) compileNumberLiteral(v *ast.NumberLiteral) compiledExpr {
  1905. if c.scope.strict && len(v.Literal) > 1 && v.Literal[0] == '0' && v.Literal[1] <= '7' && v.Literal[1] >= '0' {
  1906. c.throwSyntaxError(int(v.Idx)-1, "Octal literals are not allowed in strict mode")
  1907. panic("Unreachable")
  1908. }
  1909. var val Value
  1910. switch num := v.Value.(type) {
  1911. case int64:
  1912. val = intToValue(num)
  1913. case float64:
  1914. val = floatToValue(num)
  1915. default:
  1916. panic(fmt.Errorf("Unsupported number literal type: %T", v.Value))
  1917. }
  1918. r := &compiledLiteral{
  1919. val: val,
  1920. }
  1921. r.init(c, v.Idx0())
  1922. return r
  1923. }
  1924. func (c *compiler) compileStringLiteral(v *ast.StringLiteral) compiledExpr {
  1925. r := &compiledLiteral{
  1926. val: stringValueFromRaw(v.Value),
  1927. }
  1928. r.init(c, v.Idx0())
  1929. return r
  1930. }
  1931. func (c *compiler) compileTemplateLiteral(v *ast.TemplateLiteral) compiledExpr {
  1932. r := &compiledTemplateLiteral{}
  1933. if v.Tag != nil {
  1934. r.tag = c.compileExpression(v.Tag)
  1935. }
  1936. ce := make([]compiledExpr, len(v.Expressions))
  1937. for i, expr := range v.Expressions {
  1938. ce[i] = c.compileExpression(expr)
  1939. }
  1940. r.expressions = ce
  1941. r.elements = v.Elements
  1942. r.init(c, v.Idx0())
  1943. return r
  1944. }
  1945. func (c *compiler) compileBooleanLiteral(v *ast.BooleanLiteral) compiledExpr {
  1946. var val Value
  1947. if v.Value {
  1948. val = valueTrue
  1949. } else {
  1950. val = valueFalse
  1951. }
  1952. r := &compiledLiteral{
  1953. val: val,
  1954. }
  1955. r.init(c, v.Idx0())
  1956. return r
  1957. }
  1958. func (c *compiler) compileAssignExpression(v *ast.AssignExpression) compiledExpr {
  1959. // log.Printf("compileAssignExpression(): %+v", v)
  1960. r := &compiledAssignExpr{
  1961. left: c.compileExpression(v.Left),
  1962. right: c.compileExpression(v.Right),
  1963. operator: v.Operator,
  1964. }
  1965. r.init(c, v.Idx0())
  1966. return r
  1967. }
  1968. func (e *compiledEnumGetExpr) emitGetter(putOnStack bool) {
  1969. e.c.emit(enumGet)
  1970. if !putOnStack {
  1971. e.c.emit(pop)
  1972. }
  1973. }
  1974. func (c *compiler) compileObjectAssignmentPattern(v *ast.ObjectPattern) compiledExpr {
  1975. r := &compiledObjectAssignmentPattern{
  1976. expr: v,
  1977. }
  1978. r.init(c, v.Idx0())
  1979. return r
  1980. }
  1981. func (e *compiledObjectAssignmentPattern) emitGetter(putOnStack bool) {
  1982. if putOnStack {
  1983. e.c.emit(loadUndef)
  1984. }
  1985. }
  1986. func (c *compiler) compileArrayAssignmentPattern(v *ast.ArrayPattern) compiledExpr {
  1987. r := &compiledArrayAssignmentPattern{
  1988. expr: v,
  1989. }
  1990. r.init(c, v.Idx0())
  1991. return r
  1992. }
  1993. func (e *compiledArrayAssignmentPattern) emitGetter(putOnStack bool) {
  1994. if putOnStack {
  1995. e.c.emit(loadUndef)
  1996. }
  1997. }
  1998. func (c *compiler) emitExpr(expr compiledExpr, putOnStack bool) {
  1999. if expr.constant() {
  2000. c.emitConst(expr, putOnStack)
  2001. } else {
  2002. expr.emitGetter(putOnStack)
  2003. }
  2004. }
  2005. func (c *compiler) emitNamed(expr compiledExpr, name unistring.String) {
  2006. if en, ok := expr.(interface {
  2007. emitNamed(name unistring.String)
  2008. }); ok {
  2009. en.emitNamed(name)
  2010. } else {
  2011. expr.emitGetter(true)
  2012. }
  2013. }
  2014. func (c *compiler) emitNamedOrConst(expr compiledExpr, name unistring.String) {
  2015. if expr.constant() {
  2016. c.emitConst(expr, true)
  2017. } else {
  2018. c.emitNamed(expr, name)
  2019. }
  2020. }
  2021. func (e *compiledFunctionLiteral) emitNamed(name unistring.String) {
  2022. e.lhsName = name
  2023. e.emitGetter(true)
  2024. }
  2025. func (c *compiler) emitPattern(pattern ast.Pattern, emitter func(target, init compiledExpr), putOnStack bool) {
  2026. switch pattern := pattern.(type) {
  2027. case *ast.ObjectPattern:
  2028. c.emitObjectPattern(pattern, emitter, putOnStack)
  2029. case *ast.ArrayPattern:
  2030. c.emitArrayPattern(pattern, emitter, putOnStack)
  2031. default:
  2032. panic(fmt.Errorf("unsupported Pattern: %T", pattern))
  2033. }
  2034. }
  2035. func (c *compiler) emitAssign(target ast.Expression, init compiledExpr, emitAssignSimple func(target, init compiledExpr)) {
  2036. pattern, isPattern := target.(ast.Pattern)
  2037. if isPattern {
  2038. init.emitGetter(true)
  2039. c.emitPattern(pattern, emitAssignSimple, false)
  2040. } else {
  2041. emitAssignSimple(c.compileExpression(target), init)
  2042. }
  2043. }
  2044. func (c *compiler) emitObjectPattern(pattern *ast.ObjectPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  2045. if pattern.Rest != nil {
  2046. c.emit(createDestructSrc)
  2047. } else {
  2048. c.emit(checkObjectCoercible)
  2049. }
  2050. for _, prop := range pattern.Properties {
  2051. switch prop := prop.(type) {
  2052. case *ast.PropertyShort:
  2053. c.emit(dup)
  2054. emitAssign(c.compileIdentifierExpression(&prop.Name), c.compilePatternInitExpr(func() {
  2055. c.emit(getProp(prop.Name.Name))
  2056. }, prop.Initializer, prop.Idx0()))
  2057. case *ast.PropertyKeyed:
  2058. c.emit(dup)
  2059. c.compileExpression(prop.Key).emitGetter(true)
  2060. c.emit(_toPropertyKey{})
  2061. var target ast.Expression
  2062. var initializer ast.Expression
  2063. if e, ok := prop.Value.(*ast.AssignExpression); ok {
  2064. target = e.Left
  2065. initializer = e.Right
  2066. } else {
  2067. target = prop.Value
  2068. }
  2069. c.emitAssign(target, c.compilePatternInitExpr(func() {
  2070. c.emit(getKey)
  2071. }, initializer, prop.Idx0()), emitAssign)
  2072. default:
  2073. c.throwSyntaxError(int(prop.Idx0()-1), "Unsupported AssignmentProperty type: %T", prop)
  2074. }
  2075. }
  2076. if pattern.Rest != nil {
  2077. emitAssign(c.compileExpression(pattern.Rest), c.compileEmitterExpr(func() {
  2078. c.emit(copyRest)
  2079. }, pattern.Rest.Idx0()))
  2080. c.emit(pop)
  2081. }
  2082. if !putOnStack {
  2083. c.emit(pop)
  2084. }
  2085. }
  2086. func (c *compiler) emitArrayPattern(pattern *ast.ArrayPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  2087. c.emit(iterate)
  2088. for _, elt := range pattern.Elements {
  2089. switch elt := elt.(type) {
  2090. case nil:
  2091. c.emit(iterGetNextOrUndef{}, pop)
  2092. case *ast.AssignExpression:
  2093. c.emitAssign(elt.Left, c.compilePatternInitExpr(func() {
  2094. c.emit(iterGetNextOrUndef{})
  2095. }, elt.Right, elt.Idx0()), emitAssign)
  2096. default:
  2097. c.emitAssign(elt, c.compileEmitterExpr(func() {
  2098. c.emit(iterGetNextOrUndef{})
  2099. }, elt.Idx0()), emitAssign)
  2100. }
  2101. }
  2102. if pattern.Rest != nil {
  2103. c.emitAssign(pattern.Rest, c.compileEmitterExpr(func() {
  2104. c.emit(newArrayFromIter)
  2105. }, pattern.Rest.Idx0()), emitAssign)
  2106. } else {
  2107. c.emit(enumPopClose)
  2108. }
  2109. if !putOnStack {
  2110. c.emit(pop)
  2111. }
  2112. }
  2113. func (e *compiledObjectAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  2114. valueExpr.emitGetter(true)
  2115. e.c.emitObjectPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  2116. }
  2117. func (e *compiledArrayAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  2118. valueExpr.emitGetter(true)
  2119. e.c.emitArrayPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  2120. }
  2121. type compiledPatternInitExpr struct {
  2122. baseCompiledExpr
  2123. emitSrc func()
  2124. def compiledExpr
  2125. }
  2126. func (e *compiledPatternInitExpr) emitGetter(putOnStack bool) {
  2127. if !putOnStack {
  2128. return
  2129. }
  2130. e.emitSrc()
  2131. if e.def != nil {
  2132. mark := len(e.c.p.code)
  2133. e.c.emit(nil)
  2134. e.c.emitExpr(e.def, true)
  2135. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  2136. }
  2137. }
  2138. func (e *compiledPatternInitExpr) emitNamed(name unistring.String) {
  2139. e.emitSrc()
  2140. if e.def != nil {
  2141. mark := len(e.c.p.code)
  2142. e.c.emit(nil)
  2143. e.c.emitNamedOrConst(e.def, name)
  2144. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  2145. }
  2146. }
  2147. func (c *compiler) compilePatternInitExpr(emitSrc func(), def ast.Expression, idx file.Idx) compiledExpr {
  2148. r := &compiledPatternInitExpr{
  2149. emitSrc: emitSrc,
  2150. def: c.compileExpression(def),
  2151. }
  2152. r.init(c, idx)
  2153. return r
  2154. }
  2155. type compiledEmitterExpr struct {
  2156. baseCompiledExpr
  2157. emitter func()
  2158. namedEmitter func(name unistring.String)
  2159. }
  2160. func (e *compiledEmitterExpr) emitGetter(putOnStack bool) {
  2161. if e.emitter != nil {
  2162. e.emitter()
  2163. } else {
  2164. e.namedEmitter("")
  2165. }
  2166. if !putOnStack {
  2167. e.c.emit(pop)
  2168. }
  2169. }
  2170. func (e *compiledEmitterExpr) emitNamed(name unistring.String) {
  2171. if e.namedEmitter != nil {
  2172. e.namedEmitter(name)
  2173. } else {
  2174. e.emitter()
  2175. }
  2176. }
  2177. func (c *compiler) compileEmitterExpr(emitter func(), idx file.Idx) *compiledEmitterExpr {
  2178. r := &compiledEmitterExpr{
  2179. emitter: emitter,
  2180. }
  2181. r.init(c, idx)
  2182. return r
  2183. }
  2184. func (e *compiledSpreadCallArgument) emitGetter(putOnStack bool) {
  2185. e.expr.emitGetter(putOnStack)
  2186. if putOnStack {
  2187. e.c.emit(pushSpread)
  2188. }
  2189. }
  2190. func (c *compiler) startOptChain() {
  2191. c.block = &block{
  2192. typ: blockOptChain,
  2193. outer: c.block,
  2194. }
  2195. }
  2196. func (c *compiler) endOptChain() {
  2197. lbl := len(c.p.code)
  2198. for _, item := range c.block.breaks {
  2199. c.p.code[item] = jopt(lbl - item)
  2200. }
  2201. c.block = c.block.outer
  2202. }
  2203. func (e *compiledOptionalChain) emitGetter(putOnStack bool) {
  2204. e.c.startOptChain()
  2205. e.expr.emitGetter(true)
  2206. e.c.endOptChain()
  2207. if !putOnStack {
  2208. e.c.emit(pop)
  2209. }
  2210. }
  2211. func (e *compiledOptional) emitGetter(putOnStack bool) {
  2212. e.expr.emitGetter(putOnStack)
  2213. if putOnStack {
  2214. e.c.block.breaks = append(e.c.block.breaks, len(e.c.p.code))
  2215. e.c.emit(nil)
  2216. }
  2217. }