compiler_expr.go 81 KB

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