compiler_expr.go 80 KB

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