compiler_expr.go 81 KB

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