compiler_expr.go 81 KB

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