compiler_expr.go 80 KB

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