compiler_expr.go 78 KB

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