compiler_expr.go 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553
  1. package goja
  2. import (
  3. "github.com/dop251/goja/ast"
  4. "github.com/dop251/goja/file"
  5. "github.com/dop251/goja/token"
  6. "github.com/dop251/goja/unistring"
  7. )
  8. type compiledExpr interface {
  9. emitGetter(putOnStack bool)
  10. emitSetter(valueExpr compiledExpr, putOnStack bool)
  11. emitRef()
  12. emitUnary(prepare, body func(), postfix, putOnStack bool)
  13. deleteExpr() compiledExpr
  14. constant() bool
  15. addSrcMap()
  16. }
  17. type compiledExprOrRef interface {
  18. compiledExpr
  19. emitGetterOrRef()
  20. }
  21. type compiledCallExpr struct {
  22. baseCompiledExpr
  23. args []compiledExpr
  24. callee compiledExpr
  25. isVariadic bool
  26. }
  27. type compiledNewExpr struct {
  28. compiledCallExpr
  29. }
  30. type compiledObjectLiteral struct {
  31. baseCompiledExpr
  32. expr *ast.ObjectLiteral
  33. }
  34. type compiledArrayLiteral struct {
  35. baseCompiledExpr
  36. expr *ast.ArrayLiteral
  37. }
  38. type compiledRegexpLiteral struct {
  39. baseCompiledExpr
  40. expr *ast.RegExpLiteral
  41. }
  42. type compiledLiteral struct {
  43. baseCompiledExpr
  44. val Value
  45. }
  46. type compiledTemplateLiteral struct {
  47. baseCompiledExpr
  48. tag compiledExpr
  49. elements []*ast.TemplateElement
  50. expressions []compiledExpr
  51. }
  52. type compiledAssignExpr struct {
  53. baseCompiledExpr
  54. left, right compiledExpr
  55. operator token.Token
  56. }
  57. type compiledObjectAssignmentPattern struct {
  58. baseCompiledExpr
  59. expr *ast.ObjectPattern
  60. }
  61. type compiledArrayAssignmentPattern struct {
  62. baseCompiledExpr
  63. expr *ast.ArrayPattern
  64. }
  65. type deleteGlobalExpr struct {
  66. baseCompiledExpr
  67. name unistring.String
  68. }
  69. type deleteVarExpr struct {
  70. baseCompiledExpr
  71. name unistring.String
  72. }
  73. type deletePropExpr struct {
  74. baseCompiledExpr
  75. left compiledExpr
  76. name unistring.String
  77. }
  78. type deleteElemExpr struct {
  79. baseCompiledExpr
  80. left, member compiledExpr
  81. }
  82. type constantExpr struct {
  83. baseCompiledExpr
  84. val Value
  85. }
  86. type baseCompiledExpr struct {
  87. c *compiler
  88. offset int
  89. }
  90. type compiledIdentifierExpr struct {
  91. baseCompiledExpr
  92. name unistring.String
  93. }
  94. type compiledAwaitExpression struct {
  95. baseCompiledExpr
  96. arg compiledExpr
  97. }
  98. type funcType uint8
  99. const (
  100. funcNone funcType = iota
  101. funcRegular
  102. funcArrow
  103. funcMethod
  104. funcClsInit
  105. funcCtor
  106. funcDerivedCtor
  107. )
  108. type compiledFunctionLiteral struct {
  109. baseCompiledExpr
  110. name *ast.Identifier
  111. parameterList *ast.ParameterList
  112. body []ast.Statement
  113. source string
  114. declarationList []*ast.VariableDeclaration
  115. lhsName unistring.String
  116. strict *ast.StringLiteral
  117. homeObjOffset uint32
  118. typ funcType
  119. isExpr bool
  120. isAsync bool
  121. }
  122. type compiledBracketExpr struct {
  123. baseCompiledExpr
  124. left, member compiledExpr
  125. }
  126. type compiledThisExpr struct {
  127. baseCompiledExpr
  128. }
  129. type compiledSuperExpr struct {
  130. baseCompiledExpr
  131. }
  132. type compiledNewTarget struct {
  133. baseCompiledExpr
  134. }
  135. type compiledSequenceExpr struct {
  136. baseCompiledExpr
  137. sequence []compiledExpr
  138. }
  139. type compiledUnaryExpr struct {
  140. baseCompiledExpr
  141. operand compiledExpr
  142. operator token.Token
  143. postfix bool
  144. }
  145. type compiledConditionalExpr struct {
  146. baseCompiledExpr
  147. test, consequent, alternate compiledExpr
  148. }
  149. type compiledLogicalOr struct {
  150. baseCompiledExpr
  151. left, right compiledExpr
  152. }
  153. type compiledCoalesce struct {
  154. baseCompiledExpr
  155. left, right compiledExpr
  156. }
  157. type compiledLogicalAnd struct {
  158. baseCompiledExpr
  159. left, right compiledExpr
  160. }
  161. type compiledBinaryExpr struct {
  162. baseCompiledExpr
  163. left, right compiledExpr
  164. operator token.Token
  165. }
  166. type compiledEnumGetExpr struct {
  167. baseCompiledExpr
  168. }
  169. type defaultDeleteExpr struct {
  170. baseCompiledExpr
  171. expr compiledExpr
  172. }
  173. type compiledSpreadCallArgument struct {
  174. baseCompiledExpr
  175. expr compiledExpr
  176. }
  177. type compiledOptionalChain struct {
  178. baseCompiledExpr
  179. expr compiledExpr
  180. }
  181. type compiledOptional struct {
  182. baseCompiledExpr
  183. expr compiledExpr
  184. }
  185. func (e *defaultDeleteExpr) emitGetter(putOnStack bool) {
  186. e.expr.emitGetter(false)
  187. if putOnStack {
  188. e.c.emit(loadVal(e.c.p.defineLiteralValue(valueTrue)))
  189. }
  190. }
  191. func (c *compiler) compileExpression(v ast.Expression) compiledExpr {
  192. // log.Printf("compileExpression: %T", v)
  193. switch v := v.(type) {
  194. case nil:
  195. return nil
  196. case *ast.AssignExpression:
  197. return c.compileAssignExpression(v)
  198. case *ast.NumberLiteral:
  199. return c.compileNumberLiteral(v)
  200. case *ast.StringLiteral:
  201. return c.compileStringLiteral(v)
  202. case *ast.TemplateLiteral:
  203. return c.compileTemplateLiteral(v)
  204. case *ast.BooleanLiteral:
  205. return c.compileBooleanLiteral(v)
  206. case *ast.NullLiteral:
  207. r := &compiledLiteral{
  208. val: _null,
  209. }
  210. r.init(c, v.Idx0())
  211. return r
  212. case *ast.Identifier:
  213. return c.compileIdentifierExpression(v)
  214. case *ast.CallExpression:
  215. return c.compileCallExpression(v)
  216. case *ast.ObjectLiteral:
  217. return c.compileObjectLiteral(v)
  218. case *ast.ArrayLiteral:
  219. return c.compileArrayLiteral(v)
  220. case *ast.RegExpLiteral:
  221. return c.compileRegexpLiteral(v)
  222. case *ast.BinaryExpression:
  223. return c.compileBinaryExpression(v)
  224. case *ast.UnaryExpression:
  225. return c.compileUnaryExpression(v)
  226. case *ast.ConditionalExpression:
  227. return c.compileConditionalExpression(v)
  228. case *ast.FunctionLiteral:
  229. return c.compileFunctionLiteral(v, true)
  230. case *ast.ArrowFunctionLiteral:
  231. return c.compileArrowFunctionLiteral(v)
  232. case *ast.ClassLiteral:
  233. return c.compileClassLiteral(v, true)
  234. case *ast.DotExpression:
  235. return c.compileDotExpression(v)
  236. case *ast.PrivateDotExpression:
  237. return c.compilePrivateDotExpression(v)
  238. case *ast.BracketExpression:
  239. return c.compileBracketExpression(v)
  240. case *ast.ThisExpression:
  241. r := &compiledThisExpr{}
  242. r.init(c, v.Idx0())
  243. return r
  244. case *ast.SuperExpression:
  245. c.throwSyntaxError(int(v.Idx0())-1, "'super' keyword unexpected here")
  246. panic("unreachable")
  247. case *ast.SequenceExpression:
  248. return c.compileSequenceExpression(v)
  249. case *ast.NewExpression:
  250. return c.compileNewExpression(v)
  251. case *ast.MetaProperty:
  252. return c.compileMetaProperty(v)
  253. case *ast.ObjectPattern:
  254. return c.compileObjectAssignmentPattern(v)
  255. case *ast.ArrayPattern:
  256. return c.compileArrayAssignmentPattern(v)
  257. case *ast.OptionalChain:
  258. r := &compiledOptionalChain{
  259. expr: c.compileExpression(v.Expression),
  260. }
  261. r.init(c, v.Idx0())
  262. return r
  263. case *ast.Optional:
  264. r := &compiledOptional{
  265. expr: c.compileExpression(v.Expression),
  266. }
  267. r.init(c, v.Idx0())
  268. return r
  269. case *ast.AwaitExpression:
  270. r := &compiledAwaitExpression{
  271. arg: c.compileExpression(v.Argument),
  272. }
  273. r.init(c, v.Await)
  274. return r
  275. default:
  276. c.assert(false, int(v.Idx0())-1, "Unknown expression type: %T", v)
  277. panic("unreachable")
  278. }
  279. }
  280. func (e *baseCompiledExpr) constant() bool {
  281. return false
  282. }
  283. func (e *baseCompiledExpr) init(c *compiler, idx file.Idx) {
  284. e.c = c
  285. e.offset = int(idx) - 1
  286. }
  287. func (e *baseCompiledExpr) emitSetter(compiledExpr, bool) {
  288. e.c.throwSyntaxError(e.offset, "Not a valid left-value expression")
  289. }
  290. func (e *baseCompiledExpr) emitRef() {
  291. e.c.assert(false, e.offset, "Cannot emit reference for this type of expression")
  292. }
  293. func (e *baseCompiledExpr) deleteExpr() compiledExpr {
  294. r := &constantExpr{
  295. val: valueTrue,
  296. }
  297. r.init(e.c, file.Idx(e.offset+1))
  298. return r
  299. }
  300. func (e *baseCompiledExpr) emitUnary(func(), func(), bool, bool) {
  301. e.c.throwSyntaxError(e.offset, "Not a valid left-value expression")
  302. }
  303. func (e *baseCompiledExpr) addSrcMap() {
  304. if e.offset >= 0 {
  305. e.c.p.addSrcMap(e.offset)
  306. }
  307. }
  308. func (e *constantExpr) emitGetter(putOnStack bool) {
  309. if putOnStack {
  310. e.addSrcMap()
  311. e.c.emit(loadVal(e.c.p.defineLiteralValue(e.val)))
  312. }
  313. }
  314. func (e *compiledIdentifierExpr) emitGetter(putOnStack bool) {
  315. e.addSrcMap()
  316. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  317. e.c.assert(b != nil, e.offset, "No dynamics and not found")
  318. if putOnStack {
  319. b.emitGet()
  320. } else {
  321. b.emitGetP()
  322. }
  323. } else {
  324. if b != nil {
  325. b.emitGetVar(false)
  326. } else {
  327. e.c.emit(loadDynamic(e.name))
  328. }
  329. if !putOnStack {
  330. e.c.emit(pop)
  331. }
  332. }
  333. }
  334. func (e *compiledIdentifierExpr) emitGetterOrRef() {
  335. e.addSrcMap()
  336. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  337. e.c.assert(b != nil, e.offset, "No dynamics and not found")
  338. b.emitGet()
  339. } else {
  340. if b != nil {
  341. b.emitGetVar(false)
  342. } else {
  343. e.c.emit(loadDynamicRef(e.name))
  344. }
  345. }
  346. }
  347. func (e *compiledIdentifierExpr) emitGetterAndCallee() {
  348. e.addSrcMap()
  349. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  350. e.c.assert(b != nil, e.offset, "No dynamics and not found")
  351. e.c.emit(loadUndef)
  352. b.emitGet()
  353. } else {
  354. if b != nil {
  355. b.emitGetVar(true)
  356. } else {
  357. e.c.emit(loadDynamicCallee(e.name))
  358. }
  359. }
  360. }
  361. func (e *compiledIdentifierExpr) emitVarSetter1(putOnStack bool, emitRight func(isRef bool)) {
  362. e.addSrcMap()
  363. c := e.c
  364. if b, noDynamics := c.scope.lookupName(e.name); noDynamics {
  365. if c.scope.strict {
  366. c.checkIdentifierLName(e.name, e.offset)
  367. }
  368. emitRight(false)
  369. if b != nil {
  370. if putOnStack {
  371. b.emitSet()
  372. } else {
  373. b.emitSetP()
  374. }
  375. } else {
  376. if c.scope.strict {
  377. c.emit(setGlobalStrict(e.name))
  378. } else {
  379. c.emit(setGlobal(e.name))
  380. }
  381. if !putOnStack {
  382. c.emit(pop)
  383. }
  384. }
  385. } else {
  386. c.emitVarRef(e.name, e.offset, b)
  387. emitRight(true)
  388. if putOnStack {
  389. c.emit(putValue)
  390. } else {
  391. c.emit(putValueP)
  392. }
  393. }
  394. }
  395. func (e *compiledIdentifierExpr) emitVarSetter(valueExpr compiledExpr, putOnStack bool) {
  396. e.emitVarSetter1(putOnStack, func(bool) {
  397. e.c.emitNamedOrConst(valueExpr, e.name)
  398. })
  399. }
  400. func (c *compiler) emitVarRef(name unistring.String, offset int, b *binding) {
  401. if c.scope.strict {
  402. c.checkIdentifierLName(name, offset)
  403. }
  404. if b != nil {
  405. b.emitResolveVar(c.scope.strict)
  406. } else {
  407. if c.scope.strict {
  408. c.emit(resolveVar1Strict(name))
  409. } else {
  410. c.emit(resolveVar1(name))
  411. }
  412. }
  413. }
  414. func (e *compiledIdentifierExpr) emitRef() {
  415. b, _ := e.c.scope.lookupName(e.name)
  416. e.c.emitVarRef(e.name, e.offset, b)
  417. }
  418. func (e *compiledIdentifierExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  419. e.emitVarSetter(valueExpr, putOnStack)
  420. }
  421. func (e *compiledIdentifierExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  422. if putOnStack {
  423. e.emitVarSetter1(true, func(isRef bool) {
  424. e.c.emit(loadUndef)
  425. if isRef {
  426. e.c.emit(getValue)
  427. } else {
  428. e.emitGetter(true)
  429. }
  430. if prepare != nil {
  431. prepare()
  432. }
  433. if !postfix {
  434. body()
  435. }
  436. e.c.emit(rdupN(1))
  437. if postfix {
  438. body()
  439. }
  440. })
  441. e.c.emit(pop)
  442. } else {
  443. e.emitVarSetter1(false, func(isRef bool) {
  444. if isRef {
  445. e.c.emit(getValue)
  446. } else {
  447. e.emitGetter(true)
  448. }
  449. body()
  450. })
  451. }
  452. }
  453. func (e *compiledIdentifierExpr) deleteExpr() compiledExpr {
  454. if e.c.scope.strict {
  455. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  456. panic("Unreachable")
  457. }
  458. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  459. if b == nil {
  460. r := &deleteGlobalExpr{
  461. name: e.name,
  462. }
  463. r.init(e.c, file.Idx(0))
  464. return r
  465. }
  466. } else {
  467. if b == nil {
  468. r := &deleteVarExpr{
  469. name: e.name,
  470. }
  471. r.init(e.c, file.Idx(e.offset+1))
  472. return r
  473. }
  474. }
  475. r := &compiledLiteral{
  476. val: valueFalse,
  477. }
  478. r.init(e.c, file.Idx(e.offset+1))
  479. return r
  480. }
  481. type compiledSuperDotExpr struct {
  482. baseCompiledExpr
  483. name unistring.String
  484. }
  485. func (e *compiledSuperDotExpr) emitGetter(putOnStack bool) {
  486. e.c.emitLoadThis()
  487. e.c.emit(loadSuper)
  488. e.addSrcMap()
  489. e.c.emit(getPropRecv(e.name))
  490. if !putOnStack {
  491. e.c.emit(pop)
  492. }
  493. }
  494. func (e *compiledSuperDotExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  495. e.c.emitLoadThis()
  496. e.c.emit(loadSuper)
  497. valueExpr.emitGetter(true)
  498. e.addSrcMap()
  499. if putOnStack {
  500. if e.c.scope.strict {
  501. e.c.emit(setPropRecvStrict(e.name))
  502. } else {
  503. e.c.emit(setPropRecv(e.name))
  504. }
  505. } else {
  506. if e.c.scope.strict {
  507. e.c.emit(setPropRecvStrictP(e.name))
  508. } else {
  509. e.c.emit(setPropRecvP(e.name))
  510. }
  511. }
  512. }
  513. func (e *compiledSuperDotExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  514. if !putOnStack {
  515. e.c.emitLoadThis()
  516. e.c.emit(loadSuper, dupLast(2), getPropRecv(e.name))
  517. body()
  518. e.addSrcMap()
  519. if e.c.scope.strict {
  520. e.c.emit(setPropRecvStrictP(e.name))
  521. } else {
  522. e.c.emit(setPropRecvP(e.name))
  523. }
  524. } else {
  525. if !postfix {
  526. e.c.emitLoadThis()
  527. e.c.emit(loadSuper, dupLast(2), getPropRecv(e.name))
  528. if prepare != nil {
  529. prepare()
  530. }
  531. body()
  532. e.addSrcMap()
  533. if e.c.scope.strict {
  534. e.c.emit(setPropRecvStrict(e.name))
  535. } else {
  536. e.c.emit(setPropRecv(e.name))
  537. }
  538. } else {
  539. e.c.emit(loadUndef)
  540. e.c.emitLoadThis()
  541. e.c.emit(loadSuper, dupLast(2), getPropRecv(e.name))
  542. if prepare != nil {
  543. prepare()
  544. }
  545. e.c.emit(rdupN(3))
  546. body()
  547. e.addSrcMap()
  548. if e.c.scope.strict {
  549. e.c.emit(setPropRecvStrictP(e.name))
  550. } else {
  551. e.c.emit(setPropRecvP(e.name))
  552. }
  553. }
  554. }
  555. }
  556. func (e *compiledSuperDotExpr) emitRef() {
  557. e.c.emitLoadThis()
  558. e.c.emit(loadSuper)
  559. if e.c.scope.strict {
  560. e.c.emit(getPropRefRecvStrict(e.name))
  561. } else {
  562. e.c.emit(getPropRefRecv(e.name))
  563. }
  564. }
  565. func (e *compiledSuperDotExpr) deleteExpr() compiledExpr {
  566. return e.c.superDeleteError(e.offset)
  567. }
  568. type compiledDotExpr struct {
  569. baseCompiledExpr
  570. left compiledExpr
  571. name unistring.String
  572. }
  573. type compiledPrivateDotExpr struct {
  574. baseCompiledExpr
  575. left compiledExpr
  576. name unistring.String
  577. }
  578. func (c *compiler) checkSuperBase(idx file.Idx) {
  579. if s := c.scope.nearestThis(); s != nil {
  580. switch s.funcType {
  581. case funcMethod, funcClsInit, funcCtor, funcDerivedCtor:
  582. return
  583. }
  584. }
  585. c.throwSyntaxError(int(idx)-1, "'super' keyword unexpected here")
  586. panic("unreachable")
  587. }
  588. func (c *compiler) compileDotExpression(v *ast.DotExpression) compiledExpr {
  589. if sup, ok := v.Left.(*ast.SuperExpression); ok {
  590. c.checkSuperBase(sup.Idx)
  591. r := &compiledSuperDotExpr{
  592. name: v.Identifier.Name,
  593. }
  594. r.init(c, v.Identifier.Idx)
  595. return r
  596. }
  597. r := &compiledDotExpr{
  598. left: c.compileExpression(v.Left),
  599. name: v.Identifier.Name,
  600. }
  601. r.init(c, v.Identifier.Idx)
  602. return r
  603. }
  604. func (c *compiler) compilePrivateDotExpression(v *ast.PrivateDotExpression) compiledExpr {
  605. r := &compiledPrivateDotExpr{
  606. left: c.compileExpression(v.Left),
  607. name: v.Identifier.Name,
  608. }
  609. r.init(c, v.Identifier.Idx)
  610. return r
  611. }
  612. func (e *compiledPrivateDotExpr) _emitGetter(rn *resolvedPrivateName, id *privateId) {
  613. if rn != nil {
  614. e.c.emit((*getPrivatePropRes)(rn))
  615. } else {
  616. e.c.emit((*getPrivatePropId)(id))
  617. }
  618. }
  619. func (e *compiledPrivateDotExpr) _emitSetter(rn *resolvedPrivateName, id *privateId) {
  620. if rn != nil {
  621. e.c.emit((*setPrivatePropRes)(rn))
  622. } else {
  623. e.c.emit((*setPrivatePropId)(id))
  624. }
  625. }
  626. func (e *compiledPrivateDotExpr) _emitSetterP(rn *resolvedPrivateName, id *privateId) {
  627. if rn != nil {
  628. e.c.emit((*setPrivatePropResP)(rn))
  629. } else {
  630. e.c.emit((*setPrivatePropIdP)(id))
  631. }
  632. }
  633. func (e *compiledPrivateDotExpr) emitGetter(putOnStack bool) {
  634. e.left.emitGetter(true)
  635. e.addSrcMap()
  636. rn, id := e.c.resolvePrivateName(e.name, e.offset)
  637. e._emitGetter(rn, id)
  638. if !putOnStack {
  639. e.c.emit(pop)
  640. }
  641. }
  642. func (e *compiledPrivateDotExpr) emitSetter(v compiledExpr, putOnStack bool) {
  643. rn, id := e.c.resolvePrivateName(e.name, e.offset)
  644. e.left.emitGetter(true)
  645. v.emitGetter(true)
  646. e.addSrcMap()
  647. if putOnStack {
  648. e._emitSetter(rn, id)
  649. } else {
  650. e._emitSetterP(rn, id)
  651. }
  652. }
  653. func (e *compiledPrivateDotExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  654. rn, id := e.c.resolvePrivateName(e.name, e.offset)
  655. if !putOnStack {
  656. e.left.emitGetter(true)
  657. e.c.emit(dup)
  658. e._emitGetter(rn, id)
  659. body()
  660. e.addSrcMap()
  661. e._emitSetterP(rn, id)
  662. } else {
  663. if !postfix {
  664. e.left.emitGetter(true)
  665. e.c.emit(dup)
  666. e._emitGetter(rn, id)
  667. if prepare != nil {
  668. prepare()
  669. }
  670. body()
  671. e.addSrcMap()
  672. e._emitSetter(rn, id)
  673. } else {
  674. e.c.emit(loadUndef)
  675. e.left.emitGetter(true)
  676. e.c.emit(dup)
  677. e._emitGetter(rn, id)
  678. if prepare != nil {
  679. prepare()
  680. }
  681. e.c.emit(rdupN(2))
  682. body()
  683. e.addSrcMap()
  684. e._emitSetterP(rn, id)
  685. }
  686. }
  687. }
  688. func (e *compiledPrivateDotExpr) deleteExpr() compiledExpr {
  689. e.c.throwSyntaxError(e.offset, "Private fields can not be deleted")
  690. panic("unreachable")
  691. }
  692. func (e *compiledPrivateDotExpr) emitRef() {
  693. e.left.emitGetter(true)
  694. rn, id := e.c.resolvePrivateName(e.name, e.offset)
  695. if rn != nil {
  696. e.c.emit((*getPrivateRefRes)(rn))
  697. } else {
  698. e.c.emit((*getPrivateRefId)(id))
  699. }
  700. }
  701. type compiledSuperBracketExpr struct {
  702. baseCompiledExpr
  703. member compiledExpr
  704. }
  705. func (e *compiledSuperBracketExpr) emitGetter(putOnStack bool) {
  706. e.c.emitLoadThis()
  707. e.member.emitGetter(true)
  708. e.c.emit(loadSuper)
  709. e.addSrcMap()
  710. e.c.emit(getElemRecv)
  711. if !putOnStack {
  712. e.c.emit(pop)
  713. }
  714. }
  715. func (e *compiledSuperBracketExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  716. e.c.emitLoadThis()
  717. e.member.emitGetter(true)
  718. e.c.emit(loadSuper)
  719. valueExpr.emitGetter(true)
  720. e.addSrcMap()
  721. if putOnStack {
  722. if e.c.scope.strict {
  723. e.c.emit(setElemRecvStrict)
  724. } else {
  725. e.c.emit(setElemRecv)
  726. }
  727. } else {
  728. if e.c.scope.strict {
  729. e.c.emit(setElemRecvStrictP)
  730. } else {
  731. e.c.emit(setElemRecvP)
  732. }
  733. }
  734. }
  735. func (e *compiledSuperBracketExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  736. if !putOnStack {
  737. e.c.emitLoadThis()
  738. e.member.emitGetter(true)
  739. e.c.emit(loadSuper, dupLast(3), getElemRecv)
  740. body()
  741. e.addSrcMap()
  742. if e.c.scope.strict {
  743. e.c.emit(setElemRecvStrictP)
  744. } else {
  745. e.c.emit(setElemRecvP)
  746. }
  747. } else {
  748. if !postfix {
  749. e.c.emitLoadThis()
  750. e.member.emitGetter(true)
  751. e.c.emit(loadSuper, dupLast(3), getElemRecv)
  752. if prepare != nil {
  753. prepare()
  754. }
  755. body()
  756. e.addSrcMap()
  757. if e.c.scope.strict {
  758. e.c.emit(setElemRecvStrict)
  759. } else {
  760. e.c.emit(setElemRecv)
  761. }
  762. } else {
  763. e.c.emit(loadUndef)
  764. e.c.emitLoadThis()
  765. e.member.emitGetter(true)
  766. e.c.emit(loadSuper, dupLast(3), getElemRecv)
  767. if prepare != nil {
  768. prepare()
  769. }
  770. e.c.emit(rdupN(4))
  771. body()
  772. e.addSrcMap()
  773. if e.c.scope.strict {
  774. e.c.emit(setElemRecvStrictP)
  775. } else {
  776. e.c.emit(setElemRecvP)
  777. }
  778. }
  779. }
  780. }
  781. func (e *compiledSuperBracketExpr) emitRef() {
  782. e.c.emitLoadThis()
  783. e.member.emitGetter(true)
  784. e.c.emit(loadSuper)
  785. if e.c.scope.strict {
  786. e.c.emit(getElemRefRecvStrict)
  787. } else {
  788. e.c.emit(getElemRefRecv)
  789. }
  790. }
  791. func (c *compiler) superDeleteError(offset int) compiledExpr {
  792. return c.compileEmitterExpr(func() {
  793. c.emit(throwConst{referenceError("Unsupported reference to 'super'")})
  794. }, file.Idx(offset+1))
  795. }
  796. func (e *compiledSuperBracketExpr) deleteExpr() compiledExpr {
  797. return e.c.superDeleteError(e.offset)
  798. }
  799. func (c *compiler) checkConstantString(expr compiledExpr) (unistring.String, bool) {
  800. if expr.constant() {
  801. if val, ex := c.evalConst(expr); ex == nil {
  802. if s, ok := val.(valueString); ok {
  803. return s.string(), true
  804. }
  805. }
  806. }
  807. return "", false
  808. }
  809. func (c *compiler) compileBracketExpression(v *ast.BracketExpression) compiledExpr {
  810. if sup, ok := v.Left.(*ast.SuperExpression); ok {
  811. c.checkSuperBase(sup.Idx)
  812. member := c.compileExpression(v.Member)
  813. if name, ok := c.checkConstantString(member); ok {
  814. r := &compiledSuperDotExpr{
  815. name: name,
  816. }
  817. r.init(c, v.LeftBracket)
  818. return r
  819. }
  820. r := &compiledSuperBracketExpr{
  821. member: member,
  822. }
  823. r.init(c, v.LeftBracket)
  824. return r
  825. }
  826. left := c.compileExpression(v.Left)
  827. member := c.compileExpression(v.Member)
  828. if name, ok := c.checkConstantString(member); ok {
  829. r := &compiledDotExpr{
  830. left: left,
  831. name: name,
  832. }
  833. r.init(c, v.LeftBracket)
  834. return r
  835. }
  836. r := &compiledBracketExpr{
  837. left: left,
  838. member: member,
  839. }
  840. r.init(c, v.LeftBracket)
  841. return r
  842. }
  843. func (e *compiledDotExpr) emitGetter(putOnStack bool) {
  844. e.left.emitGetter(true)
  845. e.addSrcMap()
  846. e.c.emit(getProp(e.name))
  847. if !putOnStack {
  848. e.c.emit(pop)
  849. }
  850. }
  851. func (e *compiledDotExpr) emitRef() {
  852. e.left.emitGetter(true)
  853. if e.c.scope.strict {
  854. e.c.emit(getPropRefStrict(e.name))
  855. } else {
  856. e.c.emit(getPropRef(e.name))
  857. }
  858. }
  859. func (e *compiledDotExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  860. e.left.emitGetter(true)
  861. valueExpr.emitGetter(true)
  862. if e.c.scope.strict {
  863. if putOnStack {
  864. e.c.emit(setPropStrict(e.name))
  865. } else {
  866. e.c.emit(setPropStrictP(e.name))
  867. }
  868. } else {
  869. if putOnStack {
  870. e.c.emit(setProp(e.name))
  871. } else {
  872. e.c.emit(setPropP(e.name))
  873. }
  874. }
  875. }
  876. func (e *compiledDotExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  877. if !putOnStack {
  878. e.left.emitGetter(true)
  879. e.c.emit(dup)
  880. e.c.emit(getProp(e.name))
  881. body()
  882. e.addSrcMap()
  883. if e.c.scope.strict {
  884. e.c.emit(setPropStrictP(e.name))
  885. } else {
  886. e.c.emit(setPropP(e.name))
  887. }
  888. } else {
  889. if !postfix {
  890. e.left.emitGetter(true)
  891. e.c.emit(dup)
  892. e.c.emit(getProp(e.name))
  893. if prepare != nil {
  894. prepare()
  895. }
  896. body()
  897. e.addSrcMap()
  898. if e.c.scope.strict {
  899. e.c.emit(setPropStrict(e.name))
  900. } else {
  901. e.c.emit(setProp(e.name))
  902. }
  903. } else {
  904. e.c.emit(loadUndef)
  905. e.left.emitGetter(true)
  906. e.c.emit(dup)
  907. e.c.emit(getProp(e.name))
  908. if prepare != nil {
  909. prepare()
  910. }
  911. e.c.emit(rdupN(2))
  912. body()
  913. e.addSrcMap()
  914. if e.c.scope.strict {
  915. e.c.emit(setPropStrictP(e.name))
  916. } else {
  917. e.c.emit(setPropP(e.name))
  918. }
  919. }
  920. }
  921. }
  922. func (e *compiledDotExpr) deleteExpr() compiledExpr {
  923. r := &deletePropExpr{
  924. left: e.left,
  925. name: e.name,
  926. }
  927. r.init(e.c, file.Idx(e.offset)+1)
  928. return r
  929. }
  930. func (e *compiledBracketExpr) emitGetter(putOnStack bool) {
  931. e.left.emitGetter(true)
  932. e.member.emitGetter(true)
  933. e.addSrcMap()
  934. e.c.emit(getElem)
  935. if !putOnStack {
  936. e.c.emit(pop)
  937. }
  938. }
  939. func (e *compiledBracketExpr) emitRef() {
  940. e.left.emitGetter(true)
  941. e.member.emitGetter(true)
  942. if e.c.scope.strict {
  943. e.c.emit(getElemRefStrict)
  944. } else {
  945. e.c.emit(getElemRef)
  946. }
  947. }
  948. func (e *compiledBracketExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  949. e.left.emitGetter(true)
  950. e.member.emitGetter(true)
  951. valueExpr.emitGetter(true)
  952. e.addSrcMap()
  953. if e.c.scope.strict {
  954. if putOnStack {
  955. e.c.emit(setElemStrict)
  956. } else {
  957. e.c.emit(setElemStrictP)
  958. }
  959. } else {
  960. if putOnStack {
  961. e.c.emit(setElem)
  962. } else {
  963. e.c.emit(setElemP)
  964. }
  965. }
  966. }
  967. func (e *compiledBracketExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  968. if !putOnStack {
  969. e.left.emitGetter(true)
  970. e.member.emitGetter(true)
  971. e.c.emit(dupLast(2), getElem)
  972. body()
  973. e.addSrcMap()
  974. if e.c.scope.strict {
  975. e.c.emit(setElemStrict, pop)
  976. } else {
  977. e.c.emit(setElem, pop)
  978. }
  979. } else {
  980. if !postfix {
  981. e.left.emitGetter(true)
  982. e.member.emitGetter(true)
  983. e.c.emit(dupLast(2), getElem)
  984. if prepare != nil {
  985. prepare()
  986. }
  987. body()
  988. e.addSrcMap()
  989. if e.c.scope.strict {
  990. e.c.emit(setElemStrict)
  991. } else {
  992. e.c.emit(setElem)
  993. }
  994. } else {
  995. e.c.emit(loadUndef)
  996. e.left.emitGetter(true)
  997. e.member.emitGetter(true)
  998. e.c.emit(dupLast(2), getElem)
  999. if prepare != nil {
  1000. prepare()
  1001. }
  1002. e.c.emit(rdupN(3))
  1003. body()
  1004. e.addSrcMap()
  1005. if e.c.scope.strict {
  1006. e.c.emit(setElemStrict, pop)
  1007. } else {
  1008. e.c.emit(setElem, pop)
  1009. }
  1010. }
  1011. }
  1012. }
  1013. func (e *compiledBracketExpr) deleteExpr() compiledExpr {
  1014. r := &deleteElemExpr{
  1015. left: e.left,
  1016. member: e.member,
  1017. }
  1018. r.init(e.c, file.Idx(e.offset)+1)
  1019. return r
  1020. }
  1021. func (e *deleteElemExpr) emitGetter(putOnStack bool) {
  1022. e.left.emitGetter(true)
  1023. e.member.emitGetter(true)
  1024. e.addSrcMap()
  1025. if e.c.scope.strict {
  1026. e.c.emit(deleteElemStrict)
  1027. } else {
  1028. e.c.emit(deleteElem)
  1029. }
  1030. if !putOnStack {
  1031. e.c.emit(pop)
  1032. }
  1033. }
  1034. func (e *deletePropExpr) emitGetter(putOnStack bool) {
  1035. e.left.emitGetter(true)
  1036. e.addSrcMap()
  1037. if e.c.scope.strict {
  1038. e.c.emit(deletePropStrict(e.name))
  1039. } else {
  1040. e.c.emit(deleteProp(e.name))
  1041. }
  1042. if !putOnStack {
  1043. e.c.emit(pop)
  1044. }
  1045. }
  1046. func (e *deleteVarExpr) emitGetter(putOnStack bool) {
  1047. /*if e.c.scope.strict {
  1048. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  1049. return
  1050. }*/
  1051. e.c.emit(deleteVar(e.name))
  1052. if !putOnStack {
  1053. e.c.emit(pop)
  1054. }
  1055. }
  1056. func (e *deleteGlobalExpr) emitGetter(putOnStack bool) {
  1057. /*if e.c.scope.strict {
  1058. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  1059. return
  1060. }*/
  1061. e.c.emit(deleteGlobal(e.name))
  1062. if !putOnStack {
  1063. e.c.emit(pop)
  1064. }
  1065. }
  1066. func (e *compiledAssignExpr) emitGetter(putOnStack bool) {
  1067. switch e.operator {
  1068. case token.ASSIGN:
  1069. e.left.emitSetter(e.right, putOnStack)
  1070. case token.PLUS:
  1071. e.left.emitUnary(nil, func() {
  1072. e.right.emitGetter(true)
  1073. e.c.emit(add)
  1074. }, false, putOnStack)
  1075. case token.MINUS:
  1076. e.left.emitUnary(nil, func() {
  1077. e.right.emitGetter(true)
  1078. e.c.emit(sub)
  1079. }, false, putOnStack)
  1080. case token.MULTIPLY:
  1081. e.left.emitUnary(nil, func() {
  1082. e.right.emitGetter(true)
  1083. e.c.emit(mul)
  1084. }, false, putOnStack)
  1085. case token.EXPONENT:
  1086. e.left.emitUnary(nil, func() {
  1087. e.right.emitGetter(true)
  1088. e.c.emit(exp)
  1089. }, false, putOnStack)
  1090. case token.SLASH:
  1091. e.left.emitUnary(nil, func() {
  1092. e.right.emitGetter(true)
  1093. e.c.emit(div)
  1094. }, false, putOnStack)
  1095. case token.REMAINDER:
  1096. e.left.emitUnary(nil, func() {
  1097. e.right.emitGetter(true)
  1098. e.c.emit(mod)
  1099. }, false, putOnStack)
  1100. case token.OR:
  1101. e.left.emitUnary(nil, func() {
  1102. e.right.emitGetter(true)
  1103. e.c.emit(or)
  1104. }, false, putOnStack)
  1105. case token.AND:
  1106. e.left.emitUnary(nil, func() {
  1107. e.right.emitGetter(true)
  1108. e.c.emit(and)
  1109. }, false, putOnStack)
  1110. case token.EXCLUSIVE_OR:
  1111. e.left.emitUnary(nil, func() {
  1112. e.right.emitGetter(true)
  1113. e.c.emit(xor)
  1114. }, false, putOnStack)
  1115. case token.SHIFT_LEFT:
  1116. e.left.emitUnary(nil, func() {
  1117. e.right.emitGetter(true)
  1118. e.c.emit(sal)
  1119. }, false, putOnStack)
  1120. case token.SHIFT_RIGHT:
  1121. e.left.emitUnary(nil, func() {
  1122. e.right.emitGetter(true)
  1123. e.c.emit(sar)
  1124. }, false, putOnStack)
  1125. case token.UNSIGNED_SHIFT_RIGHT:
  1126. e.left.emitUnary(nil, func() {
  1127. e.right.emitGetter(true)
  1128. e.c.emit(shr)
  1129. }, false, putOnStack)
  1130. default:
  1131. e.c.assert(false, e.offset, "Unknown assign operator: %s", e.operator.String())
  1132. panic("unreachable")
  1133. }
  1134. }
  1135. func (e *compiledLiteral) emitGetter(putOnStack bool) {
  1136. if putOnStack {
  1137. e.c.emit(loadVal(e.c.p.defineLiteralValue(e.val)))
  1138. }
  1139. }
  1140. func (e *compiledLiteral) constant() bool {
  1141. return true
  1142. }
  1143. func (e *compiledTemplateLiteral) emitGetter(putOnStack bool) {
  1144. if e.tag == nil {
  1145. if len(e.elements) == 0 {
  1146. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringEmpty)))
  1147. } else {
  1148. tail := e.elements[len(e.elements)-1].Parsed
  1149. if len(e.elements) == 1 {
  1150. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(tail))))
  1151. } else {
  1152. stringCount := 0
  1153. if head := e.elements[0].Parsed; head != "" {
  1154. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(head))))
  1155. stringCount++
  1156. }
  1157. e.expressions[0].emitGetter(true)
  1158. e.c.emit(_toString{})
  1159. stringCount++
  1160. for i := 1; i < len(e.elements)-1; i++ {
  1161. if elt := e.elements[i].Parsed; elt != "" {
  1162. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(elt))))
  1163. stringCount++
  1164. }
  1165. e.expressions[i].emitGetter(true)
  1166. e.c.emit(_toString{})
  1167. stringCount++
  1168. }
  1169. if tail != "" {
  1170. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(tail))))
  1171. stringCount++
  1172. }
  1173. e.c.emit(concatStrings(stringCount))
  1174. }
  1175. }
  1176. } else {
  1177. cooked := make([]Value, len(e.elements))
  1178. raw := make([]Value, len(e.elements))
  1179. for i, elt := range e.elements {
  1180. raw[i] = &valueProperty{
  1181. enumerable: true,
  1182. value: newStringValue(elt.Literal),
  1183. }
  1184. var cookedVal Value
  1185. if elt.Valid {
  1186. cookedVal = stringValueFromRaw(elt.Parsed)
  1187. } else {
  1188. cookedVal = _undefined
  1189. }
  1190. cooked[i] = &valueProperty{
  1191. enumerable: true,
  1192. value: cookedVal,
  1193. }
  1194. }
  1195. e.c.emitCallee(e.tag)
  1196. e.c.emit(&getTaggedTmplObject{
  1197. raw: raw,
  1198. cooked: cooked,
  1199. })
  1200. for _, expr := range e.expressions {
  1201. expr.emitGetter(true)
  1202. }
  1203. e.c.emit(call(len(e.expressions) + 1))
  1204. }
  1205. if !putOnStack {
  1206. e.c.emit(pop)
  1207. }
  1208. }
  1209. func (c *compiler) compileParameterBindingIdentifier(name unistring.String, offset int) (*binding, bool) {
  1210. if c.scope.strict {
  1211. c.checkIdentifierName(name, offset)
  1212. c.checkIdentifierLName(name, offset)
  1213. }
  1214. return c.scope.bindNameShadow(name)
  1215. }
  1216. func (c *compiler) compileParameterPatternIdBinding(name unistring.String, offset int) {
  1217. if _, unique := c.compileParameterBindingIdentifier(name, offset); !unique {
  1218. c.throwSyntaxError(offset, "Duplicate parameter name not allowed in this context")
  1219. }
  1220. }
  1221. func (c *compiler) compileParameterPatternBinding(item ast.Expression) {
  1222. c.createBindings(item, c.compileParameterPatternIdBinding)
  1223. }
  1224. func (c *compiler) newCode(length, minCap int) (buf []instruction) {
  1225. if c.codeScratchpad != nil {
  1226. buf = c.codeScratchpad
  1227. c.codeScratchpad = nil
  1228. }
  1229. if cap(buf) < minCap {
  1230. buf = make([]instruction, length, minCap)
  1231. } else {
  1232. buf = buf[:length]
  1233. }
  1234. return
  1235. }
  1236. func (e *compiledFunctionLiteral) compile() (prg *Program, name unistring.String, length int, strict bool) {
  1237. e.c.assert(e.typ != funcNone, e.offset, "compiledFunctionLiteral.typ is not set")
  1238. savedPrg := e.c.p
  1239. preambleLen := 8 // enter, boxThis, loadStack(0), initThis, createArgs, set, loadCallee, init
  1240. e.c.p = &Program{
  1241. src: e.c.p.src,
  1242. code: e.c.newCode(preambleLen, 16),
  1243. }
  1244. e.c.newScope()
  1245. s := e.c.scope
  1246. s.funcType = e.typ
  1247. if e.name != nil {
  1248. name = e.name.Name
  1249. } else {
  1250. name = e.lhsName
  1251. }
  1252. if name != "" {
  1253. e.c.p.funcName = name
  1254. }
  1255. savedBlock := e.c.block
  1256. defer func() {
  1257. e.c.block = savedBlock
  1258. }()
  1259. e.c.block = &block{
  1260. typ: blockScope,
  1261. }
  1262. if !s.strict {
  1263. s.strict = e.strict != nil
  1264. }
  1265. hasPatterns := false
  1266. hasInits := false
  1267. firstDupIdx := -1
  1268. if e.parameterList.Rest != nil {
  1269. hasPatterns = true // strictly speaking not, but we need to activate all the checks
  1270. }
  1271. // First, make sure that the first bindings correspond to the formal parameters
  1272. for _, item := range e.parameterList.List {
  1273. switch tgt := item.Target.(type) {
  1274. case *ast.Identifier:
  1275. offset := int(tgt.Idx) - 1
  1276. b, unique := e.c.compileParameterBindingIdentifier(tgt.Name, offset)
  1277. if !unique {
  1278. firstDupIdx = offset
  1279. }
  1280. b.isArg = true
  1281. case ast.Pattern:
  1282. b := s.addBinding(int(item.Idx0()) - 1)
  1283. b.isArg = true
  1284. hasPatterns = true
  1285. default:
  1286. e.c.throwSyntaxError(int(item.Idx0())-1, "Unsupported BindingElement type: %T", item)
  1287. return
  1288. }
  1289. if item.Initializer != nil {
  1290. hasInits = true
  1291. }
  1292. if firstDupIdx >= 0 && (hasPatterns || hasInits || s.strict || e.typ == funcArrow || e.typ == funcMethod) {
  1293. e.c.throwSyntaxError(firstDupIdx, "Duplicate parameter name not allowed in this context")
  1294. return
  1295. }
  1296. if (hasPatterns || hasInits) && e.strict != nil {
  1297. e.c.throwSyntaxError(int(e.strict.Idx)-1, "Illegal 'use strict' directive in function with non-simple parameter list")
  1298. return
  1299. }
  1300. if !hasInits {
  1301. length++
  1302. }
  1303. }
  1304. var thisBinding *binding
  1305. if e.typ != funcArrow {
  1306. thisBinding = s.createThisBinding()
  1307. }
  1308. // create pattern bindings
  1309. if hasPatterns {
  1310. for _, item := range e.parameterList.List {
  1311. switch tgt := item.Target.(type) {
  1312. case *ast.Identifier:
  1313. // we already created those in the previous loop, skipping
  1314. default:
  1315. e.c.compileParameterPatternBinding(tgt)
  1316. }
  1317. }
  1318. if rest := e.parameterList.Rest; rest != nil {
  1319. e.c.compileParameterPatternBinding(rest)
  1320. }
  1321. }
  1322. paramsCount := len(e.parameterList.List)
  1323. s.numArgs = paramsCount
  1324. body := e.body
  1325. funcs := e.c.extractFunctions(body)
  1326. var calleeBinding *binding
  1327. emitArgsRestMark := -1
  1328. firstForwardRef := -1
  1329. enterFunc2Mark := -1
  1330. if hasPatterns || hasInits {
  1331. if e.isExpr && e.name != nil {
  1332. if b, created := s.bindNameLexical(e.name.Name, false, 0); created {
  1333. b.isConst = true
  1334. calleeBinding = b
  1335. }
  1336. }
  1337. for i, item := range e.parameterList.List {
  1338. if pattern, ok := item.Target.(ast.Pattern); ok {
  1339. i := i
  1340. e.c.compilePatternInitExpr(func() {
  1341. if firstForwardRef == -1 {
  1342. s.bindings[i].emitGet()
  1343. } else {
  1344. e.c.emit(loadStackLex(-i - 1))
  1345. }
  1346. }, item.Initializer, item.Target.Idx0()).emitGetter(true)
  1347. e.c.emitPattern(pattern, func(target, init compiledExpr) {
  1348. e.c.emitPatternLexicalAssign(target, init)
  1349. }, false)
  1350. } else if item.Initializer != nil {
  1351. markGet := len(e.c.p.code)
  1352. e.c.emit(nil)
  1353. mark := len(e.c.p.code)
  1354. e.c.emit(nil)
  1355. e.c.emitExpr(e.c.compileExpression(item.Initializer), true)
  1356. if firstForwardRef == -1 && (s.isDynamic() || s.bindings[i].useCount() > 0) {
  1357. firstForwardRef = i
  1358. }
  1359. if firstForwardRef == -1 {
  1360. s.bindings[i].emitGetAt(markGet)
  1361. } else {
  1362. e.c.p.code[markGet] = loadStackLex(-i - 1)
  1363. }
  1364. s.bindings[i].emitInitP()
  1365. e.c.p.code[mark] = jdefP(len(e.c.p.code) - mark)
  1366. } else {
  1367. if firstForwardRef == -1 && s.bindings[i].useCount() > 0 {
  1368. firstForwardRef = i
  1369. }
  1370. if firstForwardRef != -1 {
  1371. e.c.emit(loadStackLex(-i - 1))
  1372. s.bindings[i].emitInitP()
  1373. }
  1374. }
  1375. }
  1376. if rest := e.parameterList.Rest; rest != nil {
  1377. e.c.emitAssign(rest, e.c.compileEmitterExpr(
  1378. func() {
  1379. emitArgsRestMark = len(e.c.p.code)
  1380. e.c.emit(createArgsRestStack(paramsCount))
  1381. }, rest.Idx0()),
  1382. func(target, init compiledExpr) {
  1383. e.c.emitPatternLexicalAssign(target, init)
  1384. })
  1385. }
  1386. if firstForwardRef != -1 {
  1387. for _, b := range s.bindings {
  1388. b.inStash = true
  1389. }
  1390. s.argsInStash = true
  1391. s.needStash = true
  1392. }
  1393. e.c.newBlockScope()
  1394. varScope := e.c.scope
  1395. varScope.variable = true
  1396. enterFunc2Mark = len(e.c.p.code)
  1397. e.c.emit(nil)
  1398. e.c.compileDeclList(e.declarationList, false)
  1399. e.c.createFunctionBindings(funcs)
  1400. e.c.compileLexicalDeclarationsFuncBody(body, calleeBinding)
  1401. for _, b := range varScope.bindings {
  1402. if b.isVar {
  1403. if parentBinding := s.boundNames[b.name]; parentBinding != nil && parentBinding != calleeBinding {
  1404. parentBinding.emitGet()
  1405. b.emitSetP()
  1406. }
  1407. }
  1408. }
  1409. } else {
  1410. // To avoid triggering variable conflict when binding from non-strict direct eval().
  1411. // Parameters are supposed to be in a parent scope, hence no conflict.
  1412. for _, b := range s.bindings[:paramsCount] {
  1413. b.isVar = true
  1414. }
  1415. e.c.compileDeclList(e.declarationList, true)
  1416. e.c.createFunctionBindings(funcs)
  1417. e.c.compileLexicalDeclarations(body, true)
  1418. if e.isExpr && e.name != nil {
  1419. if b, created := s.bindNameLexical(e.name.Name, false, 0); created {
  1420. b.isConst = true
  1421. calleeBinding = b
  1422. }
  1423. }
  1424. if calleeBinding != nil {
  1425. e.c.emit(loadCallee)
  1426. calleeBinding.emitInitP()
  1427. }
  1428. }
  1429. e.c.compileFunctions(funcs)
  1430. e.c.compileStatements(body, false)
  1431. var last ast.Statement
  1432. if l := len(body); l > 0 {
  1433. last = body[l-1]
  1434. }
  1435. if _, ok := last.(*ast.ReturnStatement); !ok {
  1436. if e.typ == funcDerivedCtor {
  1437. e.c.emit(loadUndef)
  1438. thisBinding.markAccessPoint()
  1439. e.c.emit(ret)
  1440. } else {
  1441. e.c.emit(loadUndef, ret)
  1442. }
  1443. }
  1444. delta := 0
  1445. code := e.c.p.code
  1446. if s.isDynamic() && !s.argsInStash {
  1447. s.moveArgsToStash()
  1448. }
  1449. if s.argsNeeded || s.isDynamic() && e.typ != funcArrow && e.typ != funcClsInit {
  1450. if e.typ == funcClsInit {
  1451. e.c.throwSyntaxError(e.offset, "'arguments' is not allowed in class field initializer or static initialization block")
  1452. }
  1453. b, created := s.bindNameLexical("arguments", false, 0)
  1454. if created || b.isVar {
  1455. if !s.argsInStash {
  1456. s.moveArgsToStash()
  1457. }
  1458. if s.strict {
  1459. b.isConst = true
  1460. } else {
  1461. b.isVar = e.c.scope.isFunction()
  1462. }
  1463. pos := preambleLen - 2
  1464. delta += 2
  1465. if s.strict || hasPatterns || hasInits {
  1466. code[pos] = createArgsUnmapped(paramsCount)
  1467. } else {
  1468. code[pos] = createArgsMapped(paramsCount)
  1469. }
  1470. pos++
  1471. b.emitInitPAtScope(s, pos)
  1472. }
  1473. }
  1474. if calleeBinding != nil {
  1475. if !s.isDynamic() && calleeBinding.useCount() == 0 {
  1476. s.deleteBinding(calleeBinding)
  1477. calleeBinding = nil
  1478. } else {
  1479. delta++
  1480. calleeBinding.emitInitPAtScope(s, preambleLen-delta)
  1481. delta++
  1482. code[preambleLen-delta] = loadCallee
  1483. }
  1484. }
  1485. if thisBinding != nil {
  1486. if !s.isDynamic() && thisBinding.useCount() == 0 {
  1487. s.deleteBinding(thisBinding)
  1488. thisBinding = nil
  1489. } else {
  1490. if thisBinding.inStash || s.isDynamic() {
  1491. delta++
  1492. thisBinding.emitInitAtScope(s, preambleLen-delta)
  1493. }
  1494. }
  1495. }
  1496. stashSize, stackSize := s.finaliseVarAlloc(0)
  1497. if thisBinding != nil && thisBinding.inStash && (!s.argsInStash || stackSize > 0) {
  1498. delta++
  1499. code[preambleLen-delta] = loadStack(0)
  1500. } // otherwise, 'this' will be at stack[sp-1], no need to load
  1501. if !s.strict && thisBinding != nil {
  1502. delta++
  1503. code[preambleLen-delta] = boxThis
  1504. }
  1505. delta++
  1506. delta = preambleLen - delta
  1507. var enter instruction
  1508. if stashSize > 0 || s.argsInStash {
  1509. if firstForwardRef == -1 {
  1510. enter1 := enterFunc{
  1511. numArgs: uint32(paramsCount),
  1512. argsToStash: s.argsInStash,
  1513. stashSize: uint32(stashSize),
  1514. stackSize: uint32(stackSize),
  1515. extensible: s.dynamic,
  1516. funcType: e.typ,
  1517. }
  1518. if s.isDynamic() {
  1519. enter1.names = s.makeNamesMap()
  1520. }
  1521. enter = &enter1
  1522. if enterFunc2Mark != -1 {
  1523. ef2 := &enterFuncBody{
  1524. extensible: e.c.scope.dynamic,
  1525. funcType: e.typ,
  1526. }
  1527. e.c.updateEnterBlock(&ef2.enterBlock)
  1528. e.c.p.code[enterFunc2Mark] = ef2
  1529. }
  1530. } else {
  1531. enter1 := enterFunc1{
  1532. stashSize: uint32(stashSize),
  1533. numArgs: uint32(paramsCount),
  1534. argsToCopy: uint32(firstForwardRef),
  1535. extensible: s.dynamic,
  1536. funcType: e.typ,
  1537. }
  1538. if s.isDynamic() {
  1539. enter1.names = s.makeNamesMap()
  1540. }
  1541. enter = &enter1
  1542. if enterFunc2Mark != -1 {
  1543. ef2 := &enterFuncBody{
  1544. adjustStack: true,
  1545. extensible: e.c.scope.dynamic,
  1546. funcType: e.typ,
  1547. }
  1548. e.c.updateEnterBlock(&ef2.enterBlock)
  1549. e.c.p.code[enterFunc2Mark] = ef2
  1550. }
  1551. }
  1552. if emitArgsRestMark != -1 && s.argsInStash {
  1553. e.c.p.code[emitArgsRestMark] = createArgsRestStash
  1554. }
  1555. } else {
  1556. enter = &enterFuncStashless{
  1557. stackSize: uint32(stackSize),
  1558. args: uint32(paramsCount),
  1559. }
  1560. if enterFunc2Mark != -1 {
  1561. ef2 := &enterFuncBody{
  1562. extensible: e.c.scope.dynamic,
  1563. funcType: e.typ,
  1564. }
  1565. e.c.updateEnterBlock(&ef2.enterBlock)
  1566. e.c.p.code[enterFunc2Mark] = ef2
  1567. }
  1568. }
  1569. code[delta] = enter
  1570. s.trimCode(delta)
  1571. strict = s.strict
  1572. prg = e.c.p
  1573. // e.c.p.dumpCode()
  1574. if enterFunc2Mark != -1 {
  1575. e.c.popScope()
  1576. }
  1577. e.c.popScope()
  1578. e.c.p = savedPrg
  1579. return
  1580. }
  1581. func (e *compiledFunctionLiteral) emitGetter(putOnStack bool) {
  1582. p, name, length, strict := e.compile()
  1583. switch e.typ {
  1584. case funcArrow:
  1585. if e.isAsync {
  1586. e.c.emit(&newAsyncArrowFunc{newArrowFunc: newArrowFunc{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}}})
  1587. } else {
  1588. e.c.emit(&newArrowFunc{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}})
  1589. }
  1590. case funcMethod, funcClsInit:
  1591. if e.isAsync {
  1592. e.c.emit(&newAsyncMethod{newMethod: newMethod{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}, homeObjOffset: e.homeObjOffset}})
  1593. } else {
  1594. e.c.emit(&newMethod{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}, homeObjOffset: e.homeObjOffset})
  1595. }
  1596. case funcRegular:
  1597. if e.isAsync {
  1598. e.c.emit(&newAsyncFunc{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}})
  1599. } else {
  1600. e.c.emit(&newFunc{prg: p, length: length, name: name, source: e.source, strict: strict})
  1601. }
  1602. default:
  1603. e.c.throwSyntaxError(e.offset, "Unsupported func type: %v", e.typ)
  1604. }
  1605. if !putOnStack {
  1606. e.c.emit(pop)
  1607. }
  1608. }
  1609. func (c *compiler) compileFunctionLiteral(v *ast.FunctionLiteral, isExpr bool) *compiledFunctionLiteral {
  1610. strictBody := c.isStrictStatement(v.Body)
  1611. if v.Name != nil && (c.scope.strict || strictBody != nil) {
  1612. c.checkIdentifierLName(v.Name.Name, int(v.Name.Idx)-1)
  1613. }
  1614. r := &compiledFunctionLiteral{
  1615. name: v.Name,
  1616. parameterList: v.ParameterList,
  1617. body: v.Body.List,
  1618. source: v.Source,
  1619. declarationList: v.DeclarationList,
  1620. isExpr: isExpr,
  1621. typ: funcRegular,
  1622. strict: strictBody,
  1623. isAsync: v.Async,
  1624. }
  1625. r.init(c, v.Idx0())
  1626. return r
  1627. }
  1628. type compiledClassLiteral struct {
  1629. baseCompiledExpr
  1630. name *ast.Identifier
  1631. superClass compiledExpr
  1632. body []ast.ClassElement
  1633. lhsName unistring.String
  1634. source string
  1635. isExpr bool
  1636. }
  1637. func (c *compiler) processKey(expr ast.Expression) (val unistring.String, computed bool) {
  1638. keyExpr := c.compileExpression(expr)
  1639. if keyExpr.constant() {
  1640. v, ex := c.evalConst(keyExpr)
  1641. if ex == nil {
  1642. return v.string(), false
  1643. }
  1644. }
  1645. keyExpr.emitGetter(true)
  1646. computed = true
  1647. return
  1648. }
  1649. func (e *compiledClassLiteral) processClassKey(expr ast.Expression) (privateName *privateName, key unistring.String, computed bool) {
  1650. if p, ok := expr.(*ast.PrivateIdentifier); ok {
  1651. privateName = e.c.classScope.getDeclaredPrivateId(p.Name)
  1652. key = privateIdString(p.Name)
  1653. return
  1654. }
  1655. key, computed = e.c.processKey(expr)
  1656. return
  1657. }
  1658. type clsElement struct {
  1659. key unistring.String
  1660. privateName *privateName
  1661. initializer compiledExpr
  1662. body *compiledFunctionLiteral
  1663. computed bool
  1664. }
  1665. func (e *compiledClassLiteral) emitGetter(putOnStack bool) {
  1666. e.c.newBlockScope()
  1667. s := e.c.scope
  1668. s.strict = true
  1669. enter := &enterBlock{}
  1670. mark0 := len(e.c.p.code)
  1671. e.c.emit(enter)
  1672. e.c.block = &block{
  1673. typ: blockScope,
  1674. outer: e.c.block,
  1675. }
  1676. var clsBinding *binding
  1677. var clsName unistring.String
  1678. if name := e.name; name != nil {
  1679. clsName = name.Name
  1680. clsBinding = e.c.createLexicalIdBinding(clsName, true, int(name.Idx)-1)
  1681. } else {
  1682. clsName = e.lhsName
  1683. }
  1684. var ctorMethod *ast.MethodDefinition
  1685. ctorMethodIdx := -1
  1686. staticsCount := 0
  1687. instanceFieldsCount := 0
  1688. hasStaticPrivateMethods := false
  1689. cs := &classScope{
  1690. c: e.c,
  1691. outer: e.c.classScope,
  1692. }
  1693. for idx, elt := range e.body {
  1694. switch elt := elt.(type) {
  1695. case *ast.ClassStaticBlock:
  1696. if len(elt.Block.List) > 0 {
  1697. staticsCount++
  1698. }
  1699. case *ast.FieldDefinition:
  1700. if id, ok := elt.Key.(*ast.PrivateIdentifier); ok {
  1701. cs.declarePrivateId(id.Name, ast.PropertyKindValue, elt.Static, int(elt.Idx)-1)
  1702. }
  1703. if elt.Static {
  1704. staticsCount++
  1705. } else {
  1706. instanceFieldsCount++
  1707. }
  1708. case *ast.MethodDefinition:
  1709. if !elt.Static {
  1710. if id, ok := elt.Key.(*ast.StringLiteral); ok {
  1711. if !elt.Computed && id.Value == "constructor" {
  1712. if ctorMethod != nil {
  1713. e.c.throwSyntaxError(int(id.Idx)-1, "A class may only have one constructor")
  1714. }
  1715. ctorMethod = elt
  1716. ctorMethodIdx = idx
  1717. continue
  1718. }
  1719. }
  1720. }
  1721. if id, ok := elt.Key.(*ast.PrivateIdentifier); ok {
  1722. cs.declarePrivateId(id.Name, elt.Kind, elt.Static, int(elt.Idx)-1)
  1723. if elt.Static {
  1724. hasStaticPrivateMethods = true
  1725. }
  1726. }
  1727. default:
  1728. e.c.assert(false, int(elt.Idx0())-1, "Unsupported static element: %T", elt)
  1729. }
  1730. }
  1731. var staticInit *newStaticFieldInit
  1732. if staticsCount > 0 || hasStaticPrivateMethods {
  1733. staticInit = &newStaticFieldInit{}
  1734. e.c.emit(staticInit)
  1735. }
  1736. var derived bool
  1737. var newClassIns *newClass
  1738. if superClass := e.superClass; superClass != nil {
  1739. derived = true
  1740. superClass.emitGetter(true)
  1741. ndc := &newDerivedClass{
  1742. newClass: newClass{
  1743. name: clsName,
  1744. source: e.source,
  1745. },
  1746. }
  1747. e.addSrcMap()
  1748. e.c.emit(ndc)
  1749. newClassIns = &ndc.newClass
  1750. } else {
  1751. newClassIns = &newClass{
  1752. name: clsName,
  1753. source: e.source,
  1754. }
  1755. e.addSrcMap()
  1756. e.c.emit(newClassIns)
  1757. }
  1758. e.c.classScope = cs
  1759. if ctorMethod != nil {
  1760. newClassIns.ctor, newClassIns.length = e.c.compileCtor(ctorMethod.Body, derived)
  1761. }
  1762. curIsPrototype := false
  1763. instanceFields := make([]clsElement, 0, instanceFieldsCount)
  1764. staticElements := make([]clsElement, 0, staticsCount)
  1765. // stack at this point:
  1766. //
  1767. // staticFieldInit (if staticsCount > 0 || hasStaticPrivateMethods)
  1768. // prototype
  1769. // class function
  1770. // <- sp
  1771. for idx, elt := range e.body {
  1772. if idx == ctorMethodIdx {
  1773. continue
  1774. }
  1775. switch elt := elt.(type) {
  1776. case *ast.ClassStaticBlock:
  1777. if len(elt.Block.List) > 0 {
  1778. f := e.c.compileFunctionLiteral(&ast.FunctionLiteral{
  1779. Function: elt.Idx0(),
  1780. ParameterList: &ast.ParameterList{},
  1781. Body: elt.Block,
  1782. Source: elt.Source,
  1783. DeclarationList: elt.DeclarationList,
  1784. }, true)
  1785. f.typ = funcClsInit
  1786. //f.lhsName = "<static_initializer>"
  1787. f.homeObjOffset = 1
  1788. staticElements = append(staticElements, clsElement{
  1789. body: f,
  1790. })
  1791. }
  1792. case *ast.FieldDefinition:
  1793. privateName, key, computed := e.processClassKey(elt.Key)
  1794. var el clsElement
  1795. if elt.Initializer != nil {
  1796. el.initializer = e.c.compileExpression(elt.Initializer)
  1797. }
  1798. el.computed = computed
  1799. if computed {
  1800. if elt.Static {
  1801. if curIsPrototype {
  1802. e.c.emit(defineComputedKey(5))
  1803. } else {
  1804. e.c.emit(defineComputedKey(4))
  1805. }
  1806. } else {
  1807. if curIsPrototype {
  1808. e.c.emit(defineComputedKey(3))
  1809. } else {
  1810. e.c.emit(defineComputedKey(2))
  1811. }
  1812. }
  1813. } else {
  1814. el.privateName = privateName
  1815. el.key = key
  1816. }
  1817. if elt.Static {
  1818. staticElements = append(staticElements, el)
  1819. } else {
  1820. instanceFields = append(instanceFields, el)
  1821. }
  1822. case *ast.MethodDefinition:
  1823. if elt.Static {
  1824. if curIsPrototype {
  1825. e.c.emit(pop)
  1826. curIsPrototype = false
  1827. }
  1828. } else {
  1829. if !curIsPrototype {
  1830. e.c.emit(dupN(1))
  1831. curIsPrototype = true
  1832. }
  1833. }
  1834. privateName, key, computed := e.processClassKey(elt.Key)
  1835. lit := e.c.compileFunctionLiteral(elt.Body, true)
  1836. lit.typ = funcMethod
  1837. if computed {
  1838. e.c.emit(_toPropertyKey{})
  1839. lit.homeObjOffset = 2
  1840. } else {
  1841. lit.homeObjOffset = 1
  1842. lit.lhsName = key
  1843. }
  1844. lit.emitGetter(true)
  1845. if privateName != nil {
  1846. var offset int
  1847. if elt.Static {
  1848. if curIsPrototype {
  1849. /*
  1850. staticInit
  1851. proto
  1852. cls
  1853. proto
  1854. method
  1855. <- sp
  1856. */
  1857. offset = 5
  1858. } else {
  1859. /*
  1860. staticInit
  1861. proto
  1862. cls
  1863. method
  1864. <- sp
  1865. */
  1866. offset = 4
  1867. }
  1868. } else {
  1869. if curIsPrototype {
  1870. offset = 3
  1871. } else {
  1872. offset = 2
  1873. }
  1874. }
  1875. switch elt.Kind {
  1876. case ast.PropertyKindGet:
  1877. e.c.emit(&definePrivateGetter{
  1878. definePrivateMethod: definePrivateMethod{
  1879. idx: privateName.idx,
  1880. targetOffset: offset,
  1881. },
  1882. })
  1883. case ast.PropertyKindSet:
  1884. e.c.emit(&definePrivateSetter{
  1885. definePrivateMethod: definePrivateMethod{
  1886. idx: privateName.idx,
  1887. targetOffset: offset,
  1888. },
  1889. })
  1890. default:
  1891. e.c.emit(&definePrivateMethod{
  1892. idx: privateName.idx,
  1893. targetOffset: offset,
  1894. })
  1895. }
  1896. } else if computed {
  1897. switch elt.Kind {
  1898. case ast.PropertyKindGet:
  1899. e.c.emit(&defineGetter{})
  1900. case ast.PropertyKindSet:
  1901. e.c.emit(&defineSetter{})
  1902. default:
  1903. e.c.emit(&defineMethod{})
  1904. }
  1905. } else {
  1906. switch elt.Kind {
  1907. case ast.PropertyKindGet:
  1908. e.c.emit(&defineGetterKeyed{key: key})
  1909. case ast.PropertyKindSet:
  1910. e.c.emit(&defineSetterKeyed{key: key})
  1911. default:
  1912. e.c.emit(&defineMethodKeyed{key: key})
  1913. }
  1914. }
  1915. }
  1916. }
  1917. if curIsPrototype {
  1918. e.c.emit(pop)
  1919. }
  1920. if len(instanceFields) > 0 {
  1921. newClassIns.initFields = e.compileFieldsAndStaticBlocks(instanceFields, "<instance_members_initializer>")
  1922. }
  1923. if staticInit != nil {
  1924. if len(staticElements) > 0 {
  1925. staticInit.initFields = e.compileFieldsAndStaticBlocks(staticElements, "<static_initializer>")
  1926. }
  1927. }
  1928. env := e.c.classScope.instanceEnv
  1929. if s.dynLookup {
  1930. newClassIns.privateMethods, newClassIns.privateFields = env.methods, env.fields
  1931. }
  1932. newClassIns.numPrivateMethods = uint32(len(env.methods))
  1933. newClassIns.numPrivateFields = uint32(len(env.fields))
  1934. newClassIns.hasPrivateEnv = len(e.c.classScope.privateNames) > 0
  1935. if (clsBinding != nil && clsBinding.useCount() > 0) || s.dynLookup {
  1936. if clsBinding != nil {
  1937. // Because this block may be in the middle of an expression, it's initial stack position
  1938. // cannot be known, and therefore it may not have any stack variables.
  1939. // Note, because clsBinding would be accessed through a function, it should already be in stash,
  1940. // this is just to make sure.
  1941. clsBinding.moveToStash()
  1942. clsBinding.emitInit()
  1943. }
  1944. } else {
  1945. if clsBinding != nil {
  1946. s.deleteBinding(clsBinding)
  1947. clsBinding = nil
  1948. }
  1949. e.c.p.code[mark0] = jump(1)
  1950. }
  1951. if staticsCount > 0 || hasStaticPrivateMethods {
  1952. ise := &initStaticElements{}
  1953. e.c.emit(ise)
  1954. env := e.c.classScope.staticEnv
  1955. staticInit.numPrivateFields = uint32(len(env.fields))
  1956. staticInit.numPrivateMethods = uint32(len(env.methods))
  1957. if s.dynLookup {
  1958. // These cannot be set on staticInit, because it is executed before ClassHeritage, and therefore
  1959. // the VM's PrivateEnvironment is still not set.
  1960. ise.privateFields = env.fields
  1961. ise.privateMethods = env.methods
  1962. }
  1963. } else {
  1964. e.c.emit(endVariadic) // re-using as semantics match
  1965. }
  1966. if !putOnStack {
  1967. e.c.emit(pop)
  1968. }
  1969. if clsBinding != nil || s.dynLookup {
  1970. e.c.leaveScopeBlock(enter)
  1971. e.c.assert(enter.stackSize == 0, e.offset, "enter.StackSize != 0 in compiledClassLiteral")
  1972. } else {
  1973. e.c.block = e.c.block.outer
  1974. }
  1975. if len(e.c.classScope.privateNames) > 0 {
  1976. e.c.emit(popPrivateEnv{})
  1977. }
  1978. e.c.classScope = e.c.classScope.outer
  1979. e.c.popScope()
  1980. }
  1981. func (e *compiledClassLiteral) compileFieldsAndStaticBlocks(elements []clsElement, funcName unistring.String) *Program {
  1982. savedPrg := e.c.p
  1983. savedBlock := e.c.block
  1984. defer func() {
  1985. e.c.p = savedPrg
  1986. e.c.block = savedBlock
  1987. }()
  1988. e.c.block = &block{
  1989. typ: blockScope,
  1990. }
  1991. e.c.p = &Program{
  1992. src: savedPrg.src,
  1993. funcName: funcName,
  1994. code: e.c.newCode(2, 16),
  1995. }
  1996. e.c.newScope()
  1997. s := e.c.scope
  1998. s.funcType = funcClsInit
  1999. thisBinding := s.createThisBinding()
  2000. valIdx := 0
  2001. for _, elt := range elements {
  2002. if elt.body != nil {
  2003. e.c.emit(dup) // this
  2004. elt.body.emitGetter(true)
  2005. elt.body.addSrcMap()
  2006. e.c.emit(call(0), pop)
  2007. } else {
  2008. if elt.computed {
  2009. e.c.emit(loadComputedKey(valIdx))
  2010. valIdx++
  2011. }
  2012. if init := elt.initializer; init != nil {
  2013. if !elt.computed {
  2014. e.c.emitNamedOrConst(init, elt.key)
  2015. } else {
  2016. e.c.emitExpr(init, true)
  2017. }
  2018. } else {
  2019. e.c.emit(loadUndef)
  2020. }
  2021. if elt.privateName != nil {
  2022. e.c.emit(&definePrivateProp{
  2023. idx: elt.privateName.idx,
  2024. })
  2025. } else if elt.computed {
  2026. e.c.emit(defineProp{})
  2027. } else {
  2028. e.c.emit(definePropKeyed(elt.key))
  2029. }
  2030. }
  2031. }
  2032. //e.c.emit(halt)
  2033. if s.isDynamic() || thisBinding.useCount() > 0 {
  2034. if s.isDynamic() || thisBinding.inStash {
  2035. thisBinding.emitInitAt(1)
  2036. }
  2037. } else {
  2038. s.deleteBinding(thisBinding)
  2039. }
  2040. stashSize, stackSize := s.finaliseVarAlloc(0)
  2041. e.c.assert(stackSize == 0, e.offset, "stackSize != 0 in initFields")
  2042. if stashSize > 0 {
  2043. e.c.assert(stashSize == 1, e.offset, "stashSize != 1 in initFields")
  2044. enter := &enterFunc{
  2045. stashSize: 1,
  2046. funcType: funcClsInit,
  2047. }
  2048. if s.dynLookup {
  2049. enter.names = s.makeNamesMap()
  2050. }
  2051. e.c.p.code[0] = enter
  2052. s.trimCode(0)
  2053. } else {
  2054. s.trimCode(2)
  2055. }
  2056. res := e.c.p
  2057. e.c.popScope()
  2058. return res
  2059. }
  2060. func (c *compiler) compileClassLiteral(v *ast.ClassLiteral, isExpr bool) *compiledClassLiteral {
  2061. if v.Name != nil {
  2062. c.checkIdentifierLName(v.Name.Name, int(v.Name.Idx)-1)
  2063. }
  2064. r := &compiledClassLiteral{
  2065. name: v.Name,
  2066. superClass: c.compileExpression(v.SuperClass),
  2067. body: v.Body,
  2068. source: v.Source,
  2069. isExpr: isExpr,
  2070. }
  2071. r.init(c, v.Idx0())
  2072. return r
  2073. }
  2074. func (c *compiler) compileCtor(ctor *ast.FunctionLiteral, derived bool) (p *Program, length int) {
  2075. f := c.compileFunctionLiteral(ctor, true)
  2076. if derived {
  2077. f.typ = funcDerivedCtor
  2078. } else {
  2079. f.typ = funcCtor
  2080. }
  2081. p, _, length, _ = f.compile()
  2082. return
  2083. }
  2084. func (c *compiler) compileArrowFunctionLiteral(v *ast.ArrowFunctionLiteral) *compiledFunctionLiteral {
  2085. var strictBody *ast.StringLiteral
  2086. var body []ast.Statement
  2087. switch b := v.Body.(type) {
  2088. case *ast.BlockStatement:
  2089. strictBody = c.isStrictStatement(b)
  2090. body = b.List
  2091. case *ast.ExpressionBody:
  2092. body = []ast.Statement{
  2093. &ast.ReturnStatement{
  2094. Argument: b.Expression,
  2095. },
  2096. }
  2097. default:
  2098. c.throwSyntaxError(int(b.Idx0())-1, "Unsupported ConciseBody type: %T", b)
  2099. }
  2100. r := &compiledFunctionLiteral{
  2101. parameterList: v.ParameterList,
  2102. body: body,
  2103. source: v.Source,
  2104. declarationList: v.DeclarationList,
  2105. isExpr: true,
  2106. typ: funcArrow,
  2107. strict: strictBody,
  2108. isAsync: v.Async,
  2109. }
  2110. r.init(c, v.Idx0())
  2111. return r
  2112. }
  2113. func (c *compiler) emitLoadThis() {
  2114. b, eval := c.scope.lookupThis()
  2115. if b != nil {
  2116. b.emitGet()
  2117. } else {
  2118. if eval {
  2119. c.emit(getThisDynamic{})
  2120. } else {
  2121. c.emit(loadGlobalObject)
  2122. }
  2123. }
  2124. }
  2125. func (e *compiledThisExpr) emitGetter(putOnStack bool) {
  2126. e.addSrcMap()
  2127. e.c.emitLoadThis()
  2128. if !putOnStack {
  2129. e.c.emit(pop)
  2130. }
  2131. }
  2132. func (e *compiledSuperExpr) emitGetter(putOnStack bool) {
  2133. if putOnStack {
  2134. e.c.emit(loadSuper)
  2135. }
  2136. }
  2137. func (e *compiledNewExpr) emitGetter(putOnStack bool) {
  2138. if e.isVariadic {
  2139. e.c.emit(startVariadic)
  2140. }
  2141. e.callee.emitGetter(true)
  2142. for _, expr := range e.args {
  2143. expr.emitGetter(true)
  2144. }
  2145. e.addSrcMap()
  2146. if e.isVariadic {
  2147. e.c.emit(newVariadic, endVariadic)
  2148. } else {
  2149. e.c.emit(_new(len(e.args)))
  2150. }
  2151. if !putOnStack {
  2152. e.c.emit(pop)
  2153. }
  2154. }
  2155. func (c *compiler) compileCallArgs(list []ast.Expression) (args []compiledExpr, isVariadic bool) {
  2156. args = make([]compiledExpr, len(list))
  2157. for i, argExpr := range list {
  2158. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  2159. args[i] = c.compileSpreadCallArgument(spread)
  2160. isVariadic = true
  2161. } else {
  2162. args[i] = c.compileExpression(argExpr)
  2163. }
  2164. }
  2165. return
  2166. }
  2167. func (c *compiler) compileNewExpression(v *ast.NewExpression) compiledExpr {
  2168. args, isVariadic := c.compileCallArgs(v.ArgumentList)
  2169. r := &compiledNewExpr{
  2170. compiledCallExpr: compiledCallExpr{
  2171. callee: c.compileExpression(v.Callee),
  2172. args: args,
  2173. isVariadic: isVariadic,
  2174. },
  2175. }
  2176. r.init(c, v.Idx0())
  2177. return r
  2178. }
  2179. func (e *compiledNewTarget) emitGetter(putOnStack bool) {
  2180. if s := e.c.scope.nearestThis(); s == nil || s.funcType == funcNone {
  2181. e.c.throwSyntaxError(e.offset, "new.target expression is not allowed here")
  2182. }
  2183. if putOnStack {
  2184. e.addSrcMap()
  2185. e.c.emit(loadNewTarget)
  2186. }
  2187. }
  2188. func (c *compiler) compileMetaProperty(v *ast.MetaProperty) compiledExpr {
  2189. if v.Meta.Name == "new" || v.Property.Name != "target" {
  2190. r := &compiledNewTarget{}
  2191. r.init(c, v.Idx0())
  2192. return r
  2193. }
  2194. c.throwSyntaxError(int(v.Idx)-1, "Unsupported meta property: %s.%s", v.Meta.Name, v.Property.Name)
  2195. return nil
  2196. }
  2197. func (e *compiledSequenceExpr) emitGetter(putOnStack bool) {
  2198. if len(e.sequence) > 0 {
  2199. for i := 0; i < len(e.sequence)-1; i++ {
  2200. e.sequence[i].emitGetter(false)
  2201. }
  2202. e.sequence[len(e.sequence)-1].emitGetter(putOnStack)
  2203. }
  2204. }
  2205. func (c *compiler) compileSequenceExpression(v *ast.SequenceExpression) compiledExpr {
  2206. s := make([]compiledExpr, len(v.Sequence))
  2207. for i, expr := range v.Sequence {
  2208. s[i] = c.compileExpression(expr)
  2209. }
  2210. r := &compiledSequenceExpr{
  2211. sequence: s,
  2212. }
  2213. var idx file.Idx
  2214. if len(v.Sequence) > 0 {
  2215. idx = v.Idx0()
  2216. }
  2217. r.init(c, idx)
  2218. return r
  2219. }
  2220. func (c *compiler) emitThrow(v Value) {
  2221. if o, ok := v.(*Object); ok {
  2222. t := nilSafe(o.self.getStr("name", nil)).toString().String()
  2223. switch t {
  2224. case "TypeError":
  2225. c.emit(loadDynamic(t))
  2226. msg := o.self.getStr("message", nil)
  2227. if msg != nil {
  2228. c.emit(loadVal(c.p.defineLiteralValue(msg)))
  2229. c.emit(_new(1))
  2230. } else {
  2231. c.emit(_new(0))
  2232. }
  2233. c.emit(throw)
  2234. return
  2235. }
  2236. }
  2237. c.assert(false, 0, "unknown exception type thrown while evaluating constant expression: %s", v.String())
  2238. panic("unreachable")
  2239. }
  2240. func (c *compiler) emitConst(expr compiledExpr, putOnStack bool) {
  2241. v, ex := c.evalConst(expr)
  2242. if ex == nil {
  2243. if putOnStack {
  2244. c.emit(loadVal(c.p.defineLiteralValue(v)))
  2245. }
  2246. } else {
  2247. c.emitThrow(ex.val)
  2248. }
  2249. }
  2250. func (c *compiler) evalConst(expr compiledExpr) (Value, *Exception) {
  2251. if expr, ok := expr.(*compiledLiteral); ok {
  2252. return expr.val, nil
  2253. }
  2254. if c.evalVM == nil {
  2255. c.evalVM = New().vm
  2256. }
  2257. var savedPrg *Program
  2258. createdPrg := false
  2259. if c.evalVM.prg == nil {
  2260. c.evalVM.prg = &Program{}
  2261. savedPrg = c.p
  2262. c.p = c.evalVM.prg
  2263. createdPrg = true
  2264. }
  2265. savedPc := len(c.p.code)
  2266. expr.emitGetter(true)
  2267. c.evalVM.pc = savedPc
  2268. ex := c.evalVM.runTry()
  2269. if createdPrg {
  2270. c.evalVM.prg = nil
  2271. c.evalVM.pc = 0
  2272. c.p = savedPrg
  2273. } else {
  2274. c.evalVM.prg.code = c.evalVM.prg.code[:savedPc]
  2275. c.p.code = c.evalVM.prg.code
  2276. }
  2277. if ex == nil {
  2278. return c.evalVM.pop(), nil
  2279. }
  2280. return nil, ex
  2281. }
  2282. func (e *compiledUnaryExpr) constant() bool {
  2283. return e.operand.constant()
  2284. }
  2285. func (e *compiledUnaryExpr) emitGetter(putOnStack bool) {
  2286. var prepare, body func()
  2287. toNumber := func() {
  2288. e.addSrcMap()
  2289. e.c.emit(toNumber)
  2290. }
  2291. switch e.operator {
  2292. case token.NOT:
  2293. e.operand.emitGetter(true)
  2294. e.c.emit(not)
  2295. goto end
  2296. case token.BITWISE_NOT:
  2297. e.operand.emitGetter(true)
  2298. e.c.emit(bnot)
  2299. goto end
  2300. case token.TYPEOF:
  2301. if o, ok := e.operand.(compiledExprOrRef); ok {
  2302. o.emitGetterOrRef()
  2303. } else {
  2304. e.operand.emitGetter(true)
  2305. }
  2306. e.c.emit(typeof)
  2307. goto end
  2308. case token.DELETE:
  2309. e.operand.deleteExpr().emitGetter(putOnStack)
  2310. return
  2311. case token.MINUS:
  2312. e.c.emitExpr(e.operand, true)
  2313. e.c.emit(neg)
  2314. goto end
  2315. case token.PLUS:
  2316. e.c.emitExpr(e.operand, true)
  2317. e.c.emit(plus)
  2318. goto end
  2319. case token.INCREMENT:
  2320. prepare = toNumber
  2321. body = func() {
  2322. e.c.emit(inc)
  2323. }
  2324. case token.DECREMENT:
  2325. prepare = toNumber
  2326. body = func() {
  2327. e.c.emit(dec)
  2328. }
  2329. case token.VOID:
  2330. e.c.emitExpr(e.operand, false)
  2331. if putOnStack {
  2332. e.c.emit(loadUndef)
  2333. }
  2334. return
  2335. default:
  2336. e.c.assert(false, e.offset, "Unknown unary operator: %s", e.operator.String())
  2337. panic("unreachable")
  2338. }
  2339. e.operand.emitUnary(prepare, body, e.postfix, putOnStack)
  2340. return
  2341. end:
  2342. if !putOnStack {
  2343. e.c.emit(pop)
  2344. }
  2345. }
  2346. func (c *compiler) compileUnaryExpression(v *ast.UnaryExpression) compiledExpr {
  2347. r := &compiledUnaryExpr{
  2348. operand: c.compileExpression(v.Operand),
  2349. operator: v.Operator,
  2350. postfix: v.Postfix,
  2351. }
  2352. r.init(c, v.Idx0())
  2353. return r
  2354. }
  2355. func (e *compiledConditionalExpr) emitGetter(putOnStack bool) {
  2356. e.test.emitGetter(true)
  2357. j := len(e.c.p.code)
  2358. e.c.emit(nil)
  2359. e.consequent.emitGetter(putOnStack)
  2360. j1 := len(e.c.p.code)
  2361. e.c.emit(nil)
  2362. e.c.p.code[j] = jne(len(e.c.p.code) - j)
  2363. e.alternate.emitGetter(putOnStack)
  2364. e.c.p.code[j1] = jump(len(e.c.p.code) - j1)
  2365. }
  2366. func (c *compiler) compileConditionalExpression(v *ast.ConditionalExpression) compiledExpr {
  2367. r := &compiledConditionalExpr{
  2368. test: c.compileExpression(v.Test),
  2369. consequent: c.compileExpression(v.Consequent),
  2370. alternate: c.compileExpression(v.Alternate),
  2371. }
  2372. r.init(c, v.Idx0())
  2373. return r
  2374. }
  2375. func (e *compiledLogicalOr) constant() bool {
  2376. if e.left.constant() {
  2377. if v, ex := e.c.evalConst(e.left); ex == nil {
  2378. if v.ToBoolean() {
  2379. return true
  2380. }
  2381. return e.right.constant()
  2382. } else {
  2383. return true
  2384. }
  2385. }
  2386. return false
  2387. }
  2388. func (e *compiledLogicalOr) emitGetter(putOnStack bool) {
  2389. if e.left.constant() {
  2390. if v, ex := e.c.evalConst(e.left); ex == nil {
  2391. if !v.ToBoolean() {
  2392. e.c.emitExpr(e.right, putOnStack)
  2393. } else {
  2394. if putOnStack {
  2395. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  2396. }
  2397. }
  2398. } else {
  2399. e.c.emitThrow(ex.val)
  2400. }
  2401. return
  2402. }
  2403. e.c.emitExpr(e.left, true)
  2404. j := len(e.c.p.code)
  2405. e.addSrcMap()
  2406. e.c.emit(nil)
  2407. e.c.emitExpr(e.right, true)
  2408. e.c.p.code[j] = jeq1(len(e.c.p.code) - j)
  2409. if !putOnStack {
  2410. e.c.emit(pop)
  2411. }
  2412. }
  2413. func (e *compiledCoalesce) constant() bool {
  2414. if e.left.constant() {
  2415. if v, ex := e.c.evalConst(e.left); ex == nil {
  2416. if v != _null && v != _undefined {
  2417. return true
  2418. }
  2419. return e.right.constant()
  2420. } else {
  2421. return true
  2422. }
  2423. }
  2424. return false
  2425. }
  2426. func (e *compiledCoalesce) emitGetter(putOnStack bool) {
  2427. if e.left.constant() {
  2428. if v, ex := e.c.evalConst(e.left); ex == nil {
  2429. if v == _undefined || v == _null {
  2430. e.c.emitExpr(e.right, putOnStack)
  2431. } else {
  2432. if putOnStack {
  2433. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  2434. }
  2435. }
  2436. } else {
  2437. e.c.emitThrow(ex.val)
  2438. }
  2439. return
  2440. }
  2441. e.c.emitExpr(e.left, true)
  2442. j := len(e.c.p.code)
  2443. e.addSrcMap()
  2444. e.c.emit(nil)
  2445. e.c.emitExpr(e.right, true)
  2446. e.c.p.code[j] = jcoalesc(len(e.c.p.code) - j)
  2447. if !putOnStack {
  2448. e.c.emit(pop)
  2449. }
  2450. }
  2451. func (e *compiledLogicalAnd) constant() bool {
  2452. if e.left.constant() {
  2453. if v, ex := e.c.evalConst(e.left); ex == nil {
  2454. if !v.ToBoolean() {
  2455. return true
  2456. } else {
  2457. return e.right.constant()
  2458. }
  2459. } else {
  2460. return true
  2461. }
  2462. }
  2463. return false
  2464. }
  2465. func (e *compiledLogicalAnd) emitGetter(putOnStack bool) {
  2466. var j int
  2467. if e.left.constant() {
  2468. if v, ex := e.c.evalConst(e.left); ex == nil {
  2469. if !v.ToBoolean() {
  2470. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  2471. } else {
  2472. e.c.emitExpr(e.right, putOnStack)
  2473. }
  2474. } else {
  2475. e.c.emitThrow(ex.val)
  2476. }
  2477. return
  2478. }
  2479. e.left.emitGetter(true)
  2480. j = len(e.c.p.code)
  2481. e.addSrcMap()
  2482. e.c.emit(nil)
  2483. e.c.emitExpr(e.right, true)
  2484. e.c.p.code[j] = jneq1(len(e.c.p.code) - j)
  2485. if !putOnStack {
  2486. e.c.emit(pop)
  2487. }
  2488. }
  2489. func (e *compiledBinaryExpr) constant() bool {
  2490. return e.left.constant() && e.right.constant()
  2491. }
  2492. func (e *compiledBinaryExpr) emitGetter(putOnStack bool) {
  2493. e.c.emitExpr(e.left, true)
  2494. e.c.emitExpr(e.right, true)
  2495. e.addSrcMap()
  2496. switch e.operator {
  2497. case token.LESS:
  2498. e.c.emit(op_lt)
  2499. case token.GREATER:
  2500. e.c.emit(op_gt)
  2501. case token.LESS_OR_EQUAL:
  2502. e.c.emit(op_lte)
  2503. case token.GREATER_OR_EQUAL:
  2504. e.c.emit(op_gte)
  2505. case token.EQUAL:
  2506. e.c.emit(op_eq)
  2507. case token.NOT_EQUAL:
  2508. e.c.emit(op_neq)
  2509. case token.STRICT_EQUAL:
  2510. e.c.emit(op_strict_eq)
  2511. case token.STRICT_NOT_EQUAL:
  2512. e.c.emit(op_strict_neq)
  2513. case token.PLUS:
  2514. e.c.emit(add)
  2515. case token.MINUS:
  2516. e.c.emit(sub)
  2517. case token.MULTIPLY:
  2518. e.c.emit(mul)
  2519. case token.EXPONENT:
  2520. e.c.emit(exp)
  2521. case token.SLASH:
  2522. e.c.emit(div)
  2523. case token.REMAINDER:
  2524. e.c.emit(mod)
  2525. case token.AND:
  2526. e.c.emit(and)
  2527. case token.OR:
  2528. e.c.emit(or)
  2529. case token.EXCLUSIVE_OR:
  2530. e.c.emit(xor)
  2531. case token.INSTANCEOF:
  2532. e.c.emit(op_instanceof)
  2533. case token.IN:
  2534. e.c.emit(op_in)
  2535. case token.SHIFT_LEFT:
  2536. e.c.emit(sal)
  2537. case token.SHIFT_RIGHT:
  2538. e.c.emit(sar)
  2539. case token.UNSIGNED_SHIFT_RIGHT:
  2540. e.c.emit(shr)
  2541. default:
  2542. e.c.assert(false, e.offset, "Unknown operator: %s", e.operator.String())
  2543. panic("unreachable")
  2544. }
  2545. if !putOnStack {
  2546. e.c.emit(pop)
  2547. }
  2548. }
  2549. func (c *compiler) compileBinaryExpression(v *ast.BinaryExpression) compiledExpr {
  2550. switch v.Operator {
  2551. case token.LOGICAL_OR:
  2552. return c.compileLogicalOr(v.Left, v.Right, v.Idx0())
  2553. case token.COALESCE:
  2554. return c.compileCoalesce(v.Left, v.Right, v.Idx0())
  2555. case token.LOGICAL_AND:
  2556. return c.compileLogicalAnd(v.Left, v.Right, v.Idx0())
  2557. }
  2558. if id, ok := v.Left.(*ast.PrivateIdentifier); ok {
  2559. return c.compilePrivateIn(id, v.Right, id.Idx)
  2560. }
  2561. r := &compiledBinaryExpr{
  2562. left: c.compileExpression(v.Left),
  2563. right: c.compileExpression(v.Right),
  2564. operator: v.Operator,
  2565. }
  2566. r.init(c, v.Idx0())
  2567. return r
  2568. }
  2569. type compiledPrivateIn struct {
  2570. baseCompiledExpr
  2571. id unistring.String
  2572. right compiledExpr
  2573. }
  2574. func (e *compiledPrivateIn) emitGetter(putOnStack bool) {
  2575. e.right.emitGetter(true)
  2576. rn, id := e.c.resolvePrivateName(e.id, e.offset)
  2577. if rn != nil {
  2578. e.c.emit((*privateInRes)(rn))
  2579. } else {
  2580. e.c.emit((*privateInId)(id))
  2581. }
  2582. if !putOnStack {
  2583. e.c.emit(pop)
  2584. }
  2585. }
  2586. func (c *compiler) compilePrivateIn(id *ast.PrivateIdentifier, right ast.Expression, idx file.Idx) compiledExpr {
  2587. r := &compiledPrivateIn{
  2588. id: id.Name,
  2589. right: c.compileExpression(right),
  2590. }
  2591. r.init(c, idx)
  2592. return r
  2593. }
  2594. func (c *compiler) compileLogicalOr(left, right ast.Expression, idx file.Idx) compiledExpr {
  2595. r := &compiledLogicalOr{
  2596. left: c.compileExpression(left),
  2597. right: c.compileExpression(right),
  2598. }
  2599. r.init(c, idx)
  2600. return r
  2601. }
  2602. func (c *compiler) compileCoalesce(left, right ast.Expression, idx file.Idx) compiledExpr {
  2603. r := &compiledCoalesce{
  2604. left: c.compileExpression(left),
  2605. right: c.compileExpression(right),
  2606. }
  2607. r.init(c, idx)
  2608. return r
  2609. }
  2610. func (c *compiler) compileLogicalAnd(left, right ast.Expression, idx file.Idx) compiledExpr {
  2611. r := &compiledLogicalAnd{
  2612. left: c.compileExpression(left),
  2613. right: c.compileExpression(right),
  2614. }
  2615. r.init(c, idx)
  2616. return r
  2617. }
  2618. func (e *compiledObjectLiteral) emitGetter(putOnStack bool) {
  2619. e.addSrcMap()
  2620. e.c.emit(newObject)
  2621. hasProto := false
  2622. for _, prop := range e.expr.Value {
  2623. switch prop := prop.(type) {
  2624. case *ast.PropertyKeyed:
  2625. key, computed := e.c.processKey(prop.Key)
  2626. valueExpr := e.c.compileExpression(prop.Value)
  2627. var ne namedEmitter
  2628. if fn, ok := valueExpr.(*compiledFunctionLiteral); ok {
  2629. if fn.name == nil {
  2630. ne = fn
  2631. }
  2632. switch prop.Kind {
  2633. case ast.PropertyKindMethod, ast.PropertyKindGet, ast.PropertyKindSet:
  2634. fn.typ = funcMethod
  2635. if computed {
  2636. fn.homeObjOffset = 2
  2637. } else {
  2638. fn.homeObjOffset = 1
  2639. }
  2640. }
  2641. } else if v, ok := valueExpr.(namedEmitter); ok {
  2642. ne = v
  2643. }
  2644. if computed {
  2645. e.c.emit(_toPropertyKey{})
  2646. e.c.emitExpr(valueExpr, true)
  2647. switch prop.Kind {
  2648. case ast.PropertyKindValue:
  2649. if ne != nil {
  2650. e.c.emit(setElem1Named)
  2651. } else {
  2652. e.c.emit(setElem1)
  2653. }
  2654. case ast.PropertyKindMethod:
  2655. e.c.emit(&defineMethod{enumerable: true})
  2656. case ast.PropertyKindGet:
  2657. e.c.emit(&defineGetter{enumerable: true})
  2658. case ast.PropertyKindSet:
  2659. e.c.emit(&defineSetter{enumerable: true})
  2660. default:
  2661. e.c.assert(false, e.offset, "unknown property kind: %s", prop.Kind)
  2662. panic("unreachable")
  2663. }
  2664. } else {
  2665. isProto := key == __proto__ && !prop.Computed
  2666. if isProto {
  2667. if hasProto {
  2668. e.c.throwSyntaxError(int(prop.Idx0())-1, "Duplicate __proto__ fields are not allowed in object literals")
  2669. } else {
  2670. hasProto = true
  2671. }
  2672. }
  2673. if ne != nil && !isProto {
  2674. ne.emitNamed(key)
  2675. } else {
  2676. e.c.emitExpr(valueExpr, true)
  2677. }
  2678. switch prop.Kind {
  2679. case ast.PropertyKindValue:
  2680. if isProto {
  2681. e.c.emit(setProto)
  2682. } else {
  2683. e.c.emit(putProp(key))
  2684. }
  2685. case ast.PropertyKindMethod:
  2686. e.c.emit(&defineMethodKeyed{key: key, enumerable: true})
  2687. case ast.PropertyKindGet:
  2688. e.c.emit(&defineGetterKeyed{key: key, enumerable: true})
  2689. case ast.PropertyKindSet:
  2690. e.c.emit(&defineSetterKeyed{key: key, enumerable: true})
  2691. default:
  2692. e.c.assert(false, e.offset, "unknown property kind: %s", prop.Kind)
  2693. panic("unreachable")
  2694. }
  2695. }
  2696. case *ast.PropertyShort:
  2697. key := prop.Name.Name
  2698. if prop.Initializer != nil {
  2699. e.c.throwSyntaxError(int(prop.Initializer.Idx0())-1, "Invalid shorthand property initializer")
  2700. }
  2701. if e.c.scope.strict && key == "let" {
  2702. e.c.throwSyntaxError(e.offset, "'let' cannot be used as a shorthand property in strict mode")
  2703. }
  2704. e.c.compileIdentifierExpression(&prop.Name).emitGetter(true)
  2705. e.c.emit(putProp(key))
  2706. case *ast.SpreadElement:
  2707. e.c.compileExpression(prop.Expression).emitGetter(true)
  2708. e.c.emit(copySpread)
  2709. default:
  2710. e.c.assert(false, e.offset, "unknown Property type: %T", prop)
  2711. panic("unreachable")
  2712. }
  2713. }
  2714. if !putOnStack {
  2715. e.c.emit(pop)
  2716. }
  2717. }
  2718. func (c *compiler) compileObjectLiteral(v *ast.ObjectLiteral) compiledExpr {
  2719. r := &compiledObjectLiteral{
  2720. expr: v,
  2721. }
  2722. r.init(c, v.Idx0())
  2723. return r
  2724. }
  2725. func (e *compiledArrayLiteral) emitGetter(putOnStack bool) {
  2726. e.addSrcMap()
  2727. hasSpread := false
  2728. mark := len(e.c.p.code)
  2729. e.c.emit(nil)
  2730. for _, v := range e.expr.Value {
  2731. if spread, ok := v.(*ast.SpreadElement); ok {
  2732. hasSpread = true
  2733. e.c.compileExpression(spread.Expression).emitGetter(true)
  2734. e.c.emit(pushArraySpread)
  2735. } else {
  2736. if v != nil {
  2737. e.c.emitExpr(e.c.compileExpression(v), true)
  2738. } else {
  2739. e.c.emit(loadNil)
  2740. }
  2741. e.c.emit(pushArrayItem)
  2742. }
  2743. }
  2744. var objCount uint32
  2745. if !hasSpread {
  2746. objCount = uint32(len(e.expr.Value))
  2747. }
  2748. e.c.p.code[mark] = newArray(objCount)
  2749. if !putOnStack {
  2750. e.c.emit(pop)
  2751. }
  2752. }
  2753. func (c *compiler) compileArrayLiteral(v *ast.ArrayLiteral) compiledExpr {
  2754. r := &compiledArrayLiteral{
  2755. expr: v,
  2756. }
  2757. r.init(c, v.Idx0())
  2758. return r
  2759. }
  2760. func (e *compiledRegexpLiteral) emitGetter(putOnStack bool) {
  2761. if putOnStack {
  2762. pattern, err := compileRegexp(e.expr.Pattern, e.expr.Flags)
  2763. if err != nil {
  2764. e.c.throwSyntaxError(e.offset, err.Error())
  2765. }
  2766. e.c.emit(&newRegexp{pattern: pattern, src: newStringValue(e.expr.Pattern)})
  2767. }
  2768. }
  2769. func (c *compiler) compileRegexpLiteral(v *ast.RegExpLiteral) compiledExpr {
  2770. r := &compiledRegexpLiteral{
  2771. expr: v,
  2772. }
  2773. r.init(c, v.Idx0())
  2774. return r
  2775. }
  2776. func (c *compiler) emitCallee(callee compiledExpr) (calleeName unistring.String) {
  2777. switch callee := callee.(type) {
  2778. case *compiledDotExpr:
  2779. callee.left.emitGetter(true)
  2780. c.emit(getPropCallee(callee.name))
  2781. case *compiledPrivateDotExpr:
  2782. callee.left.emitGetter(true)
  2783. rn, id := c.resolvePrivateName(callee.name, callee.offset)
  2784. if rn != nil {
  2785. c.emit((*getPrivatePropResCallee)(rn))
  2786. } else {
  2787. c.emit((*getPrivatePropIdCallee)(id))
  2788. }
  2789. case *compiledSuperDotExpr:
  2790. c.emitLoadThis()
  2791. c.emit(loadSuper)
  2792. c.emit(getPropRecvCallee(callee.name))
  2793. case *compiledBracketExpr:
  2794. callee.left.emitGetter(true)
  2795. callee.member.emitGetter(true)
  2796. c.emit(getElemCallee)
  2797. case *compiledSuperBracketExpr:
  2798. c.emitLoadThis()
  2799. c.emit(loadSuper)
  2800. callee.member.emitGetter(true)
  2801. c.emit(getElemRecvCallee)
  2802. case *compiledIdentifierExpr:
  2803. calleeName = callee.name
  2804. callee.emitGetterAndCallee()
  2805. case *compiledOptionalChain:
  2806. c.startOptChain()
  2807. c.emitCallee(callee.expr)
  2808. c.endOptChain()
  2809. case *compiledOptional:
  2810. c.emitCallee(callee.expr)
  2811. c.block.conts = append(c.block.conts, len(c.p.code))
  2812. c.emit(nil)
  2813. case *compiledSuperExpr:
  2814. // no-op
  2815. default:
  2816. c.emit(loadUndef)
  2817. callee.emitGetter(true)
  2818. }
  2819. return
  2820. }
  2821. func (e *compiledCallExpr) emitGetter(putOnStack bool) {
  2822. if e.isVariadic {
  2823. e.c.emit(startVariadic)
  2824. }
  2825. calleeName := e.c.emitCallee(e.callee)
  2826. for _, expr := range e.args {
  2827. expr.emitGetter(true)
  2828. }
  2829. e.addSrcMap()
  2830. if _, ok := e.callee.(*compiledSuperExpr); ok {
  2831. b, eval := e.c.scope.lookupThis()
  2832. e.c.assert(eval || b != nil, e.offset, "super call, but no 'this' binding")
  2833. if eval {
  2834. e.c.emit(resolveThisDynamic{})
  2835. } else {
  2836. b.markAccessPoint()
  2837. e.c.emit(resolveThisStack{})
  2838. }
  2839. if e.isVariadic {
  2840. e.c.emit(superCallVariadic)
  2841. } else {
  2842. e.c.emit(superCall(len(e.args)))
  2843. }
  2844. } else if calleeName == "eval" {
  2845. foundVar := false
  2846. for sc := e.c.scope; sc != nil; sc = sc.outer {
  2847. if !foundVar && (sc.variable || sc.isFunction()) {
  2848. foundVar = true
  2849. if !sc.strict {
  2850. sc.dynamic = true
  2851. }
  2852. }
  2853. sc.dynLookup = true
  2854. }
  2855. if e.c.scope.strict {
  2856. if e.isVariadic {
  2857. e.c.emit(callEvalVariadicStrict)
  2858. } else {
  2859. e.c.emit(callEvalStrict(len(e.args)))
  2860. }
  2861. } else {
  2862. if e.isVariadic {
  2863. e.c.emit(callEvalVariadic)
  2864. } else {
  2865. e.c.emit(callEval(len(e.args)))
  2866. }
  2867. }
  2868. } else {
  2869. if e.isVariadic {
  2870. e.c.emit(callVariadic)
  2871. } else {
  2872. e.c.emit(call(len(e.args)))
  2873. }
  2874. }
  2875. if e.isVariadic {
  2876. e.c.emit(endVariadic)
  2877. }
  2878. if !putOnStack {
  2879. e.c.emit(pop)
  2880. }
  2881. }
  2882. func (e *compiledCallExpr) deleteExpr() compiledExpr {
  2883. r := &defaultDeleteExpr{
  2884. expr: e,
  2885. }
  2886. r.init(e.c, file.Idx(e.offset+1))
  2887. return r
  2888. }
  2889. func (c *compiler) compileSpreadCallArgument(spread *ast.SpreadElement) compiledExpr {
  2890. r := &compiledSpreadCallArgument{
  2891. expr: c.compileExpression(spread.Expression),
  2892. }
  2893. r.init(c, spread.Idx0())
  2894. return r
  2895. }
  2896. func (c *compiler) compileCallee(v ast.Expression) compiledExpr {
  2897. if sup, ok := v.(*ast.SuperExpression); ok {
  2898. if s := c.scope.nearestThis(); s != nil && s.funcType == funcDerivedCtor {
  2899. e := &compiledSuperExpr{}
  2900. e.init(c, sup.Idx)
  2901. return e
  2902. }
  2903. c.throwSyntaxError(int(v.Idx0())-1, "'super' keyword unexpected here")
  2904. panic("unreachable")
  2905. }
  2906. return c.compileExpression(v)
  2907. }
  2908. func (c *compiler) compileCallExpression(v *ast.CallExpression) compiledExpr {
  2909. args := make([]compiledExpr, len(v.ArgumentList))
  2910. isVariadic := false
  2911. for i, argExpr := range v.ArgumentList {
  2912. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  2913. args[i] = c.compileSpreadCallArgument(spread)
  2914. isVariadic = true
  2915. } else {
  2916. args[i] = c.compileExpression(argExpr)
  2917. }
  2918. }
  2919. r := &compiledCallExpr{
  2920. args: args,
  2921. callee: c.compileCallee(v.Callee),
  2922. isVariadic: isVariadic,
  2923. }
  2924. r.init(c, v.LeftParenthesis)
  2925. return r
  2926. }
  2927. func (c *compiler) compileIdentifierExpression(v *ast.Identifier) compiledExpr {
  2928. if c.scope.strict {
  2929. c.checkIdentifierName(v.Name, int(v.Idx)-1)
  2930. }
  2931. r := &compiledIdentifierExpr{
  2932. name: v.Name,
  2933. }
  2934. r.offset = int(v.Idx) - 1
  2935. r.init(c, v.Idx0())
  2936. return r
  2937. }
  2938. func (c *compiler) compileNumberLiteral(v *ast.NumberLiteral) compiledExpr {
  2939. if c.scope.strict && len(v.Literal) > 1 && v.Literal[0] == '0' && v.Literal[1] <= '7' && v.Literal[1] >= '0' {
  2940. c.throwSyntaxError(int(v.Idx)-1, "Octal literals are not allowed in strict mode")
  2941. panic("Unreachable")
  2942. }
  2943. var val Value
  2944. switch num := v.Value.(type) {
  2945. case int64:
  2946. val = intToValue(num)
  2947. case float64:
  2948. val = floatToValue(num)
  2949. default:
  2950. c.assert(false, int(v.Idx)-1, "Unsupported number literal type: %T", v.Value)
  2951. panic("unreachable")
  2952. }
  2953. r := &compiledLiteral{
  2954. val: val,
  2955. }
  2956. r.init(c, v.Idx0())
  2957. return r
  2958. }
  2959. func (c *compiler) compileStringLiteral(v *ast.StringLiteral) compiledExpr {
  2960. r := &compiledLiteral{
  2961. val: stringValueFromRaw(v.Value),
  2962. }
  2963. r.init(c, v.Idx0())
  2964. return r
  2965. }
  2966. func (c *compiler) compileTemplateLiteral(v *ast.TemplateLiteral) compiledExpr {
  2967. r := &compiledTemplateLiteral{}
  2968. if v.Tag != nil {
  2969. r.tag = c.compileExpression(v.Tag)
  2970. }
  2971. ce := make([]compiledExpr, len(v.Expressions))
  2972. for i, expr := range v.Expressions {
  2973. ce[i] = c.compileExpression(expr)
  2974. }
  2975. r.expressions = ce
  2976. r.elements = v.Elements
  2977. r.init(c, v.Idx0())
  2978. return r
  2979. }
  2980. func (c *compiler) compileBooleanLiteral(v *ast.BooleanLiteral) compiledExpr {
  2981. var val Value
  2982. if v.Value {
  2983. val = valueTrue
  2984. } else {
  2985. val = valueFalse
  2986. }
  2987. r := &compiledLiteral{
  2988. val: val,
  2989. }
  2990. r.init(c, v.Idx0())
  2991. return r
  2992. }
  2993. func (c *compiler) compileAssignExpression(v *ast.AssignExpression) compiledExpr {
  2994. // log.Printf("compileAssignExpression(): %+v", v)
  2995. r := &compiledAssignExpr{
  2996. left: c.compileExpression(v.Left),
  2997. right: c.compileExpression(v.Right),
  2998. operator: v.Operator,
  2999. }
  3000. r.init(c, v.Idx0())
  3001. return r
  3002. }
  3003. func (e *compiledEnumGetExpr) emitGetter(putOnStack bool) {
  3004. e.c.emit(enumGet)
  3005. if !putOnStack {
  3006. e.c.emit(pop)
  3007. }
  3008. }
  3009. func (c *compiler) compileObjectAssignmentPattern(v *ast.ObjectPattern) compiledExpr {
  3010. r := &compiledObjectAssignmentPattern{
  3011. expr: v,
  3012. }
  3013. r.init(c, v.Idx0())
  3014. return r
  3015. }
  3016. func (e *compiledObjectAssignmentPattern) emitGetter(putOnStack bool) {
  3017. if putOnStack {
  3018. e.c.emit(loadUndef)
  3019. }
  3020. }
  3021. func (c *compiler) compileArrayAssignmentPattern(v *ast.ArrayPattern) compiledExpr {
  3022. r := &compiledArrayAssignmentPattern{
  3023. expr: v,
  3024. }
  3025. r.init(c, v.Idx0())
  3026. return r
  3027. }
  3028. func (e *compiledArrayAssignmentPattern) emitGetter(putOnStack bool) {
  3029. if putOnStack {
  3030. e.c.emit(loadUndef)
  3031. }
  3032. }
  3033. func (c *compiler) emitExpr(expr compiledExpr, putOnStack bool) {
  3034. if expr.constant() {
  3035. c.emitConst(expr, putOnStack)
  3036. } else {
  3037. expr.emitGetter(putOnStack)
  3038. }
  3039. }
  3040. type namedEmitter interface {
  3041. emitNamed(name unistring.String)
  3042. }
  3043. func (c *compiler) emitNamed(expr compiledExpr, name unistring.String) {
  3044. if en, ok := expr.(namedEmitter); ok {
  3045. en.emitNamed(name)
  3046. } else {
  3047. expr.emitGetter(true)
  3048. }
  3049. }
  3050. func (c *compiler) emitNamedOrConst(expr compiledExpr, name unistring.String) {
  3051. if expr.constant() {
  3052. c.emitConst(expr, true)
  3053. } else {
  3054. c.emitNamed(expr, name)
  3055. }
  3056. }
  3057. func (e *compiledFunctionLiteral) emitNamed(name unistring.String) {
  3058. e.lhsName = name
  3059. e.emitGetter(true)
  3060. }
  3061. func (e *compiledClassLiteral) emitNamed(name unistring.String) {
  3062. e.lhsName = name
  3063. e.emitGetter(true)
  3064. }
  3065. func (c *compiler) emitPattern(pattern ast.Pattern, emitter func(target, init compiledExpr), putOnStack bool) {
  3066. switch pattern := pattern.(type) {
  3067. case *ast.ObjectPattern:
  3068. c.emitObjectPattern(pattern, emitter, putOnStack)
  3069. case *ast.ArrayPattern:
  3070. c.emitArrayPattern(pattern, emitter, putOnStack)
  3071. default:
  3072. c.assert(false, int(pattern.Idx0())-1, "unsupported Pattern: %T", pattern)
  3073. panic("unreachable")
  3074. }
  3075. }
  3076. func (c *compiler) emitAssign(target ast.Expression, init compiledExpr, emitAssignSimple func(target, init compiledExpr)) {
  3077. pattern, isPattern := target.(ast.Pattern)
  3078. if isPattern {
  3079. init.emitGetter(true)
  3080. c.emitPattern(pattern, emitAssignSimple, false)
  3081. } else {
  3082. emitAssignSimple(c.compileExpression(target), init)
  3083. }
  3084. }
  3085. func (c *compiler) emitObjectPattern(pattern *ast.ObjectPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  3086. if pattern.Rest != nil {
  3087. c.emit(createDestructSrc)
  3088. } else {
  3089. c.emit(checkObjectCoercible)
  3090. }
  3091. for _, prop := range pattern.Properties {
  3092. switch prop := prop.(type) {
  3093. case *ast.PropertyShort:
  3094. c.emit(dup)
  3095. emitAssign(c.compileIdentifierExpression(&prop.Name), c.compilePatternInitExpr(func() {
  3096. c.emit(getProp(prop.Name.Name))
  3097. }, prop.Initializer, prop.Idx0()))
  3098. case *ast.PropertyKeyed:
  3099. c.emit(dup)
  3100. c.compileExpression(prop.Key).emitGetter(true)
  3101. c.emit(_toPropertyKey{})
  3102. var target ast.Expression
  3103. var initializer ast.Expression
  3104. if e, ok := prop.Value.(*ast.AssignExpression); ok {
  3105. target = e.Left
  3106. initializer = e.Right
  3107. } else {
  3108. target = prop.Value
  3109. }
  3110. c.emitAssign(target, c.compilePatternInitExpr(func() {
  3111. c.emit(getKey)
  3112. }, initializer, prop.Idx0()), emitAssign)
  3113. default:
  3114. c.throwSyntaxError(int(prop.Idx0()-1), "Unsupported AssignmentProperty type: %T", prop)
  3115. }
  3116. }
  3117. if pattern.Rest != nil {
  3118. emitAssign(c.compileExpression(pattern.Rest), c.compileEmitterExpr(func() {
  3119. c.emit(copyRest)
  3120. }, pattern.Rest.Idx0()))
  3121. c.emit(pop)
  3122. }
  3123. if !putOnStack {
  3124. c.emit(pop)
  3125. }
  3126. }
  3127. func (c *compiler) emitArrayPattern(pattern *ast.ArrayPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  3128. c.emit(iterate)
  3129. for _, elt := range pattern.Elements {
  3130. switch elt := elt.(type) {
  3131. case nil:
  3132. c.emit(iterGetNextOrUndef{}, pop)
  3133. case *ast.AssignExpression:
  3134. c.emitAssign(elt.Left, c.compilePatternInitExpr(func() {
  3135. c.emit(iterGetNextOrUndef{})
  3136. }, elt.Right, elt.Idx0()), emitAssign)
  3137. default:
  3138. c.emitAssign(elt, c.compileEmitterExpr(func() {
  3139. c.emit(iterGetNextOrUndef{})
  3140. }, elt.Idx0()), emitAssign)
  3141. }
  3142. }
  3143. if pattern.Rest != nil {
  3144. c.emitAssign(pattern.Rest, c.compileEmitterExpr(func() {
  3145. c.emit(newArrayFromIter)
  3146. }, pattern.Rest.Idx0()), emitAssign)
  3147. } else {
  3148. c.emit(enumPopClose)
  3149. }
  3150. if !putOnStack {
  3151. c.emit(pop)
  3152. }
  3153. }
  3154. func (e *compiledObjectAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  3155. valueExpr.emitGetter(true)
  3156. e.c.emitObjectPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  3157. }
  3158. func (e *compiledArrayAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  3159. valueExpr.emitGetter(true)
  3160. e.c.emitArrayPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  3161. }
  3162. type compiledPatternInitExpr struct {
  3163. baseCompiledExpr
  3164. emitSrc func()
  3165. def compiledExpr
  3166. }
  3167. func (e *compiledPatternInitExpr) emitGetter(putOnStack bool) {
  3168. if !putOnStack {
  3169. return
  3170. }
  3171. e.emitSrc()
  3172. if e.def != nil {
  3173. mark := len(e.c.p.code)
  3174. e.c.emit(nil)
  3175. e.c.emitExpr(e.def, true)
  3176. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  3177. }
  3178. }
  3179. func (e *compiledPatternInitExpr) emitNamed(name unistring.String) {
  3180. e.emitSrc()
  3181. if e.def != nil {
  3182. mark := len(e.c.p.code)
  3183. e.c.emit(nil)
  3184. e.c.emitNamedOrConst(e.def, name)
  3185. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  3186. }
  3187. }
  3188. func (c *compiler) compilePatternInitExpr(emitSrc func(), def ast.Expression, idx file.Idx) compiledExpr {
  3189. r := &compiledPatternInitExpr{
  3190. emitSrc: emitSrc,
  3191. def: c.compileExpression(def),
  3192. }
  3193. r.init(c, idx)
  3194. return r
  3195. }
  3196. type compiledEmitterExpr struct {
  3197. baseCompiledExpr
  3198. emitter func()
  3199. namedEmitter func(name unistring.String)
  3200. }
  3201. func (e *compiledEmitterExpr) emitGetter(putOnStack bool) {
  3202. if e.emitter != nil {
  3203. e.emitter()
  3204. } else {
  3205. e.namedEmitter("")
  3206. }
  3207. if !putOnStack {
  3208. e.c.emit(pop)
  3209. }
  3210. }
  3211. func (e *compiledEmitterExpr) emitNamed(name unistring.String) {
  3212. if e.namedEmitter != nil {
  3213. e.namedEmitter(name)
  3214. } else {
  3215. e.emitter()
  3216. }
  3217. }
  3218. func (c *compiler) compileEmitterExpr(emitter func(), idx file.Idx) *compiledEmitterExpr {
  3219. r := &compiledEmitterExpr{
  3220. emitter: emitter,
  3221. }
  3222. r.init(c, idx)
  3223. return r
  3224. }
  3225. func (e *compiledSpreadCallArgument) emitGetter(putOnStack bool) {
  3226. e.expr.emitGetter(putOnStack)
  3227. if putOnStack {
  3228. e.c.emit(pushSpread)
  3229. }
  3230. }
  3231. func (c *compiler) startOptChain() {
  3232. c.block = &block{
  3233. typ: blockOptChain,
  3234. outer: c.block,
  3235. }
  3236. }
  3237. func (c *compiler) endOptChain() {
  3238. lbl := len(c.p.code)
  3239. for _, item := range c.block.breaks {
  3240. c.p.code[item] = jopt(lbl - item)
  3241. }
  3242. for _, item := range c.block.conts {
  3243. c.p.code[item] = joptc(lbl - item)
  3244. }
  3245. c.block = c.block.outer
  3246. }
  3247. func (e *compiledOptionalChain) emitGetter(putOnStack bool) {
  3248. e.c.startOptChain()
  3249. e.expr.emitGetter(true)
  3250. e.c.endOptChain()
  3251. if !putOnStack {
  3252. e.c.emit(pop)
  3253. }
  3254. }
  3255. func (e *compiledOptional) emitGetter(putOnStack bool) {
  3256. e.expr.emitGetter(putOnStack)
  3257. if putOnStack {
  3258. e.c.block.breaks = append(e.c.block.breaks, len(e.c.p.code))
  3259. e.c.emit(nil)
  3260. }
  3261. }
  3262. func (e *compiledAwaitExpression) emitGetter(putOnStack bool) {
  3263. e.arg.emitGetter(true)
  3264. e.c.emit(await{})
  3265. if !putOnStack {
  3266. e.c.emit(pop)
  3267. }
  3268. }