compiler_expr.go 50 KB

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