compiler_expr.go 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520
  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 (c *compiler) newCode(length, minCap int) (buf []instruction) {
  1214. if c.codeScratchpad != nil {
  1215. buf = c.codeScratchpad
  1216. c.codeScratchpad = nil
  1217. }
  1218. if cap(buf) < minCap {
  1219. buf = make([]instruction, length, minCap)
  1220. } else {
  1221. buf = buf[:length]
  1222. }
  1223. return
  1224. }
  1225. func (e *compiledFunctionLiteral) compile() (prg *Program, name unistring.String, length int, strict bool) {
  1226. e.c.assert(e.typ != funcNone, e.offset, "compiledFunctionLiteral.typ is not set")
  1227. savedPrg := e.c.p
  1228. preambleLen := 8 // enter, boxThis, loadStack(0), initThis, createArgs, set, loadCallee, init
  1229. e.c.p = &Program{
  1230. src: e.c.p.src,
  1231. code: e.c.newCode(preambleLen, 16),
  1232. }
  1233. e.c.newScope()
  1234. s := e.c.scope
  1235. s.funcType = e.typ
  1236. if e.name != nil {
  1237. name = e.name.Name
  1238. } else {
  1239. name = e.lhsName
  1240. }
  1241. if name != "" {
  1242. e.c.p.funcName = name
  1243. }
  1244. savedBlock := e.c.block
  1245. defer func() {
  1246. e.c.block = savedBlock
  1247. }()
  1248. e.c.block = &block{
  1249. typ: blockScope,
  1250. }
  1251. if !s.strict {
  1252. s.strict = e.strict != nil
  1253. }
  1254. hasPatterns := false
  1255. hasInits := false
  1256. firstDupIdx := -1
  1257. if e.parameterList.Rest != nil {
  1258. hasPatterns = true // strictly speaking not, but we need to activate all the checks
  1259. }
  1260. // First, make sure that the first bindings correspond to the formal parameters
  1261. for _, item := range e.parameterList.List {
  1262. switch tgt := item.Target.(type) {
  1263. case *ast.Identifier:
  1264. offset := int(tgt.Idx) - 1
  1265. b, unique := e.c.compileParameterBindingIdentifier(tgt.Name, offset)
  1266. if !unique {
  1267. firstDupIdx = offset
  1268. }
  1269. b.isArg = true
  1270. case ast.Pattern:
  1271. b := s.addBinding(int(item.Idx0()) - 1)
  1272. b.isArg = true
  1273. hasPatterns = true
  1274. default:
  1275. e.c.throwSyntaxError(int(item.Idx0())-1, "Unsupported BindingElement type: %T", item)
  1276. return
  1277. }
  1278. if item.Initializer != nil {
  1279. hasInits = true
  1280. }
  1281. if firstDupIdx >= 0 && (hasPatterns || hasInits || s.strict || e.typ == funcArrow || e.typ == funcMethod) {
  1282. e.c.throwSyntaxError(firstDupIdx, "Duplicate parameter name not allowed in this context")
  1283. return
  1284. }
  1285. if (hasPatterns || hasInits) && e.strict != nil {
  1286. e.c.throwSyntaxError(int(e.strict.Idx)-1, "Illegal 'use strict' directive in function with non-simple parameter list")
  1287. return
  1288. }
  1289. if !hasInits {
  1290. length++
  1291. }
  1292. }
  1293. var thisBinding *binding
  1294. if e.typ != funcArrow {
  1295. thisBinding = s.createThisBinding()
  1296. }
  1297. // create pattern bindings
  1298. if hasPatterns {
  1299. for _, item := range e.parameterList.List {
  1300. switch tgt := item.Target.(type) {
  1301. case *ast.Identifier:
  1302. // we already created those in the previous loop, skipping
  1303. default:
  1304. e.c.compileParameterPatternBinding(tgt)
  1305. }
  1306. }
  1307. if rest := e.parameterList.Rest; rest != nil {
  1308. e.c.compileParameterPatternBinding(rest)
  1309. }
  1310. }
  1311. paramsCount := len(e.parameterList.List)
  1312. s.numArgs = paramsCount
  1313. body := e.body
  1314. funcs := e.c.extractFunctions(body)
  1315. var calleeBinding *binding
  1316. emitArgsRestMark := -1
  1317. firstForwardRef := -1
  1318. enterFunc2Mark := -1
  1319. if hasPatterns || hasInits {
  1320. if e.isExpr && e.name != nil {
  1321. if b, created := s.bindNameLexical(e.name.Name, false, 0); created {
  1322. b.isConst = true
  1323. calleeBinding = b
  1324. }
  1325. }
  1326. for i, item := range e.parameterList.List {
  1327. if pattern, ok := item.Target.(ast.Pattern); ok {
  1328. i := i
  1329. e.c.compilePatternInitExpr(func() {
  1330. if firstForwardRef == -1 {
  1331. s.bindings[i].emitGet()
  1332. } else {
  1333. e.c.emit(loadStackLex(-i - 1))
  1334. }
  1335. }, item.Initializer, item.Target.Idx0()).emitGetter(true)
  1336. e.c.emitPattern(pattern, func(target, init compiledExpr) {
  1337. e.c.emitPatternLexicalAssign(target, init)
  1338. }, false)
  1339. } else if item.Initializer != nil {
  1340. markGet := len(e.c.p.code)
  1341. e.c.emit(nil)
  1342. mark := len(e.c.p.code)
  1343. e.c.emit(nil)
  1344. e.c.emitExpr(e.c.compileExpression(item.Initializer), true)
  1345. if firstForwardRef == -1 && (s.isDynamic() || s.bindings[i].useCount() > 0) {
  1346. firstForwardRef = i
  1347. }
  1348. if firstForwardRef == -1 {
  1349. s.bindings[i].emitGetAt(markGet)
  1350. } else {
  1351. e.c.p.code[markGet] = loadStackLex(-i - 1)
  1352. }
  1353. s.bindings[i].emitInitP()
  1354. e.c.p.code[mark] = jdefP(len(e.c.p.code) - mark)
  1355. } else {
  1356. if firstForwardRef == -1 && s.bindings[i].useCount() > 0 {
  1357. firstForwardRef = i
  1358. }
  1359. if firstForwardRef != -1 {
  1360. e.c.emit(loadStackLex(-i - 1))
  1361. s.bindings[i].emitInitP()
  1362. }
  1363. }
  1364. }
  1365. if rest := e.parameterList.Rest; rest != nil {
  1366. e.c.emitAssign(rest, e.c.compileEmitterExpr(
  1367. func() {
  1368. emitArgsRestMark = len(e.c.p.code)
  1369. e.c.emit(createArgsRestStack(paramsCount))
  1370. }, rest.Idx0()),
  1371. func(target, init compiledExpr) {
  1372. e.c.emitPatternLexicalAssign(target, init)
  1373. })
  1374. }
  1375. if firstForwardRef != -1 {
  1376. for _, b := range s.bindings {
  1377. b.inStash = true
  1378. }
  1379. s.argsInStash = true
  1380. s.needStash = true
  1381. }
  1382. e.c.newBlockScope()
  1383. varScope := e.c.scope
  1384. varScope.variable = true
  1385. enterFunc2Mark = len(e.c.p.code)
  1386. e.c.emit(nil)
  1387. e.c.compileDeclList(e.declarationList, false)
  1388. e.c.createFunctionBindings(funcs)
  1389. e.c.compileLexicalDeclarationsFuncBody(body, calleeBinding)
  1390. for _, b := range varScope.bindings {
  1391. if b.isVar {
  1392. if parentBinding := s.boundNames[b.name]; parentBinding != nil && parentBinding != calleeBinding {
  1393. parentBinding.emitGet()
  1394. b.emitSetP()
  1395. }
  1396. }
  1397. }
  1398. } else {
  1399. // To avoid triggering variable conflict when binding from non-strict direct eval().
  1400. // Parameters are supposed to be in a parent scope, hence no conflict.
  1401. for _, b := range s.bindings[:paramsCount] {
  1402. b.isVar = true
  1403. }
  1404. e.c.compileDeclList(e.declarationList, true)
  1405. e.c.createFunctionBindings(funcs)
  1406. e.c.compileLexicalDeclarations(body, true)
  1407. if e.isExpr && e.name != nil {
  1408. if b, created := s.bindNameLexical(e.name.Name, false, 0); created {
  1409. b.isConst = true
  1410. calleeBinding = b
  1411. }
  1412. }
  1413. if calleeBinding != nil {
  1414. e.c.emit(loadCallee)
  1415. calleeBinding.emitInitP()
  1416. }
  1417. }
  1418. e.c.compileFunctions(funcs)
  1419. e.c.compileStatements(body, false)
  1420. var last ast.Statement
  1421. if l := len(body); l > 0 {
  1422. last = body[l-1]
  1423. }
  1424. if _, ok := last.(*ast.ReturnStatement); !ok {
  1425. if e.typ == funcDerivedCtor {
  1426. e.c.emit(loadUndef)
  1427. thisBinding.markAccessPoint()
  1428. e.c.emit(ret)
  1429. } else {
  1430. e.c.emit(loadUndef, ret)
  1431. }
  1432. }
  1433. delta := 0
  1434. code := e.c.p.code
  1435. if s.isDynamic() && !s.argsInStash {
  1436. s.moveArgsToStash()
  1437. }
  1438. if s.argsNeeded || s.isDynamic() && e.typ != funcArrow && e.typ != funcClsInit {
  1439. if e.typ == funcClsInit {
  1440. e.c.throwSyntaxError(e.offset, "'arguments' is not allowed in class field initializer or static initialization block")
  1441. }
  1442. b, created := s.bindNameLexical("arguments", false, 0)
  1443. if created || b.isVar {
  1444. if !s.argsInStash {
  1445. s.moveArgsToStash()
  1446. }
  1447. if s.strict {
  1448. b.isConst = true
  1449. } else {
  1450. b.isVar = e.c.scope.isFunction()
  1451. }
  1452. pos := preambleLen - 2
  1453. delta += 2
  1454. if s.strict || hasPatterns || hasInits {
  1455. code[pos] = createArgsUnmapped(paramsCount)
  1456. } else {
  1457. code[pos] = createArgsMapped(paramsCount)
  1458. }
  1459. pos++
  1460. b.emitInitPAtScope(s, pos)
  1461. }
  1462. }
  1463. if calleeBinding != nil {
  1464. if !s.isDynamic() && calleeBinding.useCount() == 0 {
  1465. s.deleteBinding(calleeBinding)
  1466. calleeBinding = nil
  1467. } else {
  1468. delta++
  1469. calleeBinding.emitInitPAtScope(s, preambleLen-delta)
  1470. delta++
  1471. code[preambleLen-delta] = loadCallee
  1472. }
  1473. }
  1474. if thisBinding != nil {
  1475. if !s.isDynamic() && thisBinding.useCount() == 0 {
  1476. s.deleteBinding(thisBinding)
  1477. thisBinding = nil
  1478. } else {
  1479. if thisBinding.inStash || s.isDynamic() {
  1480. delta++
  1481. thisBinding.emitInitAtScope(s, preambleLen-delta)
  1482. }
  1483. }
  1484. }
  1485. stashSize, stackSize := s.finaliseVarAlloc(0)
  1486. if thisBinding != nil && thisBinding.inStash && (!s.argsInStash || stackSize > 0) {
  1487. delta++
  1488. code[preambleLen-delta] = loadStack(0)
  1489. } // otherwise, 'this' will be at stack[sp-1], no need to load
  1490. if !s.strict && thisBinding != nil {
  1491. delta++
  1492. code[preambleLen-delta] = boxThis
  1493. }
  1494. delta++
  1495. delta = preambleLen - delta
  1496. var enter instruction
  1497. if stashSize > 0 || s.argsInStash {
  1498. if firstForwardRef == -1 {
  1499. enter1 := enterFunc{
  1500. numArgs: uint32(paramsCount),
  1501. argsToStash: s.argsInStash,
  1502. stashSize: uint32(stashSize),
  1503. stackSize: uint32(stackSize),
  1504. extensible: s.dynamic,
  1505. funcType: e.typ,
  1506. }
  1507. if s.isDynamic() {
  1508. enter1.names = s.makeNamesMap()
  1509. }
  1510. enter = &enter1
  1511. if enterFunc2Mark != -1 {
  1512. ef2 := &enterFuncBody{
  1513. extensible: e.c.scope.dynamic,
  1514. funcType: e.typ,
  1515. }
  1516. e.c.updateEnterBlock(&ef2.enterBlock)
  1517. e.c.p.code[enterFunc2Mark] = ef2
  1518. }
  1519. } else {
  1520. enter1 := enterFunc1{
  1521. stashSize: uint32(stashSize),
  1522. numArgs: uint32(paramsCount),
  1523. argsToCopy: uint32(firstForwardRef),
  1524. extensible: s.dynamic,
  1525. funcType: e.typ,
  1526. }
  1527. if s.isDynamic() {
  1528. enter1.names = s.makeNamesMap()
  1529. }
  1530. enter = &enter1
  1531. if enterFunc2Mark != -1 {
  1532. ef2 := &enterFuncBody{
  1533. adjustStack: true,
  1534. extensible: e.c.scope.dynamic,
  1535. funcType: e.typ,
  1536. }
  1537. e.c.updateEnterBlock(&ef2.enterBlock)
  1538. e.c.p.code[enterFunc2Mark] = ef2
  1539. }
  1540. }
  1541. if emitArgsRestMark != -1 && s.argsInStash {
  1542. e.c.p.code[emitArgsRestMark] = createArgsRestStash
  1543. }
  1544. } else {
  1545. enter = &enterFuncStashless{
  1546. stackSize: uint32(stackSize),
  1547. args: uint32(paramsCount),
  1548. }
  1549. if enterFunc2Mark != -1 {
  1550. ef2 := &enterFuncBody{
  1551. extensible: e.c.scope.dynamic,
  1552. funcType: e.typ,
  1553. }
  1554. e.c.updateEnterBlock(&ef2.enterBlock)
  1555. e.c.p.code[enterFunc2Mark] = ef2
  1556. }
  1557. }
  1558. code[delta] = enter
  1559. s.trimCode(delta)
  1560. strict = s.strict
  1561. prg = e.c.p
  1562. // e.c.p.dumpCode()
  1563. if enterFunc2Mark != -1 {
  1564. e.c.popScope()
  1565. }
  1566. e.c.popScope()
  1567. e.c.p = savedPrg
  1568. return
  1569. }
  1570. func (e *compiledFunctionLiteral) emitGetter(putOnStack bool) {
  1571. p, name, length, strict := e.compile()
  1572. switch e.typ {
  1573. case funcArrow:
  1574. e.c.emit(&newArrowFunc{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}})
  1575. case funcMethod, funcClsInit:
  1576. e.c.emit(&newMethod{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}, homeObjOffset: e.homeObjOffset})
  1577. case funcRegular:
  1578. e.c.emit(&newFunc{prg: p, length: length, name: name, source: e.source, strict: strict})
  1579. default:
  1580. e.c.throwSyntaxError(e.offset, "Unsupported func type: %v", e.typ)
  1581. }
  1582. if !putOnStack {
  1583. e.c.emit(pop)
  1584. }
  1585. }
  1586. func (c *compiler) compileFunctionLiteral(v *ast.FunctionLiteral, isExpr bool) *compiledFunctionLiteral {
  1587. strictBody := c.isStrictStatement(v.Body)
  1588. if v.Name != nil && (c.scope.strict || strictBody != nil) {
  1589. c.checkIdentifierLName(v.Name.Name, int(v.Name.Idx)-1)
  1590. }
  1591. r := &compiledFunctionLiteral{
  1592. name: v.Name,
  1593. parameterList: v.ParameterList,
  1594. body: v.Body.List,
  1595. source: v.Source,
  1596. declarationList: v.DeclarationList,
  1597. isExpr: isExpr,
  1598. typ: funcRegular,
  1599. strict: strictBody,
  1600. }
  1601. r.init(c, v.Idx0())
  1602. return r
  1603. }
  1604. type compiledClassLiteral struct {
  1605. baseCompiledExpr
  1606. name *ast.Identifier
  1607. superClass compiledExpr
  1608. body []ast.ClassElement
  1609. lhsName unistring.String
  1610. source string
  1611. isExpr bool
  1612. }
  1613. func (c *compiler) processKey(expr ast.Expression) (val unistring.String, computed bool) {
  1614. keyExpr := c.compileExpression(expr)
  1615. if keyExpr.constant() {
  1616. v, ex := c.evalConst(keyExpr)
  1617. if ex == nil {
  1618. return v.string(), false
  1619. }
  1620. }
  1621. keyExpr.emitGetter(true)
  1622. computed = true
  1623. return
  1624. }
  1625. func (e *compiledClassLiteral) processClassKey(expr ast.Expression) (privateName *privateName, key unistring.String, computed bool) {
  1626. if p, ok := expr.(*ast.PrivateIdentifier); ok {
  1627. privateName = e.c.classScope.getDeclaredPrivateId(p.Name)
  1628. key = privateIdString(p.Name)
  1629. return
  1630. }
  1631. key, computed = e.c.processKey(expr)
  1632. return
  1633. }
  1634. type clsElement struct {
  1635. key unistring.String
  1636. privateName *privateName
  1637. initializer compiledExpr
  1638. body *compiledFunctionLiteral
  1639. computed bool
  1640. }
  1641. func (e *compiledClassLiteral) emitGetter(putOnStack bool) {
  1642. e.c.newBlockScope()
  1643. s := e.c.scope
  1644. s.strict = true
  1645. enter := &enterBlock{}
  1646. mark0 := len(e.c.p.code)
  1647. e.c.emit(enter)
  1648. e.c.block = &block{
  1649. typ: blockScope,
  1650. outer: e.c.block,
  1651. }
  1652. var clsBinding *binding
  1653. var clsName unistring.String
  1654. if name := e.name; name != nil {
  1655. clsName = name.Name
  1656. clsBinding = e.c.createLexicalIdBinding(clsName, true, int(name.Idx)-1)
  1657. } else {
  1658. clsName = e.lhsName
  1659. }
  1660. var ctorMethod *ast.MethodDefinition
  1661. ctorMethodIdx := -1
  1662. staticsCount := 0
  1663. instanceFieldsCount := 0
  1664. hasStaticPrivateMethods := false
  1665. cs := &classScope{
  1666. c: e.c,
  1667. outer: e.c.classScope,
  1668. }
  1669. for idx, elt := range e.body {
  1670. switch elt := elt.(type) {
  1671. case *ast.ClassStaticBlock:
  1672. if len(elt.Block.List) > 0 {
  1673. staticsCount++
  1674. }
  1675. case *ast.FieldDefinition:
  1676. if id, ok := elt.Key.(*ast.PrivateIdentifier); ok {
  1677. cs.declarePrivateId(id.Name, ast.PropertyKindValue, elt.Static, int(elt.Idx)-1)
  1678. }
  1679. if elt.Static {
  1680. staticsCount++
  1681. } else {
  1682. instanceFieldsCount++
  1683. }
  1684. case *ast.MethodDefinition:
  1685. if !elt.Static {
  1686. if id, ok := elt.Key.(*ast.StringLiteral); ok {
  1687. if !elt.Computed && id.Value == "constructor" {
  1688. if ctorMethod != nil {
  1689. e.c.throwSyntaxError(int(id.Idx)-1, "A class may only have one constructor")
  1690. }
  1691. ctorMethod = elt
  1692. ctorMethodIdx = idx
  1693. continue
  1694. }
  1695. }
  1696. }
  1697. if id, ok := elt.Key.(*ast.PrivateIdentifier); ok {
  1698. cs.declarePrivateId(id.Name, elt.Kind, elt.Static, int(elt.Idx)-1)
  1699. if elt.Static {
  1700. hasStaticPrivateMethods = true
  1701. }
  1702. }
  1703. default:
  1704. e.c.assert(false, int(elt.Idx0())-1, "Unsupported static element: %T", elt)
  1705. }
  1706. }
  1707. var staticInit *newStaticFieldInit
  1708. if staticsCount > 0 || hasStaticPrivateMethods {
  1709. staticInit = &newStaticFieldInit{}
  1710. e.c.emit(staticInit)
  1711. }
  1712. var derived bool
  1713. var newClassIns *newClass
  1714. if superClass := e.superClass; superClass != nil {
  1715. derived = true
  1716. superClass.emitGetter(true)
  1717. ndc := &newDerivedClass{
  1718. newClass: newClass{
  1719. name: clsName,
  1720. source: e.source,
  1721. },
  1722. }
  1723. e.addSrcMap()
  1724. e.c.emit(ndc)
  1725. newClassIns = &ndc.newClass
  1726. } else {
  1727. newClassIns = &newClass{
  1728. name: clsName,
  1729. source: e.source,
  1730. }
  1731. e.addSrcMap()
  1732. e.c.emit(newClassIns)
  1733. }
  1734. e.c.classScope = cs
  1735. if ctorMethod != nil {
  1736. newClassIns.ctor, newClassIns.length = e.c.compileCtor(ctorMethod.Body, derived)
  1737. }
  1738. curIsPrototype := false
  1739. instanceFields := make([]clsElement, 0, instanceFieldsCount)
  1740. staticElements := make([]clsElement, 0, staticsCount)
  1741. // stack at this point:
  1742. //
  1743. // staticFieldInit (if staticsCount > 0 || hasStaticPrivateMethods)
  1744. // prototype
  1745. // class function
  1746. // <- sp
  1747. for idx, elt := range e.body {
  1748. if idx == ctorMethodIdx {
  1749. continue
  1750. }
  1751. switch elt := elt.(type) {
  1752. case *ast.ClassStaticBlock:
  1753. if len(elt.Block.List) > 0 {
  1754. f := e.c.compileFunctionLiteral(&ast.FunctionLiteral{
  1755. Function: elt.Idx0(),
  1756. ParameterList: &ast.ParameterList{},
  1757. Body: elt.Block,
  1758. Source: elt.Source,
  1759. DeclarationList: elt.DeclarationList,
  1760. }, true)
  1761. f.typ = funcClsInit
  1762. //f.lhsName = "<static_initializer>"
  1763. f.homeObjOffset = 1
  1764. staticElements = append(staticElements, clsElement{
  1765. body: f,
  1766. })
  1767. }
  1768. case *ast.FieldDefinition:
  1769. privateName, key, computed := e.processClassKey(elt.Key)
  1770. var el clsElement
  1771. if elt.Initializer != nil {
  1772. el.initializer = e.c.compileExpression(elt.Initializer)
  1773. }
  1774. el.computed = computed
  1775. if computed {
  1776. if elt.Static {
  1777. if curIsPrototype {
  1778. e.c.emit(defineComputedKey(5))
  1779. } else {
  1780. e.c.emit(defineComputedKey(4))
  1781. }
  1782. } else {
  1783. if curIsPrototype {
  1784. e.c.emit(defineComputedKey(3))
  1785. } else {
  1786. e.c.emit(defineComputedKey(2))
  1787. }
  1788. }
  1789. } else {
  1790. el.privateName = privateName
  1791. el.key = key
  1792. }
  1793. if elt.Static {
  1794. staticElements = append(staticElements, el)
  1795. } else {
  1796. instanceFields = append(instanceFields, el)
  1797. }
  1798. case *ast.MethodDefinition:
  1799. if elt.Static {
  1800. if curIsPrototype {
  1801. e.c.emit(pop)
  1802. curIsPrototype = false
  1803. }
  1804. } else {
  1805. if !curIsPrototype {
  1806. e.c.emit(dupN(1))
  1807. curIsPrototype = true
  1808. }
  1809. }
  1810. privateName, key, computed := e.processClassKey(elt.Key)
  1811. lit := e.c.compileFunctionLiteral(elt.Body, true)
  1812. lit.typ = funcMethod
  1813. if computed {
  1814. e.c.emit(_toPropertyKey{})
  1815. lit.homeObjOffset = 2
  1816. } else {
  1817. lit.homeObjOffset = 1
  1818. lit.lhsName = key
  1819. }
  1820. lit.emitGetter(true)
  1821. if privateName != nil {
  1822. var offset int
  1823. if elt.Static {
  1824. if curIsPrototype {
  1825. /*
  1826. staticInit
  1827. proto
  1828. cls
  1829. proto
  1830. method
  1831. <- sp
  1832. */
  1833. offset = 5
  1834. } else {
  1835. /*
  1836. staticInit
  1837. proto
  1838. cls
  1839. method
  1840. <- sp
  1841. */
  1842. offset = 4
  1843. }
  1844. } else {
  1845. if curIsPrototype {
  1846. offset = 3
  1847. } else {
  1848. offset = 2
  1849. }
  1850. }
  1851. switch elt.Kind {
  1852. case ast.PropertyKindGet:
  1853. e.c.emit(&definePrivateGetter{
  1854. definePrivateMethod: definePrivateMethod{
  1855. idx: privateName.idx,
  1856. targetOffset: offset,
  1857. },
  1858. })
  1859. case ast.PropertyKindSet:
  1860. e.c.emit(&definePrivateSetter{
  1861. definePrivateMethod: definePrivateMethod{
  1862. idx: privateName.idx,
  1863. targetOffset: offset,
  1864. },
  1865. })
  1866. default:
  1867. e.c.emit(&definePrivateMethod{
  1868. idx: privateName.idx,
  1869. targetOffset: offset,
  1870. })
  1871. }
  1872. } else if computed {
  1873. switch elt.Kind {
  1874. case ast.PropertyKindGet:
  1875. e.c.emit(&defineGetter{})
  1876. case ast.PropertyKindSet:
  1877. e.c.emit(&defineSetter{})
  1878. default:
  1879. e.c.emit(&defineMethod{})
  1880. }
  1881. } else {
  1882. switch elt.Kind {
  1883. case ast.PropertyKindGet:
  1884. e.c.emit(&defineGetterKeyed{key: key})
  1885. case ast.PropertyKindSet:
  1886. e.c.emit(&defineSetterKeyed{key: key})
  1887. default:
  1888. e.c.emit(&defineMethodKeyed{key: key})
  1889. }
  1890. }
  1891. }
  1892. }
  1893. if curIsPrototype {
  1894. e.c.emit(pop)
  1895. }
  1896. if len(instanceFields) > 0 {
  1897. newClassIns.initFields = e.compileFieldsAndStaticBlocks(instanceFields, "<instance_members_initializer>")
  1898. }
  1899. if staticInit != nil {
  1900. if len(staticElements) > 0 {
  1901. staticInit.initFields = e.compileFieldsAndStaticBlocks(staticElements, "<static_initializer>")
  1902. }
  1903. }
  1904. env := e.c.classScope.instanceEnv
  1905. if s.dynLookup {
  1906. newClassIns.privateMethods, newClassIns.privateFields = env.methods, env.fields
  1907. }
  1908. newClassIns.numPrivateMethods = uint32(len(env.methods))
  1909. newClassIns.numPrivateFields = uint32(len(env.fields))
  1910. newClassIns.hasPrivateEnv = len(e.c.classScope.privateNames) > 0
  1911. if (clsBinding != nil && clsBinding.useCount() > 0) || s.dynLookup {
  1912. if clsBinding != nil {
  1913. // Because this block may be in the middle of an expression, it's initial stack position
  1914. // cannot be known, and therefore it may not have any stack variables.
  1915. // Note, because clsBinding would be accessed through a function, it should already be in stash,
  1916. // this is just to make sure.
  1917. clsBinding.moveToStash()
  1918. clsBinding.emitInit()
  1919. }
  1920. } else {
  1921. if clsBinding != nil {
  1922. s.deleteBinding(clsBinding)
  1923. clsBinding = nil
  1924. }
  1925. e.c.p.code[mark0] = jump(1)
  1926. }
  1927. if staticsCount > 0 || hasStaticPrivateMethods {
  1928. ise := &initStaticElements{}
  1929. e.c.emit(ise)
  1930. env := e.c.classScope.staticEnv
  1931. staticInit.numPrivateFields = uint32(len(env.fields))
  1932. staticInit.numPrivateMethods = uint32(len(env.methods))
  1933. if s.dynLookup {
  1934. // These cannot be set on staticInit, because it is executed before ClassHeritage, and therefore
  1935. // the VM's PrivateEnvironment is still not set.
  1936. ise.privateFields = env.fields
  1937. ise.privateMethods = env.methods
  1938. }
  1939. } else {
  1940. e.c.emit(endVariadic) // re-using as semantics match
  1941. }
  1942. if !putOnStack {
  1943. e.c.emit(pop)
  1944. }
  1945. if clsBinding != nil || s.dynLookup {
  1946. e.c.leaveScopeBlock(enter)
  1947. e.c.assert(enter.stackSize == 0, e.offset, "enter.StackSize != 0 in compiledClassLiteral")
  1948. } else {
  1949. e.c.block = e.c.block.outer
  1950. }
  1951. if len(e.c.classScope.privateNames) > 0 {
  1952. e.c.emit(popPrivateEnv{})
  1953. }
  1954. e.c.classScope = e.c.classScope.outer
  1955. e.c.popScope()
  1956. }
  1957. func (e *compiledClassLiteral) compileFieldsAndStaticBlocks(elements []clsElement, funcName unistring.String) *Program {
  1958. savedPrg := e.c.p
  1959. savedBlock := e.c.block
  1960. defer func() {
  1961. e.c.p = savedPrg
  1962. e.c.block = savedBlock
  1963. }()
  1964. e.c.block = &block{
  1965. typ: blockScope,
  1966. }
  1967. e.c.p = &Program{
  1968. src: savedPrg.src,
  1969. funcName: funcName,
  1970. code: e.c.newCode(2, 16),
  1971. }
  1972. e.c.newScope()
  1973. s := e.c.scope
  1974. s.funcType = funcClsInit
  1975. thisBinding := s.createThisBinding()
  1976. valIdx := 0
  1977. for _, elt := range elements {
  1978. if elt.body != nil {
  1979. e.c.emit(dup) // this
  1980. elt.body.emitGetter(true)
  1981. elt.body.addSrcMap()
  1982. e.c.emit(call(0), pop)
  1983. } else {
  1984. if elt.computed {
  1985. e.c.emit(loadComputedKey(valIdx))
  1986. valIdx++
  1987. }
  1988. if init := elt.initializer; init != nil {
  1989. if !elt.computed {
  1990. e.c.emitNamedOrConst(init, elt.key)
  1991. } else {
  1992. e.c.emitExpr(init, true)
  1993. }
  1994. } else {
  1995. e.c.emit(loadUndef)
  1996. }
  1997. if elt.privateName != nil {
  1998. e.c.emit(&definePrivateProp{
  1999. idx: elt.privateName.idx,
  2000. })
  2001. } else if elt.computed {
  2002. e.c.emit(defineProp{})
  2003. } else {
  2004. e.c.emit(definePropKeyed(elt.key))
  2005. }
  2006. }
  2007. }
  2008. e.c.emit(halt)
  2009. if s.isDynamic() || thisBinding.useCount() > 0 {
  2010. if s.isDynamic() || thisBinding.inStash {
  2011. thisBinding.emitInitAt(1)
  2012. }
  2013. } else {
  2014. s.deleteBinding(thisBinding)
  2015. }
  2016. stashSize, stackSize := s.finaliseVarAlloc(0)
  2017. e.c.assert(stackSize == 0, e.offset, "stackSize != 0 in initFields")
  2018. if stashSize > 0 {
  2019. e.c.assert(stashSize == 1, e.offset, "stashSize != 1 in initFields")
  2020. enter := &enterFunc{
  2021. stashSize: 1,
  2022. funcType: funcClsInit,
  2023. }
  2024. if s.dynLookup {
  2025. enter.names = s.makeNamesMap()
  2026. }
  2027. e.c.p.code[0] = enter
  2028. s.trimCode(0)
  2029. } else {
  2030. s.trimCode(2)
  2031. }
  2032. res := e.c.p
  2033. e.c.popScope()
  2034. return res
  2035. }
  2036. func (c *compiler) compileClassLiteral(v *ast.ClassLiteral, isExpr bool) *compiledClassLiteral {
  2037. if v.Name != nil {
  2038. c.checkIdentifierLName(v.Name.Name, int(v.Name.Idx)-1)
  2039. }
  2040. r := &compiledClassLiteral{
  2041. name: v.Name,
  2042. superClass: c.compileExpression(v.SuperClass),
  2043. body: v.Body,
  2044. source: v.Source,
  2045. isExpr: isExpr,
  2046. }
  2047. r.init(c, v.Idx0())
  2048. return r
  2049. }
  2050. func (c *compiler) compileCtor(ctor *ast.FunctionLiteral, derived bool) (p *Program, length int) {
  2051. f := c.compileFunctionLiteral(ctor, true)
  2052. if derived {
  2053. f.typ = funcDerivedCtor
  2054. } else {
  2055. f.typ = funcCtor
  2056. }
  2057. p, _, length, _ = f.compile()
  2058. return
  2059. }
  2060. func (c *compiler) compileArrowFunctionLiteral(v *ast.ArrowFunctionLiteral) *compiledFunctionLiteral {
  2061. var strictBody *ast.StringLiteral
  2062. var body []ast.Statement
  2063. switch b := v.Body.(type) {
  2064. case *ast.BlockStatement:
  2065. strictBody = c.isStrictStatement(b)
  2066. body = b.List
  2067. case *ast.ExpressionBody:
  2068. body = []ast.Statement{
  2069. &ast.ReturnStatement{
  2070. Argument: b.Expression,
  2071. },
  2072. }
  2073. default:
  2074. c.throwSyntaxError(int(b.Idx0())-1, "Unsupported ConciseBody type: %T", b)
  2075. }
  2076. r := &compiledFunctionLiteral{
  2077. parameterList: v.ParameterList,
  2078. body: body,
  2079. source: v.Source,
  2080. declarationList: v.DeclarationList,
  2081. isExpr: true,
  2082. typ: funcArrow,
  2083. strict: strictBody,
  2084. }
  2085. r.init(c, v.Idx0())
  2086. return r
  2087. }
  2088. func (c *compiler) emitLoadThis() {
  2089. b, eval := c.scope.lookupThis()
  2090. if b != nil {
  2091. b.emitGet()
  2092. } else {
  2093. if eval {
  2094. c.emit(getThisDynamic{})
  2095. } else {
  2096. c.emit(loadGlobalObject)
  2097. }
  2098. }
  2099. }
  2100. func (e *compiledThisExpr) emitGetter(putOnStack bool) {
  2101. e.addSrcMap()
  2102. e.c.emitLoadThis()
  2103. if !putOnStack {
  2104. e.c.emit(pop)
  2105. }
  2106. }
  2107. func (e *compiledSuperExpr) emitGetter(putOnStack bool) {
  2108. if putOnStack {
  2109. e.c.emit(loadSuper)
  2110. }
  2111. }
  2112. func (e *compiledNewExpr) emitGetter(putOnStack bool) {
  2113. if e.isVariadic {
  2114. e.c.emit(startVariadic)
  2115. }
  2116. e.callee.emitGetter(true)
  2117. for _, expr := range e.args {
  2118. expr.emitGetter(true)
  2119. }
  2120. e.addSrcMap()
  2121. if e.isVariadic {
  2122. e.c.emit(newVariadic, endVariadic)
  2123. } else {
  2124. e.c.emit(_new(len(e.args)))
  2125. }
  2126. if !putOnStack {
  2127. e.c.emit(pop)
  2128. }
  2129. }
  2130. func (c *compiler) compileCallArgs(list []ast.Expression) (args []compiledExpr, isVariadic bool) {
  2131. args = make([]compiledExpr, len(list))
  2132. for i, argExpr := range list {
  2133. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  2134. args[i] = c.compileSpreadCallArgument(spread)
  2135. isVariadic = true
  2136. } else {
  2137. args[i] = c.compileExpression(argExpr)
  2138. }
  2139. }
  2140. return
  2141. }
  2142. func (c *compiler) compileNewExpression(v *ast.NewExpression) compiledExpr {
  2143. args, isVariadic := c.compileCallArgs(v.ArgumentList)
  2144. r := &compiledNewExpr{
  2145. compiledCallExpr: compiledCallExpr{
  2146. callee: c.compileExpression(v.Callee),
  2147. args: args,
  2148. isVariadic: isVariadic,
  2149. },
  2150. }
  2151. r.init(c, v.Idx0())
  2152. return r
  2153. }
  2154. func (e *compiledNewTarget) emitGetter(putOnStack bool) {
  2155. if s := e.c.scope.nearestThis(); s == nil || s.funcType == funcNone {
  2156. e.c.throwSyntaxError(e.offset, "new.target expression is not allowed here")
  2157. }
  2158. if putOnStack {
  2159. e.addSrcMap()
  2160. e.c.emit(loadNewTarget)
  2161. }
  2162. }
  2163. func (c *compiler) compileMetaProperty(v *ast.MetaProperty) compiledExpr {
  2164. if v.Meta.Name == "new" || v.Property.Name != "target" {
  2165. r := &compiledNewTarget{}
  2166. r.init(c, v.Idx0())
  2167. return r
  2168. }
  2169. c.throwSyntaxError(int(v.Idx)-1, "Unsupported meta property: %s.%s", v.Meta.Name, v.Property.Name)
  2170. return nil
  2171. }
  2172. func (e *compiledSequenceExpr) emitGetter(putOnStack bool) {
  2173. if len(e.sequence) > 0 {
  2174. for i := 0; i < len(e.sequence)-1; i++ {
  2175. e.sequence[i].emitGetter(false)
  2176. }
  2177. e.sequence[len(e.sequence)-1].emitGetter(putOnStack)
  2178. }
  2179. }
  2180. func (c *compiler) compileSequenceExpression(v *ast.SequenceExpression) compiledExpr {
  2181. s := make([]compiledExpr, len(v.Sequence))
  2182. for i, expr := range v.Sequence {
  2183. s[i] = c.compileExpression(expr)
  2184. }
  2185. r := &compiledSequenceExpr{
  2186. sequence: s,
  2187. }
  2188. var idx file.Idx
  2189. if len(v.Sequence) > 0 {
  2190. idx = v.Idx0()
  2191. }
  2192. r.init(c, idx)
  2193. return r
  2194. }
  2195. func (c *compiler) emitThrow(v Value) {
  2196. if o, ok := v.(*Object); ok {
  2197. t := nilSafe(o.self.getStr("name", nil)).toString().String()
  2198. switch t {
  2199. case "TypeError":
  2200. c.emit(loadDynamic(t))
  2201. msg := o.self.getStr("message", nil)
  2202. if msg != nil {
  2203. c.emit(loadVal(c.p.defineLiteralValue(msg)))
  2204. c.emit(_new(1))
  2205. } else {
  2206. c.emit(_new(0))
  2207. }
  2208. c.emit(throw)
  2209. return
  2210. }
  2211. }
  2212. c.assert(false, 0, "unknown exception type thrown while evaluating constant expression: %s", v.String())
  2213. panic("unreachable")
  2214. }
  2215. func (c *compiler) emitConst(expr compiledExpr, putOnStack bool) {
  2216. v, ex := c.evalConst(expr)
  2217. if ex == nil {
  2218. if putOnStack {
  2219. c.emit(loadVal(c.p.defineLiteralValue(v)))
  2220. }
  2221. } else {
  2222. c.emitThrow(ex.val)
  2223. }
  2224. }
  2225. func (c *compiler) evalConst(expr compiledExpr) (Value, *Exception) {
  2226. if expr, ok := expr.(*compiledLiteral); ok {
  2227. return expr.val, nil
  2228. }
  2229. if c.evalVM == nil {
  2230. c.evalVM = New().vm
  2231. }
  2232. var savedPrg *Program
  2233. createdPrg := false
  2234. if c.evalVM.prg == nil {
  2235. c.evalVM.prg = &Program{}
  2236. savedPrg = c.p
  2237. c.p = c.evalVM.prg
  2238. createdPrg = true
  2239. }
  2240. savedPc := len(c.p.code)
  2241. expr.emitGetter(true)
  2242. c.emit(halt)
  2243. c.evalVM.pc = savedPc
  2244. ex := c.evalVM.runTry()
  2245. if createdPrg {
  2246. c.evalVM.prg = nil
  2247. c.evalVM.pc = 0
  2248. c.p = savedPrg
  2249. } else {
  2250. c.evalVM.prg.code = c.evalVM.prg.code[:savedPc]
  2251. c.p.code = c.evalVM.prg.code
  2252. }
  2253. if ex == nil {
  2254. return c.evalVM.pop(), nil
  2255. }
  2256. return nil, ex
  2257. }
  2258. func (e *compiledUnaryExpr) constant() bool {
  2259. return e.operand.constant()
  2260. }
  2261. func (e *compiledUnaryExpr) emitGetter(putOnStack bool) {
  2262. var prepare, body func()
  2263. toNumber := func() {
  2264. e.addSrcMap()
  2265. e.c.emit(toNumber)
  2266. }
  2267. switch e.operator {
  2268. case token.NOT:
  2269. e.operand.emitGetter(true)
  2270. e.c.emit(not)
  2271. goto end
  2272. case token.BITWISE_NOT:
  2273. e.operand.emitGetter(true)
  2274. e.c.emit(bnot)
  2275. goto end
  2276. case token.TYPEOF:
  2277. if o, ok := e.operand.(compiledExprOrRef); ok {
  2278. o.emitGetterOrRef()
  2279. } else {
  2280. e.operand.emitGetter(true)
  2281. }
  2282. e.c.emit(typeof)
  2283. goto end
  2284. case token.DELETE:
  2285. e.operand.deleteExpr().emitGetter(putOnStack)
  2286. return
  2287. case token.MINUS:
  2288. e.c.emitExpr(e.operand, true)
  2289. e.c.emit(neg)
  2290. goto end
  2291. case token.PLUS:
  2292. e.c.emitExpr(e.operand, true)
  2293. e.c.emit(plus)
  2294. goto end
  2295. case token.INCREMENT:
  2296. prepare = toNumber
  2297. body = func() {
  2298. e.c.emit(inc)
  2299. }
  2300. case token.DECREMENT:
  2301. prepare = toNumber
  2302. body = func() {
  2303. e.c.emit(dec)
  2304. }
  2305. case token.VOID:
  2306. e.c.emitExpr(e.operand, false)
  2307. if putOnStack {
  2308. e.c.emit(loadUndef)
  2309. }
  2310. return
  2311. default:
  2312. e.c.assert(false, e.offset, "Unknown unary operator: %s", e.operator.String())
  2313. panic("unreachable")
  2314. }
  2315. e.operand.emitUnary(prepare, body, e.postfix, putOnStack)
  2316. return
  2317. end:
  2318. if !putOnStack {
  2319. e.c.emit(pop)
  2320. }
  2321. }
  2322. func (c *compiler) compileUnaryExpression(v *ast.UnaryExpression) compiledExpr {
  2323. r := &compiledUnaryExpr{
  2324. operand: c.compileExpression(v.Operand),
  2325. operator: v.Operator,
  2326. postfix: v.Postfix,
  2327. }
  2328. r.init(c, v.Idx0())
  2329. return r
  2330. }
  2331. func (e *compiledConditionalExpr) emitGetter(putOnStack bool) {
  2332. e.test.emitGetter(true)
  2333. j := len(e.c.p.code)
  2334. e.c.emit(nil)
  2335. e.consequent.emitGetter(putOnStack)
  2336. j1 := len(e.c.p.code)
  2337. e.c.emit(nil)
  2338. e.c.p.code[j] = jne(len(e.c.p.code) - j)
  2339. e.alternate.emitGetter(putOnStack)
  2340. e.c.p.code[j1] = jump(len(e.c.p.code) - j1)
  2341. }
  2342. func (c *compiler) compileConditionalExpression(v *ast.ConditionalExpression) compiledExpr {
  2343. r := &compiledConditionalExpr{
  2344. test: c.compileExpression(v.Test),
  2345. consequent: c.compileExpression(v.Consequent),
  2346. alternate: c.compileExpression(v.Alternate),
  2347. }
  2348. r.init(c, v.Idx0())
  2349. return r
  2350. }
  2351. func (e *compiledLogicalOr) constant() bool {
  2352. if e.left.constant() {
  2353. if v, ex := e.c.evalConst(e.left); ex == nil {
  2354. if v.ToBoolean() {
  2355. return true
  2356. }
  2357. return e.right.constant()
  2358. } else {
  2359. return true
  2360. }
  2361. }
  2362. return false
  2363. }
  2364. func (e *compiledLogicalOr) emitGetter(putOnStack bool) {
  2365. if e.left.constant() {
  2366. if v, ex := e.c.evalConst(e.left); ex == nil {
  2367. if !v.ToBoolean() {
  2368. e.c.emitExpr(e.right, putOnStack)
  2369. } else {
  2370. if putOnStack {
  2371. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  2372. }
  2373. }
  2374. } else {
  2375. e.c.emitThrow(ex.val)
  2376. }
  2377. return
  2378. }
  2379. e.c.emitExpr(e.left, true)
  2380. j := len(e.c.p.code)
  2381. e.addSrcMap()
  2382. e.c.emit(nil)
  2383. e.c.emitExpr(e.right, true)
  2384. e.c.p.code[j] = jeq1(len(e.c.p.code) - j)
  2385. if !putOnStack {
  2386. e.c.emit(pop)
  2387. }
  2388. }
  2389. func (e *compiledCoalesce) constant() bool {
  2390. if e.left.constant() {
  2391. if v, ex := e.c.evalConst(e.left); ex == nil {
  2392. if v != _null && v != _undefined {
  2393. return true
  2394. }
  2395. return e.right.constant()
  2396. } else {
  2397. return true
  2398. }
  2399. }
  2400. return false
  2401. }
  2402. func (e *compiledCoalesce) emitGetter(putOnStack bool) {
  2403. if e.left.constant() {
  2404. if v, ex := e.c.evalConst(e.left); ex == nil {
  2405. if v == _undefined || v == _null {
  2406. e.c.emitExpr(e.right, putOnStack)
  2407. } else {
  2408. if putOnStack {
  2409. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  2410. }
  2411. }
  2412. } else {
  2413. e.c.emitThrow(ex.val)
  2414. }
  2415. return
  2416. }
  2417. e.c.emitExpr(e.left, true)
  2418. j := len(e.c.p.code)
  2419. e.addSrcMap()
  2420. e.c.emit(nil)
  2421. e.c.emitExpr(e.right, true)
  2422. e.c.p.code[j] = jcoalesc(len(e.c.p.code) - j)
  2423. if !putOnStack {
  2424. e.c.emit(pop)
  2425. }
  2426. }
  2427. func (e *compiledLogicalAnd) constant() bool {
  2428. if e.left.constant() {
  2429. if v, ex := e.c.evalConst(e.left); ex == nil {
  2430. if !v.ToBoolean() {
  2431. return true
  2432. } else {
  2433. return e.right.constant()
  2434. }
  2435. } else {
  2436. return true
  2437. }
  2438. }
  2439. return false
  2440. }
  2441. func (e *compiledLogicalAnd) emitGetter(putOnStack bool) {
  2442. var j int
  2443. if e.left.constant() {
  2444. if v, ex := e.c.evalConst(e.left); ex == nil {
  2445. if !v.ToBoolean() {
  2446. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  2447. } else {
  2448. e.c.emitExpr(e.right, putOnStack)
  2449. }
  2450. } else {
  2451. e.c.emitThrow(ex.val)
  2452. }
  2453. return
  2454. }
  2455. e.left.emitGetter(true)
  2456. j = len(e.c.p.code)
  2457. e.addSrcMap()
  2458. e.c.emit(nil)
  2459. e.c.emitExpr(e.right, true)
  2460. e.c.p.code[j] = jneq1(len(e.c.p.code) - j)
  2461. if !putOnStack {
  2462. e.c.emit(pop)
  2463. }
  2464. }
  2465. func (e *compiledBinaryExpr) constant() bool {
  2466. return e.left.constant() && e.right.constant()
  2467. }
  2468. func (e *compiledBinaryExpr) emitGetter(putOnStack bool) {
  2469. e.c.emitExpr(e.left, true)
  2470. e.c.emitExpr(e.right, true)
  2471. e.addSrcMap()
  2472. switch e.operator {
  2473. case token.LESS:
  2474. e.c.emit(op_lt)
  2475. case token.GREATER:
  2476. e.c.emit(op_gt)
  2477. case token.LESS_OR_EQUAL:
  2478. e.c.emit(op_lte)
  2479. case token.GREATER_OR_EQUAL:
  2480. e.c.emit(op_gte)
  2481. case token.EQUAL:
  2482. e.c.emit(op_eq)
  2483. case token.NOT_EQUAL:
  2484. e.c.emit(op_neq)
  2485. case token.STRICT_EQUAL:
  2486. e.c.emit(op_strict_eq)
  2487. case token.STRICT_NOT_EQUAL:
  2488. e.c.emit(op_strict_neq)
  2489. case token.PLUS:
  2490. e.c.emit(add)
  2491. case token.MINUS:
  2492. e.c.emit(sub)
  2493. case token.MULTIPLY:
  2494. e.c.emit(mul)
  2495. case token.EXPONENT:
  2496. e.c.emit(exp)
  2497. case token.SLASH:
  2498. e.c.emit(div)
  2499. case token.REMAINDER:
  2500. e.c.emit(mod)
  2501. case token.AND:
  2502. e.c.emit(and)
  2503. case token.OR:
  2504. e.c.emit(or)
  2505. case token.EXCLUSIVE_OR:
  2506. e.c.emit(xor)
  2507. case token.INSTANCEOF:
  2508. e.c.emit(op_instanceof)
  2509. case token.IN:
  2510. e.c.emit(op_in)
  2511. case token.SHIFT_LEFT:
  2512. e.c.emit(sal)
  2513. case token.SHIFT_RIGHT:
  2514. e.c.emit(sar)
  2515. case token.UNSIGNED_SHIFT_RIGHT:
  2516. e.c.emit(shr)
  2517. default:
  2518. e.c.assert(false, e.offset, "Unknown operator: %s", e.operator.String())
  2519. panic("unreachable")
  2520. }
  2521. if !putOnStack {
  2522. e.c.emit(pop)
  2523. }
  2524. }
  2525. func (c *compiler) compileBinaryExpression(v *ast.BinaryExpression) compiledExpr {
  2526. switch v.Operator {
  2527. case token.LOGICAL_OR:
  2528. return c.compileLogicalOr(v.Left, v.Right, v.Idx0())
  2529. case token.COALESCE:
  2530. return c.compileCoalesce(v.Left, v.Right, v.Idx0())
  2531. case token.LOGICAL_AND:
  2532. return c.compileLogicalAnd(v.Left, v.Right, v.Idx0())
  2533. }
  2534. if id, ok := v.Left.(*ast.PrivateIdentifier); ok {
  2535. return c.compilePrivateIn(id, v.Right, id.Idx)
  2536. }
  2537. r := &compiledBinaryExpr{
  2538. left: c.compileExpression(v.Left),
  2539. right: c.compileExpression(v.Right),
  2540. operator: v.Operator,
  2541. }
  2542. r.init(c, v.Idx0())
  2543. return r
  2544. }
  2545. type compiledPrivateIn struct {
  2546. baseCompiledExpr
  2547. id unistring.String
  2548. right compiledExpr
  2549. }
  2550. func (e *compiledPrivateIn) emitGetter(putOnStack bool) {
  2551. e.right.emitGetter(true)
  2552. rn, id := e.c.resolvePrivateName(e.id, e.offset)
  2553. if rn != nil {
  2554. e.c.emit((*privateInRes)(rn))
  2555. } else {
  2556. e.c.emit((*privateInId)(id))
  2557. }
  2558. if !putOnStack {
  2559. e.c.emit(pop)
  2560. }
  2561. }
  2562. func (c *compiler) compilePrivateIn(id *ast.PrivateIdentifier, right ast.Expression, idx file.Idx) compiledExpr {
  2563. r := &compiledPrivateIn{
  2564. id: id.Name,
  2565. right: c.compileExpression(right),
  2566. }
  2567. r.init(c, idx)
  2568. return r
  2569. }
  2570. func (c *compiler) compileLogicalOr(left, right ast.Expression, idx file.Idx) compiledExpr {
  2571. r := &compiledLogicalOr{
  2572. left: c.compileExpression(left),
  2573. right: c.compileExpression(right),
  2574. }
  2575. r.init(c, idx)
  2576. return r
  2577. }
  2578. func (c *compiler) compileCoalesce(left, right ast.Expression, idx file.Idx) compiledExpr {
  2579. r := &compiledCoalesce{
  2580. left: c.compileExpression(left),
  2581. right: c.compileExpression(right),
  2582. }
  2583. r.init(c, idx)
  2584. return r
  2585. }
  2586. func (c *compiler) compileLogicalAnd(left, right ast.Expression, idx file.Idx) compiledExpr {
  2587. r := &compiledLogicalAnd{
  2588. left: c.compileExpression(left),
  2589. right: c.compileExpression(right),
  2590. }
  2591. r.init(c, idx)
  2592. return r
  2593. }
  2594. func (e *compiledObjectLiteral) emitGetter(putOnStack bool) {
  2595. e.addSrcMap()
  2596. e.c.emit(newObject)
  2597. hasProto := false
  2598. for _, prop := range e.expr.Value {
  2599. switch prop := prop.(type) {
  2600. case *ast.PropertyKeyed:
  2601. key, computed := e.c.processKey(prop.Key)
  2602. valueExpr := e.c.compileExpression(prop.Value)
  2603. var ne namedEmitter
  2604. if fn, ok := valueExpr.(*compiledFunctionLiteral); ok {
  2605. if fn.name == nil {
  2606. ne = fn
  2607. }
  2608. switch prop.Kind {
  2609. case ast.PropertyKindMethod, ast.PropertyKindGet, ast.PropertyKindSet:
  2610. fn.typ = funcMethod
  2611. if computed {
  2612. fn.homeObjOffset = 2
  2613. } else {
  2614. fn.homeObjOffset = 1
  2615. }
  2616. }
  2617. } else if v, ok := valueExpr.(namedEmitter); ok {
  2618. ne = v
  2619. }
  2620. if computed {
  2621. e.c.emit(_toPropertyKey{})
  2622. e.c.emitExpr(valueExpr, true)
  2623. switch prop.Kind {
  2624. case ast.PropertyKindValue:
  2625. if ne != nil {
  2626. e.c.emit(setElem1Named)
  2627. } else {
  2628. e.c.emit(setElem1)
  2629. }
  2630. case ast.PropertyKindMethod:
  2631. e.c.emit(&defineMethod{enumerable: true})
  2632. case ast.PropertyKindGet:
  2633. e.c.emit(&defineGetter{enumerable: true})
  2634. case ast.PropertyKindSet:
  2635. e.c.emit(&defineSetter{enumerable: true})
  2636. default:
  2637. e.c.assert(false, e.offset, "unknown property kind: %s", prop.Kind)
  2638. panic("unreachable")
  2639. }
  2640. } else {
  2641. isProto := key == __proto__ && !prop.Computed
  2642. if isProto {
  2643. if hasProto {
  2644. e.c.throwSyntaxError(int(prop.Idx0())-1, "Duplicate __proto__ fields are not allowed in object literals")
  2645. } else {
  2646. hasProto = true
  2647. }
  2648. }
  2649. if ne != nil && !isProto {
  2650. ne.emitNamed(key)
  2651. } else {
  2652. e.c.emitExpr(valueExpr, true)
  2653. }
  2654. switch prop.Kind {
  2655. case ast.PropertyKindValue:
  2656. if isProto {
  2657. e.c.emit(setProto)
  2658. } else {
  2659. e.c.emit(putProp(key))
  2660. }
  2661. case ast.PropertyKindMethod:
  2662. e.c.emit(&defineMethodKeyed{key: key, enumerable: true})
  2663. case ast.PropertyKindGet:
  2664. e.c.emit(&defineGetterKeyed{key: key, enumerable: true})
  2665. case ast.PropertyKindSet:
  2666. e.c.emit(&defineSetterKeyed{key: key, enumerable: true})
  2667. default:
  2668. e.c.assert(false, e.offset, "unknown property kind: %s", prop.Kind)
  2669. panic("unreachable")
  2670. }
  2671. }
  2672. case *ast.PropertyShort:
  2673. key := prop.Name.Name
  2674. if prop.Initializer != nil {
  2675. e.c.throwSyntaxError(int(prop.Initializer.Idx0())-1, "Invalid shorthand property initializer")
  2676. }
  2677. if e.c.scope.strict && key == "let" {
  2678. e.c.throwSyntaxError(e.offset, "'let' cannot be used as a shorthand property in strict mode")
  2679. }
  2680. e.c.compileIdentifierExpression(&prop.Name).emitGetter(true)
  2681. e.c.emit(putProp(key))
  2682. case *ast.SpreadElement:
  2683. e.c.compileExpression(prop.Expression).emitGetter(true)
  2684. e.c.emit(copySpread)
  2685. default:
  2686. e.c.assert(false, e.offset, "unknown Property type: %T", prop)
  2687. panic("unreachable")
  2688. }
  2689. }
  2690. if !putOnStack {
  2691. e.c.emit(pop)
  2692. }
  2693. }
  2694. func (c *compiler) compileObjectLiteral(v *ast.ObjectLiteral) compiledExpr {
  2695. r := &compiledObjectLiteral{
  2696. expr: v,
  2697. }
  2698. r.init(c, v.Idx0())
  2699. return r
  2700. }
  2701. func (e *compiledArrayLiteral) emitGetter(putOnStack bool) {
  2702. e.addSrcMap()
  2703. hasSpread := false
  2704. mark := len(e.c.p.code)
  2705. e.c.emit(nil)
  2706. for _, v := range e.expr.Value {
  2707. if spread, ok := v.(*ast.SpreadElement); ok {
  2708. hasSpread = true
  2709. e.c.compileExpression(spread.Expression).emitGetter(true)
  2710. e.c.emit(pushArraySpread)
  2711. } else {
  2712. if v != nil {
  2713. e.c.emitExpr(e.c.compileExpression(v), true)
  2714. } else {
  2715. e.c.emit(loadNil)
  2716. }
  2717. e.c.emit(pushArrayItem)
  2718. }
  2719. }
  2720. var objCount uint32
  2721. if !hasSpread {
  2722. objCount = uint32(len(e.expr.Value))
  2723. }
  2724. e.c.p.code[mark] = newArray(objCount)
  2725. if !putOnStack {
  2726. e.c.emit(pop)
  2727. }
  2728. }
  2729. func (c *compiler) compileArrayLiteral(v *ast.ArrayLiteral) compiledExpr {
  2730. r := &compiledArrayLiteral{
  2731. expr: v,
  2732. }
  2733. r.init(c, v.Idx0())
  2734. return r
  2735. }
  2736. func (e *compiledRegexpLiteral) emitGetter(putOnStack bool) {
  2737. if putOnStack {
  2738. pattern, err := compileRegexp(e.expr.Pattern, e.expr.Flags)
  2739. if err != nil {
  2740. e.c.throwSyntaxError(e.offset, err.Error())
  2741. }
  2742. e.c.emit(&newRegexp{pattern: pattern, src: newStringValue(e.expr.Pattern)})
  2743. }
  2744. }
  2745. func (c *compiler) compileRegexpLiteral(v *ast.RegExpLiteral) compiledExpr {
  2746. r := &compiledRegexpLiteral{
  2747. expr: v,
  2748. }
  2749. r.init(c, v.Idx0())
  2750. return r
  2751. }
  2752. func (c *compiler) emitCallee(callee compiledExpr) (calleeName unistring.String) {
  2753. switch callee := callee.(type) {
  2754. case *compiledDotExpr:
  2755. callee.left.emitGetter(true)
  2756. c.emit(getPropCallee(callee.name))
  2757. case *compiledPrivateDotExpr:
  2758. callee.left.emitGetter(true)
  2759. rn, id := c.resolvePrivateName(callee.name, callee.offset)
  2760. if rn != nil {
  2761. c.emit((*getPrivatePropResCallee)(rn))
  2762. } else {
  2763. c.emit((*getPrivatePropIdCallee)(id))
  2764. }
  2765. case *compiledSuperDotExpr:
  2766. c.emitLoadThis()
  2767. c.emit(loadSuper)
  2768. c.emit(getPropRecvCallee(callee.name))
  2769. case *compiledBracketExpr:
  2770. callee.left.emitGetter(true)
  2771. callee.member.emitGetter(true)
  2772. c.emit(getElemCallee)
  2773. case *compiledSuperBracketExpr:
  2774. c.emitLoadThis()
  2775. c.emit(loadSuper)
  2776. callee.member.emitGetter(true)
  2777. c.emit(getElemRecvCallee)
  2778. case *compiledIdentifierExpr:
  2779. calleeName = callee.name
  2780. callee.emitGetterAndCallee()
  2781. case *compiledOptionalChain:
  2782. c.startOptChain()
  2783. c.emitCallee(callee.expr)
  2784. c.endOptChain()
  2785. case *compiledOptional:
  2786. c.emitCallee(callee.expr)
  2787. c.block.conts = append(c.block.conts, len(c.p.code))
  2788. c.emit(nil)
  2789. case *compiledSuperExpr:
  2790. // no-op
  2791. default:
  2792. c.emit(loadUndef)
  2793. callee.emitGetter(true)
  2794. }
  2795. return
  2796. }
  2797. func (e *compiledCallExpr) emitGetter(putOnStack bool) {
  2798. if e.isVariadic {
  2799. e.c.emit(startVariadic)
  2800. }
  2801. calleeName := e.c.emitCallee(e.callee)
  2802. for _, expr := range e.args {
  2803. expr.emitGetter(true)
  2804. }
  2805. e.addSrcMap()
  2806. if _, ok := e.callee.(*compiledSuperExpr); ok {
  2807. b, eval := e.c.scope.lookupThis()
  2808. e.c.assert(eval || b != nil, e.offset, "super call, but no 'this' binding")
  2809. if eval {
  2810. e.c.emit(resolveThisDynamic{})
  2811. } else {
  2812. b.markAccessPoint()
  2813. e.c.emit(resolveThisStack{})
  2814. }
  2815. if e.isVariadic {
  2816. e.c.emit(superCallVariadic)
  2817. } else {
  2818. e.c.emit(superCall(len(e.args)))
  2819. }
  2820. } else if calleeName == "eval" {
  2821. foundVar := false
  2822. for sc := e.c.scope; sc != nil; sc = sc.outer {
  2823. if !foundVar && (sc.variable || sc.isFunction()) {
  2824. foundVar = true
  2825. if !sc.strict {
  2826. sc.dynamic = true
  2827. }
  2828. }
  2829. sc.dynLookup = true
  2830. }
  2831. if e.c.scope.strict {
  2832. if e.isVariadic {
  2833. e.c.emit(callEvalVariadicStrict)
  2834. } else {
  2835. e.c.emit(callEvalStrict(len(e.args)))
  2836. }
  2837. } else {
  2838. if e.isVariadic {
  2839. e.c.emit(callEvalVariadic)
  2840. } else {
  2841. e.c.emit(callEval(len(e.args)))
  2842. }
  2843. }
  2844. } else {
  2845. if e.isVariadic {
  2846. e.c.emit(callVariadic)
  2847. } else {
  2848. e.c.emit(call(len(e.args)))
  2849. }
  2850. }
  2851. if e.isVariadic {
  2852. e.c.emit(endVariadic)
  2853. }
  2854. if !putOnStack {
  2855. e.c.emit(pop)
  2856. }
  2857. }
  2858. func (e *compiledCallExpr) deleteExpr() compiledExpr {
  2859. r := &defaultDeleteExpr{
  2860. expr: e,
  2861. }
  2862. r.init(e.c, file.Idx(e.offset+1))
  2863. return r
  2864. }
  2865. func (c *compiler) compileSpreadCallArgument(spread *ast.SpreadElement) compiledExpr {
  2866. r := &compiledSpreadCallArgument{
  2867. expr: c.compileExpression(spread.Expression),
  2868. }
  2869. r.init(c, spread.Idx0())
  2870. return r
  2871. }
  2872. func (c *compiler) compileCallee(v ast.Expression) compiledExpr {
  2873. if sup, ok := v.(*ast.SuperExpression); ok {
  2874. if s := c.scope.nearestThis(); s != nil && s.funcType == funcDerivedCtor {
  2875. e := &compiledSuperExpr{}
  2876. e.init(c, sup.Idx)
  2877. return e
  2878. }
  2879. c.throwSyntaxError(int(v.Idx0())-1, "'super' keyword unexpected here")
  2880. panic("unreachable")
  2881. }
  2882. return c.compileExpression(v)
  2883. }
  2884. func (c *compiler) compileCallExpression(v *ast.CallExpression) compiledExpr {
  2885. args := make([]compiledExpr, len(v.ArgumentList))
  2886. isVariadic := false
  2887. for i, argExpr := range v.ArgumentList {
  2888. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  2889. args[i] = c.compileSpreadCallArgument(spread)
  2890. isVariadic = true
  2891. } else {
  2892. args[i] = c.compileExpression(argExpr)
  2893. }
  2894. }
  2895. r := &compiledCallExpr{
  2896. args: args,
  2897. callee: c.compileCallee(v.Callee),
  2898. isVariadic: isVariadic,
  2899. }
  2900. r.init(c, v.LeftParenthesis)
  2901. return r
  2902. }
  2903. func (c *compiler) compileIdentifierExpression(v *ast.Identifier) compiledExpr {
  2904. if c.scope.strict {
  2905. c.checkIdentifierName(v.Name, int(v.Idx)-1)
  2906. }
  2907. r := &compiledIdentifierExpr{
  2908. name: v.Name,
  2909. }
  2910. r.offset = int(v.Idx) - 1
  2911. r.init(c, v.Idx0())
  2912. return r
  2913. }
  2914. func (c *compiler) compileNumberLiteral(v *ast.NumberLiteral) compiledExpr {
  2915. if c.scope.strict && len(v.Literal) > 1 && v.Literal[0] == '0' && v.Literal[1] <= '7' && v.Literal[1] >= '0' {
  2916. c.throwSyntaxError(int(v.Idx)-1, "Octal literals are not allowed in strict mode")
  2917. panic("Unreachable")
  2918. }
  2919. var val Value
  2920. switch num := v.Value.(type) {
  2921. case int64:
  2922. val = intToValue(num)
  2923. case float64:
  2924. val = floatToValue(num)
  2925. default:
  2926. c.assert(false, int(v.Idx)-1, "Unsupported number literal type: %T", v.Value)
  2927. panic("unreachable")
  2928. }
  2929. r := &compiledLiteral{
  2930. val: val,
  2931. }
  2932. r.init(c, v.Idx0())
  2933. return r
  2934. }
  2935. func (c *compiler) compileStringLiteral(v *ast.StringLiteral) compiledExpr {
  2936. r := &compiledLiteral{
  2937. val: stringValueFromRaw(v.Value),
  2938. }
  2939. r.init(c, v.Idx0())
  2940. return r
  2941. }
  2942. func (c *compiler) compileTemplateLiteral(v *ast.TemplateLiteral) compiledExpr {
  2943. r := &compiledTemplateLiteral{}
  2944. if v.Tag != nil {
  2945. r.tag = c.compileExpression(v.Tag)
  2946. }
  2947. ce := make([]compiledExpr, len(v.Expressions))
  2948. for i, expr := range v.Expressions {
  2949. ce[i] = c.compileExpression(expr)
  2950. }
  2951. r.expressions = ce
  2952. r.elements = v.Elements
  2953. r.init(c, v.Idx0())
  2954. return r
  2955. }
  2956. func (c *compiler) compileBooleanLiteral(v *ast.BooleanLiteral) compiledExpr {
  2957. var val Value
  2958. if v.Value {
  2959. val = valueTrue
  2960. } else {
  2961. val = valueFalse
  2962. }
  2963. r := &compiledLiteral{
  2964. val: val,
  2965. }
  2966. r.init(c, v.Idx0())
  2967. return r
  2968. }
  2969. func (c *compiler) compileAssignExpression(v *ast.AssignExpression) compiledExpr {
  2970. // log.Printf("compileAssignExpression(): %+v", v)
  2971. r := &compiledAssignExpr{
  2972. left: c.compileExpression(v.Left),
  2973. right: c.compileExpression(v.Right),
  2974. operator: v.Operator,
  2975. }
  2976. r.init(c, v.Idx0())
  2977. return r
  2978. }
  2979. func (e *compiledEnumGetExpr) emitGetter(putOnStack bool) {
  2980. e.c.emit(enumGet)
  2981. if !putOnStack {
  2982. e.c.emit(pop)
  2983. }
  2984. }
  2985. func (c *compiler) compileObjectAssignmentPattern(v *ast.ObjectPattern) compiledExpr {
  2986. r := &compiledObjectAssignmentPattern{
  2987. expr: v,
  2988. }
  2989. r.init(c, v.Idx0())
  2990. return r
  2991. }
  2992. func (e *compiledObjectAssignmentPattern) emitGetter(putOnStack bool) {
  2993. if putOnStack {
  2994. e.c.emit(loadUndef)
  2995. }
  2996. }
  2997. func (c *compiler) compileArrayAssignmentPattern(v *ast.ArrayPattern) compiledExpr {
  2998. r := &compiledArrayAssignmentPattern{
  2999. expr: v,
  3000. }
  3001. r.init(c, v.Idx0())
  3002. return r
  3003. }
  3004. func (e *compiledArrayAssignmentPattern) emitGetter(putOnStack bool) {
  3005. if putOnStack {
  3006. e.c.emit(loadUndef)
  3007. }
  3008. }
  3009. func (c *compiler) emitExpr(expr compiledExpr, putOnStack bool) {
  3010. if expr.constant() {
  3011. c.emitConst(expr, putOnStack)
  3012. } else {
  3013. expr.emitGetter(putOnStack)
  3014. }
  3015. }
  3016. type namedEmitter interface {
  3017. emitNamed(name unistring.String)
  3018. }
  3019. func (c *compiler) emitNamed(expr compiledExpr, name unistring.String) {
  3020. if en, ok := expr.(namedEmitter); ok {
  3021. en.emitNamed(name)
  3022. } else {
  3023. expr.emitGetter(true)
  3024. }
  3025. }
  3026. func (c *compiler) emitNamedOrConst(expr compiledExpr, name unistring.String) {
  3027. if expr.constant() {
  3028. c.emitConst(expr, true)
  3029. } else {
  3030. c.emitNamed(expr, name)
  3031. }
  3032. }
  3033. func (e *compiledFunctionLiteral) emitNamed(name unistring.String) {
  3034. e.lhsName = name
  3035. e.emitGetter(true)
  3036. }
  3037. func (e *compiledClassLiteral) emitNamed(name unistring.String) {
  3038. e.lhsName = name
  3039. e.emitGetter(true)
  3040. }
  3041. func (c *compiler) emitPattern(pattern ast.Pattern, emitter func(target, init compiledExpr), putOnStack bool) {
  3042. switch pattern := pattern.(type) {
  3043. case *ast.ObjectPattern:
  3044. c.emitObjectPattern(pattern, emitter, putOnStack)
  3045. case *ast.ArrayPattern:
  3046. c.emitArrayPattern(pattern, emitter, putOnStack)
  3047. default:
  3048. c.assert(false, int(pattern.Idx0())-1, "unsupported Pattern: %T", pattern)
  3049. panic("unreachable")
  3050. }
  3051. }
  3052. func (c *compiler) emitAssign(target ast.Expression, init compiledExpr, emitAssignSimple func(target, init compiledExpr)) {
  3053. pattern, isPattern := target.(ast.Pattern)
  3054. if isPattern {
  3055. init.emitGetter(true)
  3056. c.emitPattern(pattern, emitAssignSimple, false)
  3057. } else {
  3058. emitAssignSimple(c.compileExpression(target), init)
  3059. }
  3060. }
  3061. func (c *compiler) emitObjectPattern(pattern *ast.ObjectPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  3062. if pattern.Rest != nil {
  3063. c.emit(createDestructSrc)
  3064. } else {
  3065. c.emit(checkObjectCoercible)
  3066. }
  3067. for _, prop := range pattern.Properties {
  3068. switch prop := prop.(type) {
  3069. case *ast.PropertyShort:
  3070. c.emit(dup)
  3071. emitAssign(c.compileIdentifierExpression(&prop.Name), c.compilePatternInitExpr(func() {
  3072. c.emit(getProp(prop.Name.Name))
  3073. }, prop.Initializer, prop.Idx0()))
  3074. case *ast.PropertyKeyed:
  3075. c.emit(dup)
  3076. c.compileExpression(prop.Key).emitGetter(true)
  3077. c.emit(_toPropertyKey{})
  3078. var target ast.Expression
  3079. var initializer ast.Expression
  3080. if e, ok := prop.Value.(*ast.AssignExpression); ok {
  3081. target = e.Left
  3082. initializer = e.Right
  3083. } else {
  3084. target = prop.Value
  3085. }
  3086. c.emitAssign(target, c.compilePatternInitExpr(func() {
  3087. c.emit(getKey)
  3088. }, initializer, prop.Idx0()), emitAssign)
  3089. default:
  3090. c.throwSyntaxError(int(prop.Idx0()-1), "Unsupported AssignmentProperty type: %T", prop)
  3091. }
  3092. }
  3093. if pattern.Rest != nil {
  3094. emitAssign(c.compileExpression(pattern.Rest), c.compileEmitterExpr(func() {
  3095. c.emit(copyRest)
  3096. }, pattern.Rest.Idx0()))
  3097. c.emit(pop)
  3098. }
  3099. if !putOnStack {
  3100. c.emit(pop)
  3101. }
  3102. }
  3103. func (c *compiler) emitArrayPattern(pattern *ast.ArrayPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  3104. c.emit(iterate)
  3105. for _, elt := range pattern.Elements {
  3106. switch elt := elt.(type) {
  3107. case nil:
  3108. c.emit(iterGetNextOrUndef{}, pop)
  3109. case *ast.AssignExpression:
  3110. c.emitAssign(elt.Left, c.compilePatternInitExpr(func() {
  3111. c.emit(iterGetNextOrUndef{})
  3112. }, elt.Right, elt.Idx0()), emitAssign)
  3113. default:
  3114. c.emitAssign(elt, c.compileEmitterExpr(func() {
  3115. c.emit(iterGetNextOrUndef{})
  3116. }, elt.Idx0()), emitAssign)
  3117. }
  3118. }
  3119. if pattern.Rest != nil {
  3120. c.emitAssign(pattern.Rest, c.compileEmitterExpr(func() {
  3121. c.emit(newArrayFromIter)
  3122. }, pattern.Rest.Idx0()), emitAssign)
  3123. } else {
  3124. c.emit(enumPopClose)
  3125. }
  3126. if !putOnStack {
  3127. c.emit(pop)
  3128. }
  3129. }
  3130. func (e *compiledObjectAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  3131. valueExpr.emitGetter(true)
  3132. e.c.emitObjectPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  3133. }
  3134. func (e *compiledArrayAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  3135. valueExpr.emitGetter(true)
  3136. e.c.emitArrayPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  3137. }
  3138. type compiledPatternInitExpr struct {
  3139. baseCompiledExpr
  3140. emitSrc func()
  3141. def compiledExpr
  3142. }
  3143. func (e *compiledPatternInitExpr) emitGetter(putOnStack bool) {
  3144. if !putOnStack {
  3145. return
  3146. }
  3147. e.emitSrc()
  3148. if e.def != nil {
  3149. mark := len(e.c.p.code)
  3150. e.c.emit(nil)
  3151. e.c.emitExpr(e.def, true)
  3152. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  3153. }
  3154. }
  3155. func (e *compiledPatternInitExpr) emitNamed(name unistring.String) {
  3156. e.emitSrc()
  3157. if e.def != nil {
  3158. mark := len(e.c.p.code)
  3159. e.c.emit(nil)
  3160. e.c.emitNamedOrConst(e.def, name)
  3161. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  3162. }
  3163. }
  3164. func (c *compiler) compilePatternInitExpr(emitSrc func(), def ast.Expression, idx file.Idx) compiledExpr {
  3165. r := &compiledPatternInitExpr{
  3166. emitSrc: emitSrc,
  3167. def: c.compileExpression(def),
  3168. }
  3169. r.init(c, idx)
  3170. return r
  3171. }
  3172. type compiledEmitterExpr struct {
  3173. baseCompiledExpr
  3174. emitter func()
  3175. namedEmitter func(name unistring.String)
  3176. }
  3177. func (e *compiledEmitterExpr) emitGetter(putOnStack bool) {
  3178. if e.emitter != nil {
  3179. e.emitter()
  3180. } else {
  3181. e.namedEmitter("")
  3182. }
  3183. if !putOnStack {
  3184. e.c.emit(pop)
  3185. }
  3186. }
  3187. func (e *compiledEmitterExpr) emitNamed(name unistring.String) {
  3188. if e.namedEmitter != nil {
  3189. e.namedEmitter(name)
  3190. } else {
  3191. e.emitter()
  3192. }
  3193. }
  3194. func (c *compiler) compileEmitterExpr(emitter func(), idx file.Idx) *compiledEmitterExpr {
  3195. r := &compiledEmitterExpr{
  3196. emitter: emitter,
  3197. }
  3198. r.init(c, idx)
  3199. return r
  3200. }
  3201. func (e *compiledSpreadCallArgument) emitGetter(putOnStack bool) {
  3202. e.expr.emitGetter(putOnStack)
  3203. if putOnStack {
  3204. e.c.emit(pushSpread)
  3205. }
  3206. }
  3207. func (c *compiler) startOptChain() {
  3208. c.block = &block{
  3209. typ: blockOptChain,
  3210. outer: c.block,
  3211. }
  3212. }
  3213. func (c *compiler) endOptChain() {
  3214. lbl := len(c.p.code)
  3215. for _, item := range c.block.breaks {
  3216. c.p.code[item] = jopt(lbl - item)
  3217. }
  3218. for _, item := range c.block.conts {
  3219. c.p.code[item] = joptc(lbl - item)
  3220. }
  3221. c.block = c.block.outer
  3222. }
  3223. func (e *compiledOptionalChain) emitGetter(putOnStack bool) {
  3224. e.c.startOptChain()
  3225. e.expr.emitGetter(true)
  3226. e.c.endOptChain()
  3227. if !putOnStack {
  3228. e.c.emit(pop)
  3229. }
  3230. }
  3231. func (e *compiledOptional) emitGetter(putOnStack bool) {
  3232. e.expr.emitGetter(putOnStack)
  3233. if putOnStack {
  3234. e.c.block.breaks = append(e.c.block.breaks, len(e.c.p.code))
  3235. e.c.emit(nil)
  3236. }
  3237. }