compiler_expr.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484
  1. package goja
  2. import (
  3. "fmt"
  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 compiledFunctionLiteral struct {
  96. baseCompiledExpr
  97. name *ast.Identifier
  98. parameterList *ast.ParameterList
  99. body []ast.Statement
  100. source string
  101. declarationList []*ast.VariableDeclaration
  102. lhsName unistring.String
  103. strict *ast.StringLiteral
  104. isExpr bool
  105. isArrow bool
  106. isMethod bool
  107. }
  108. type compiledBracketExpr struct {
  109. baseCompiledExpr
  110. left, member compiledExpr
  111. }
  112. type compiledThisExpr struct {
  113. baseCompiledExpr
  114. }
  115. type compiledNewTarget struct {
  116. baseCompiledExpr
  117. }
  118. type compiledSequenceExpr struct {
  119. baseCompiledExpr
  120. sequence []compiledExpr
  121. }
  122. type compiledUnaryExpr struct {
  123. baseCompiledExpr
  124. operand compiledExpr
  125. operator token.Token
  126. postfix bool
  127. }
  128. type compiledConditionalExpr struct {
  129. baseCompiledExpr
  130. test, consequent, alternate compiledExpr
  131. }
  132. type compiledLogicalOr struct {
  133. baseCompiledExpr
  134. left, right compiledExpr
  135. }
  136. type compiledCoalesce struct {
  137. baseCompiledExpr
  138. left, right compiledExpr
  139. }
  140. type compiledLogicalAnd struct {
  141. baseCompiledExpr
  142. left, right compiledExpr
  143. }
  144. type compiledBinaryExpr struct {
  145. baseCompiledExpr
  146. left, right compiledExpr
  147. operator token.Token
  148. }
  149. type compiledEnumGetExpr struct {
  150. baseCompiledExpr
  151. }
  152. type defaultDeleteExpr struct {
  153. baseCompiledExpr
  154. expr compiledExpr
  155. }
  156. type compiledSpreadCallArgument struct {
  157. baseCompiledExpr
  158. expr compiledExpr
  159. }
  160. type compiledOptionalChain struct {
  161. baseCompiledExpr
  162. expr compiledExpr
  163. }
  164. type compiledOptional struct {
  165. baseCompiledExpr
  166. expr compiledExpr
  167. }
  168. func (e *defaultDeleteExpr) emitGetter(putOnStack bool) {
  169. e.expr.emitGetter(false)
  170. if putOnStack {
  171. e.c.emit(loadVal(e.c.p.defineLiteralValue(valueTrue)))
  172. }
  173. }
  174. func (c *compiler) compileExpression(v ast.Expression) compiledExpr {
  175. // log.Printf("compileExpression: %T", v)
  176. switch v := v.(type) {
  177. case nil:
  178. return nil
  179. case *ast.AssignExpression:
  180. return c.compileAssignExpression(v)
  181. case *ast.NumberLiteral:
  182. return c.compileNumberLiteral(v)
  183. case *ast.StringLiteral:
  184. return c.compileStringLiteral(v)
  185. case *ast.TemplateLiteral:
  186. return c.compileTemplateLiteral(v)
  187. case *ast.BooleanLiteral:
  188. return c.compileBooleanLiteral(v)
  189. case *ast.NullLiteral:
  190. r := &compiledLiteral{
  191. val: _null,
  192. }
  193. r.init(c, v.Idx0())
  194. return r
  195. case *ast.Identifier:
  196. return c.compileIdentifierExpression(v)
  197. case *ast.CallExpression:
  198. return c.compileCallExpression(v)
  199. case *ast.ObjectLiteral:
  200. return c.compileObjectLiteral(v)
  201. case *ast.ArrayLiteral:
  202. return c.compileArrayLiteral(v)
  203. case *ast.RegExpLiteral:
  204. return c.compileRegexpLiteral(v)
  205. case *ast.BinaryExpression:
  206. return c.compileBinaryExpression(v)
  207. case *ast.UnaryExpression:
  208. return c.compileUnaryExpression(v)
  209. case *ast.ConditionalExpression:
  210. return c.compileConditionalExpression(v)
  211. case *ast.FunctionLiteral:
  212. return c.compileFunctionLiteral(v, true)
  213. case *ast.ArrowFunctionLiteral:
  214. return c.compileArrowFunctionLiteral(v)
  215. case *ast.DotExpression:
  216. r := &compiledDotExpr{
  217. left: c.compileExpression(v.Left),
  218. name: v.Identifier.Name,
  219. }
  220. r.init(c, v.Idx0())
  221. return r
  222. case *ast.BracketExpression:
  223. r := &compiledBracketExpr{
  224. left: c.compileExpression(v.Left),
  225. member: c.compileExpression(v.Member),
  226. }
  227. r.init(c, v.Idx0())
  228. return r
  229. case *ast.ThisExpression:
  230. r := &compiledThisExpr{}
  231. r.init(c, v.Idx0())
  232. return r
  233. case *ast.SequenceExpression:
  234. return c.compileSequenceExpression(v)
  235. case *ast.NewExpression:
  236. return c.compileNewExpression(v)
  237. case *ast.MetaProperty:
  238. return c.compileMetaProperty(v)
  239. case *ast.ObjectPattern:
  240. return c.compileObjectAssignmentPattern(v)
  241. case *ast.ArrayPattern:
  242. return c.compileArrayAssignmentPattern(v)
  243. case *ast.OptionalChain:
  244. r := &compiledOptionalChain{
  245. expr: c.compileExpression(v.Expression),
  246. }
  247. r.init(c, v.Idx0())
  248. return r
  249. case *ast.Optional:
  250. r := &compiledOptional{
  251. expr: c.compileExpression(v.Expression),
  252. }
  253. r.init(c, v.Idx0())
  254. return r
  255. default:
  256. panic(fmt.Errorf("Unknown expression type: %T", v))
  257. }
  258. }
  259. func (e *baseCompiledExpr) constant() bool {
  260. return false
  261. }
  262. func (e *baseCompiledExpr) init(c *compiler, idx file.Idx) {
  263. e.c = c
  264. e.offset = int(idx) - 1
  265. }
  266. func (e *baseCompiledExpr) emitSetter(compiledExpr, bool) {
  267. e.c.throwSyntaxError(e.offset, "Not a valid left-value expression")
  268. }
  269. func (e *baseCompiledExpr) emitRef() {
  270. e.c.throwSyntaxError(e.offset, "Cannot emit reference for this type of expression")
  271. }
  272. func (e *baseCompiledExpr) deleteExpr() compiledExpr {
  273. r := &constantExpr{
  274. val: valueTrue,
  275. }
  276. r.init(e.c, file.Idx(e.offset+1))
  277. return r
  278. }
  279. func (e *baseCompiledExpr) emitUnary(func(), func(), bool, bool) {
  280. e.c.throwSyntaxError(e.offset, "Not a valid left-value expression")
  281. }
  282. func (e *baseCompiledExpr) addSrcMap() {
  283. if e.offset >= 0 {
  284. e.c.p.addSrcMap(e.offset)
  285. }
  286. }
  287. func (e *constantExpr) emitGetter(putOnStack bool) {
  288. if putOnStack {
  289. e.addSrcMap()
  290. e.c.emit(loadVal(e.c.p.defineLiteralValue(e.val)))
  291. }
  292. }
  293. func (e *compiledIdentifierExpr) emitGetter(putOnStack bool) {
  294. e.addSrcMap()
  295. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  296. if b != nil {
  297. if putOnStack {
  298. b.emitGet()
  299. } else {
  300. b.emitGetP()
  301. }
  302. } else {
  303. panic("No dynamics and not found")
  304. }
  305. } else {
  306. if b != nil {
  307. b.emitGetVar(false)
  308. } else {
  309. e.c.emit(loadDynamic(e.name))
  310. }
  311. if !putOnStack {
  312. e.c.emit(pop)
  313. }
  314. }
  315. }
  316. func (e *compiledIdentifierExpr) emitGetterOrRef() {
  317. e.addSrcMap()
  318. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  319. if b != nil {
  320. b.emitGet()
  321. } else {
  322. panic("No dynamics and not found")
  323. }
  324. } else {
  325. if b != nil {
  326. b.emitGetVar(false)
  327. } else {
  328. e.c.emit(loadDynamicRef(e.name))
  329. }
  330. }
  331. }
  332. func (e *compiledIdentifierExpr) emitGetterAndCallee() {
  333. e.addSrcMap()
  334. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  335. if b != nil {
  336. e.c.emit(loadUndef)
  337. b.emitGet()
  338. } else {
  339. panic("No dynamics and not found")
  340. }
  341. } else {
  342. if b != nil {
  343. b.emitGetVar(true)
  344. } else {
  345. e.c.emit(loadDynamicCallee(e.name))
  346. }
  347. }
  348. }
  349. func (e *compiledIdentifierExpr) emitVarSetter1(putOnStack bool, emitRight func(isRef bool)) {
  350. e.addSrcMap()
  351. c := e.c
  352. if b, noDynamics := c.scope.lookupName(e.name); noDynamics {
  353. if c.scope.strict {
  354. c.checkIdentifierLName(e.name, e.offset)
  355. }
  356. emitRight(false)
  357. if b != nil {
  358. if putOnStack {
  359. b.emitSet()
  360. } else {
  361. b.emitSetP()
  362. }
  363. } else {
  364. if c.scope.strict {
  365. c.emit(setGlobalStrict(e.name))
  366. } else {
  367. c.emit(setGlobal(e.name))
  368. }
  369. if !putOnStack {
  370. c.emit(pop)
  371. }
  372. }
  373. } else {
  374. c.emitVarRef(e.name, e.offset, b)
  375. emitRight(true)
  376. if putOnStack {
  377. c.emit(putValue)
  378. } else {
  379. c.emit(putValueP)
  380. }
  381. }
  382. }
  383. func (e *compiledIdentifierExpr) emitVarSetter(valueExpr compiledExpr, putOnStack bool) {
  384. e.emitVarSetter1(putOnStack, func(bool) {
  385. e.c.emitNamedOrConst(valueExpr, e.name)
  386. })
  387. }
  388. func (c *compiler) emitVarRef(name unistring.String, offset int, b *binding) {
  389. if c.scope.strict {
  390. c.checkIdentifierLName(name, offset)
  391. }
  392. if b != nil {
  393. b.emitResolveVar(c.scope.strict)
  394. } else {
  395. if c.scope.strict {
  396. c.emit(resolveVar1Strict(name))
  397. } else {
  398. c.emit(resolveVar1(name))
  399. }
  400. }
  401. }
  402. func (e *compiledIdentifierExpr) emitRef() {
  403. b, _ := e.c.scope.lookupName(e.name)
  404. e.c.emitVarRef(e.name, e.offset, b)
  405. }
  406. func (e *compiledIdentifierExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  407. e.emitVarSetter(valueExpr, putOnStack)
  408. }
  409. func (e *compiledIdentifierExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  410. if putOnStack {
  411. e.emitVarSetter1(true, func(isRef bool) {
  412. e.c.emit(loadUndef)
  413. if isRef {
  414. e.c.emit(getValue)
  415. } else {
  416. e.emitGetter(true)
  417. }
  418. if prepare != nil {
  419. prepare()
  420. }
  421. if !postfix {
  422. body()
  423. }
  424. e.c.emit(rdupN(1))
  425. if postfix {
  426. body()
  427. }
  428. })
  429. e.c.emit(pop)
  430. } else {
  431. e.emitVarSetter1(false, func(isRef bool) {
  432. if isRef {
  433. e.c.emit(getValue)
  434. } else {
  435. e.emitGetter(true)
  436. }
  437. body()
  438. })
  439. }
  440. }
  441. func (e *compiledIdentifierExpr) deleteExpr() compiledExpr {
  442. if e.c.scope.strict {
  443. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  444. panic("Unreachable")
  445. }
  446. if b, noDynamics := e.c.scope.lookupName(e.name); noDynamics {
  447. if b == nil {
  448. r := &deleteGlobalExpr{
  449. name: e.name,
  450. }
  451. r.init(e.c, file.Idx(0))
  452. return r
  453. }
  454. } else {
  455. if b == nil {
  456. r := &deleteVarExpr{
  457. name: e.name,
  458. }
  459. r.init(e.c, file.Idx(e.offset+1))
  460. return r
  461. }
  462. }
  463. r := &compiledLiteral{
  464. val: valueFalse,
  465. }
  466. r.init(e.c, file.Idx(e.offset+1))
  467. return r
  468. }
  469. type compiledDotExpr struct {
  470. baseCompiledExpr
  471. left compiledExpr
  472. name unistring.String
  473. }
  474. func (e *compiledDotExpr) emitGetter(putOnStack bool) {
  475. e.left.emitGetter(true)
  476. e.addSrcMap()
  477. e.c.emit(getProp(e.name))
  478. if !putOnStack {
  479. e.c.emit(pop)
  480. }
  481. }
  482. func (e *compiledDotExpr) emitRef() {
  483. e.left.emitGetter(true)
  484. if e.c.scope.strict {
  485. e.c.emit(getPropRefStrict(e.name))
  486. } else {
  487. e.c.emit(getPropRef(e.name))
  488. }
  489. }
  490. func (e *compiledDotExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  491. e.left.emitGetter(true)
  492. valueExpr.emitGetter(true)
  493. if e.c.scope.strict {
  494. if putOnStack {
  495. e.c.emit(setPropStrict(e.name))
  496. } else {
  497. e.c.emit(setPropStrictP(e.name))
  498. }
  499. } else {
  500. if putOnStack {
  501. e.c.emit(setProp(e.name))
  502. } else {
  503. e.c.emit(setPropP(e.name))
  504. }
  505. }
  506. }
  507. func (e *compiledDotExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  508. if !putOnStack {
  509. e.left.emitGetter(true)
  510. e.c.emit(dup)
  511. e.c.emit(getProp(e.name))
  512. body()
  513. if e.c.scope.strict {
  514. e.c.emit(setPropStrict(e.name), pop)
  515. } else {
  516. e.c.emit(setProp(e.name), pop)
  517. }
  518. } else {
  519. if !postfix {
  520. e.left.emitGetter(true)
  521. e.c.emit(dup)
  522. e.c.emit(getProp(e.name))
  523. if prepare != nil {
  524. prepare()
  525. }
  526. body()
  527. if e.c.scope.strict {
  528. e.c.emit(setPropStrict(e.name))
  529. } else {
  530. e.c.emit(setProp(e.name))
  531. }
  532. } else {
  533. e.c.emit(loadUndef)
  534. e.left.emitGetter(true)
  535. e.c.emit(dup)
  536. e.c.emit(getProp(e.name))
  537. if prepare != nil {
  538. prepare()
  539. }
  540. e.c.emit(rdupN(2))
  541. body()
  542. if e.c.scope.strict {
  543. e.c.emit(setPropStrict(e.name))
  544. } else {
  545. e.c.emit(setProp(e.name))
  546. }
  547. e.c.emit(pop)
  548. }
  549. }
  550. }
  551. func (e *compiledDotExpr) deleteExpr() compiledExpr {
  552. r := &deletePropExpr{
  553. left: e.left,
  554. name: e.name,
  555. }
  556. r.init(e.c, file.Idx(0))
  557. return r
  558. }
  559. func (e *compiledBracketExpr) emitGetter(putOnStack bool) {
  560. e.left.emitGetter(true)
  561. e.member.emitGetter(true)
  562. e.addSrcMap()
  563. e.c.emit(getElem)
  564. if !putOnStack {
  565. e.c.emit(pop)
  566. }
  567. }
  568. func (e *compiledBracketExpr) emitRef() {
  569. e.left.emitGetter(true)
  570. e.member.emitGetter(true)
  571. if e.c.scope.strict {
  572. e.c.emit(getElemRefStrict)
  573. } else {
  574. e.c.emit(getElemRef)
  575. }
  576. }
  577. func (e *compiledBracketExpr) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  578. e.left.emitGetter(true)
  579. e.member.emitGetter(true)
  580. valueExpr.emitGetter(true)
  581. if e.c.scope.strict {
  582. if putOnStack {
  583. e.c.emit(setElemStrict)
  584. } else {
  585. e.c.emit(setElemStrictP)
  586. }
  587. } else {
  588. if putOnStack {
  589. e.c.emit(setElem)
  590. } else {
  591. e.c.emit(setElemP)
  592. }
  593. }
  594. }
  595. func (e *compiledBracketExpr) emitUnary(prepare, body func(), postfix, putOnStack bool) {
  596. if !putOnStack {
  597. e.left.emitGetter(true)
  598. e.member.emitGetter(true)
  599. e.c.emit(dupN(1), dupN(1))
  600. e.c.emit(getElem)
  601. body()
  602. if e.c.scope.strict {
  603. e.c.emit(setElemStrict, pop)
  604. } else {
  605. e.c.emit(setElem, pop)
  606. }
  607. } else {
  608. if !postfix {
  609. e.left.emitGetter(true)
  610. e.member.emitGetter(true)
  611. e.c.emit(dupN(1), dupN(1))
  612. e.c.emit(getElem)
  613. if prepare != nil {
  614. prepare()
  615. }
  616. body()
  617. if e.c.scope.strict {
  618. e.c.emit(setElemStrict)
  619. } else {
  620. e.c.emit(setElem)
  621. }
  622. } else {
  623. e.c.emit(loadUndef)
  624. e.left.emitGetter(true)
  625. e.member.emitGetter(true)
  626. e.c.emit(dupN(1), dupN(1))
  627. e.c.emit(getElem)
  628. if prepare != nil {
  629. prepare()
  630. }
  631. e.c.emit(rdupN(3))
  632. body()
  633. if e.c.scope.strict {
  634. e.c.emit(setElemStrict, pop)
  635. } else {
  636. e.c.emit(setElem, pop)
  637. }
  638. }
  639. }
  640. }
  641. func (e *compiledBracketExpr) deleteExpr() compiledExpr {
  642. r := &deleteElemExpr{
  643. left: e.left,
  644. member: e.member,
  645. }
  646. r.init(e.c, file.Idx(0))
  647. return r
  648. }
  649. func (e *deleteElemExpr) emitGetter(putOnStack bool) {
  650. e.left.emitGetter(true)
  651. e.member.emitGetter(true)
  652. e.addSrcMap()
  653. if e.c.scope.strict {
  654. e.c.emit(deleteElemStrict)
  655. } else {
  656. e.c.emit(deleteElem)
  657. }
  658. if !putOnStack {
  659. e.c.emit(pop)
  660. }
  661. }
  662. func (e *deletePropExpr) emitGetter(putOnStack bool) {
  663. e.left.emitGetter(true)
  664. e.addSrcMap()
  665. if e.c.scope.strict {
  666. e.c.emit(deletePropStrict(e.name))
  667. } else {
  668. e.c.emit(deleteProp(e.name))
  669. }
  670. if !putOnStack {
  671. e.c.emit(pop)
  672. }
  673. }
  674. func (e *deleteVarExpr) emitGetter(putOnStack bool) {
  675. /*if e.c.scope.strict {
  676. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  677. return
  678. }*/
  679. e.c.emit(deleteVar(e.name))
  680. if !putOnStack {
  681. e.c.emit(pop)
  682. }
  683. }
  684. func (e *deleteGlobalExpr) emitGetter(putOnStack bool) {
  685. /*if e.c.scope.strict {
  686. e.c.throwSyntaxError(e.offset, "Delete of an unqualified identifier in strict mode")
  687. return
  688. }*/
  689. e.c.emit(deleteGlobal(e.name))
  690. if !putOnStack {
  691. e.c.emit(pop)
  692. }
  693. }
  694. func (e *compiledAssignExpr) emitGetter(putOnStack bool) {
  695. switch e.operator {
  696. case token.ASSIGN:
  697. e.left.emitSetter(e.right, putOnStack)
  698. case token.PLUS:
  699. e.left.emitUnary(nil, func() {
  700. e.right.emitGetter(true)
  701. e.c.emit(add)
  702. }, false, putOnStack)
  703. case token.MINUS:
  704. e.left.emitUnary(nil, func() {
  705. e.right.emitGetter(true)
  706. e.c.emit(sub)
  707. }, false, putOnStack)
  708. case token.MULTIPLY:
  709. e.left.emitUnary(nil, func() {
  710. e.right.emitGetter(true)
  711. e.c.emit(mul)
  712. }, false, putOnStack)
  713. case token.EXPONENT:
  714. e.left.emitUnary(nil, func() {
  715. e.right.emitGetter(true)
  716. e.c.emit(exp)
  717. }, false, putOnStack)
  718. case token.SLASH:
  719. e.left.emitUnary(nil, func() {
  720. e.right.emitGetter(true)
  721. e.c.emit(div)
  722. }, false, putOnStack)
  723. case token.REMAINDER:
  724. e.left.emitUnary(nil, func() {
  725. e.right.emitGetter(true)
  726. e.c.emit(mod)
  727. }, false, putOnStack)
  728. case token.OR:
  729. e.left.emitUnary(nil, func() {
  730. e.right.emitGetter(true)
  731. e.c.emit(or)
  732. }, false, putOnStack)
  733. case token.AND:
  734. e.left.emitUnary(nil, func() {
  735. e.right.emitGetter(true)
  736. e.c.emit(and)
  737. }, false, putOnStack)
  738. case token.EXCLUSIVE_OR:
  739. e.left.emitUnary(nil, func() {
  740. e.right.emitGetter(true)
  741. e.c.emit(xor)
  742. }, false, putOnStack)
  743. case token.SHIFT_LEFT:
  744. e.left.emitUnary(nil, func() {
  745. e.right.emitGetter(true)
  746. e.c.emit(sal)
  747. }, false, putOnStack)
  748. case token.SHIFT_RIGHT:
  749. e.left.emitUnary(nil, func() {
  750. e.right.emitGetter(true)
  751. e.c.emit(sar)
  752. }, false, putOnStack)
  753. case token.UNSIGNED_SHIFT_RIGHT:
  754. e.left.emitUnary(nil, func() {
  755. e.right.emitGetter(true)
  756. e.c.emit(shr)
  757. }, false, putOnStack)
  758. default:
  759. panic(fmt.Errorf("Unknown assign operator: %s", e.operator.String()))
  760. }
  761. }
  762. func (e *compiledLiteral) emitGetter(putOnStack bool) {
  763. if putOnStack {
  764. e.c.emit(loadVal(e.c.p.defineLiteralValue(e.val)))
  765. }
  766. }
  767. func (e *compiledLiteral) constant() bool {
  768. return true
  769. }
  770. func (e *compiledTemplateLiteral) emitGetter(putOnStack bool) {
  771. if e.tag == nil {
  772. if len(e.elements) == 0 {
  773. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringEmpty)))
  774. } else {
  775. tail := e.elements[len(e.elements)-1].Parsed
  776. if len(e.elements) == 1 {
  777. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(tail))))
  778. } else {
  779. stringCount := 0
  780. if head := e.elements[0].Parsed; head != "" {
  781. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(head))))
  782. stringCount++
  783. }
  784. e.expressions[0].emitGetter(true)
  785. e.c.emit(_toString{})
  786. stringCount++
  787. for i := 1; i < len(e.elements)-1; i++ {
  788. if elt := e.elements[i].Parsed; elt != "" {
  789. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(elt))))
  790. stringCount++
  791. }
  792. e.expressions[i].emitGetter(true)
  793. e.c.emit(_toString{})
  794. stringCount++
  795. }
  796. if tail != "" {
  797. e.c.emit(loadVal(e.c.p.defineLiteralValue(stringValueFromRaw(tail))))
  798. stringCount++
  799. }
  800. e.c.emit(concatStrings(stringCount))
  801. }
  802. }
  803. } else {
  804. cooked := make([]Value, len(e.elements))
  805. raw := make([]Value, len(e.elements))
  806. for i, elt := range e.elements {
  807. raw[i] = &valueProperty{
  808. enumerable: true,
  809. value: newStringValue(elt.Literal),
  810. }
  811. var cookedVal Value
  812. if elt.Valid {
  813. cookedVal = stringValueFromRaw(elt.Parsed)
  814. } else {
  815. cookedVal = _undefined
  816. }
  817. cooked[i] = &valueProperty{
  818. enumerable: true,
  819. value: cookedVal,
  820. }
  821. }
  822. e.c.emitCallee(e.tag)
  823. e.c.emit(&getTaggedTmplObject{
  824. raw: raw,
  825. cooked: cooked,
  826. })
  827. for _, expr := range e.expressions {
  828. expr.emitGetter(true)
  829. }
  830. e.c.emit(call(len(e.expressions) + 1))
  831. }
  832. if !putOnStack {
  833. e.c.emit(pop)
  834. }
  835. }
  836. func (c *compiler) compileParameterBindingIdentifier(name unistring.String, offset int) (*binding, bool) {
  837. if c.scope.strict {
  838. c.checkIdentifierName(name, offset)
  839. c.checkIdentifierLName(name, offset)
  840. }
  841. return c.scope.bindNameShadow(name)
  842. }
  843. func (c *compiler) compileParameterPatternIdBinding(name unistring.String, offset int) {
  844. if _, unique := c.compileParameterBindingIdentifier(name, offset); !unique {
  845. c.throwSyntaxError(offset, "Duplicate parameter name not allowed in this context")
  846. }
  847. }
  848. func (c *compiler) compileParameterPatternBinding(item ast.Expression) {
  849. c.createBindings(item, c.compileParameterPatternIdBinding)
  850. }
  851. func (e *compiledFunctionLiteral) emitGetter(putOnStack bool) {
  852. savedPrg := e.c.p
  853. e.c.p = &Program{
  854. src: e.c.p.src,
  855. }
  856. e.c.newScope()
  857. s := e.c.scope
  858. s.function = true
  859. s.arrow = e.isArrow
  860. var name unistring.String
  861. if e.name != nil {
  862. name = e.name.Name
  863. } else {
  864. name = e.lhsName
  865. }
  866. if name != "" {
  867. e.c.p.funcName = name
  868. }
  869. savedBlock := e.c.block
  870. defer func() {
  871. e.c.block = savedBlock
  872. }()
  873. e.c.block = &block{
  874. typ: blockScope,
  875. }
  876. if !s.strict {
  877. s.strict = e.strict != nil
  878. }
  879. hasPatterns := false
  880. hasInits := false
  881. firstDupIdx := -1
  882. length := 0
  883. if e.parameterList.Rest != nil {
  884. hasPatterns = true // strictly speaking not, but we need to activate all the checks
  885. }
  886. // First, make sure that the first bindings correspond to the formal parameters
  887. for _, item := range e.parameterList.List {
  888. switch tgt := item.Target.(type) {
  889. case *ast.Identifier:
  890. offset := int(tgt.Idx) - 1
  891. b, unique := e.c.compileParameterBindingIdentifier(tgt.Name, offset)
  892. if !unique {
  893. firstDupIdx = offset
  894. }
  895. b.isArg = true
  896. case ast.Pattern:
  897. b := s.addBinding(int(item.Idx0()) - 1)
  898. b.isArg = true
  899. hasPatterns = true
  900. default:
  901. e.c.throwSyntaxError(int(item.Idx0())-1, "Unsupported BindingElement type: %T", item)
  902. return
  903. }
  904. if item.Initializer != nil {
  905. hasInits = true
  906. }
  907. if firstDupIdx >= 0 && (hasPatterns || hasInits || s.strict || e.isArrow || e.isMethod) {
  908. e.c.throwSyntaxError(firstDupIdx, "Duplicate parameter name not allowed in this context")
  909. return
  910. }
  911. if (hasPatterns || hasInits) && e.strict != nil {
  912. e.c.throwSyntaxError(int(e.strict.Idx)-1, "Illegal 'use strict' directive in function with non-simple parameter list")
  913. return
  914. }
  915. if !hasInits {
  916. length++
  917. }
  918. }
  919. // create pattern bindings
  920. if hasPatterns {
  921. for _, item := range e.parameterList.List {
  922. switch tgt := item.Target.(type) {
  923. case *ast.Identifier:
  924. // we already created those in the previous loop, skipping
  925. default:
  926. e.c.compileParameterPatternBinding(tgt)
  927. }
  928. }
  929. if rest := e.parameterList.Rest; rest != nil {
  930. e.c.compileParameterPatternBinding(rest)
  931. }
  932. }
  933. paramsCount := len(e.parameterList.List)
  934. s.numArgs = paramsCount
  935. body := e.body
  936. funcs := e.c.extractFunctions(body)
  937. var calleeBinding *binding
  938. preambleLen := 4 // enter, boxThis, createArgs, set
  939. e.c.p.code = make([]instruction, preambleLen, 8)
  940. emitArgsRestMark := -1
  941. firstForwardRef := -1
  942. enterFunc2Mark := -1
  943. if hasPatterns || hasInits {
  944. if e.isExpr && e.name != nil {
  945. if b, created := s.bindNameLexical(e.name.Name, false, 0); created {
  946. b.isConst = true
  947. calleeBinding = b
  948. }
  949. }
  950. if calleeBinding != nil {
  951. e.c.emit(loadCallee)
  952. calleeBinding.emitInit()
  953. }
  954. for i, item := range e.parameterList.List {
  955. if pattern, ok := item.Target.(ast.Pattern); ok {
  956. i := i
  957. e.c.compilePatternInitExpr(func() {
  958. if firstForwardRef == -1 {
  959. s.bindings[i].emitGet()
  960. } else {
  961. e.c.emit(loadStackLex(-i - 1))
  962. }
  963. }, item.Initializer, item.Target.Idx0()).emitGetter(true)
  964. e.c.emitPattern(pattern, func(target, init compiledExpr) {
  965. e.c.emitPatternLexicalAssign(target, init)
  966. }, false)
  967. } else if item.Initializer != nil {
  968. markGet := len(e.c.p.code)
  969. e.c.emit(nil)
  970. mark := len(e.c.p.code)
  971. e.c.emit(nil)
  972. e.c.emitExpr(e.c.compileExpression(item.Initializer), true)
  973. if firstForwardRef == -1 && (s.isDynamic() || s.bindings[i].useCount() > 0) {
  974. firstForwardRef = i
  975. }
  976. if firstForwardRef == -1 {
  977. s.bindings[i].emitGetAt(markGet)
  978. } else {
  979. e.c.p.code[markGet] = loadStackLex(-i - 1)
  980. }
  981. s.bindings[i].emitInit()
  982. e.c.p.code[mark] = jdefP(len(e.c.p.code) - mark)
  983. } else {
  984. if firstForwardRef == -1 && s.bindings[i].useCount() > 0 {
  985. firstForwardRef = i
  986. }
  987. if firstForwardRef != -1 {
  988. e.c.emit(loadStackLex(-i - 1))
  989. s.bindings[i].emitInit()
  990. }
  991. }
  992. }
  993. if rest := e.parameterList.Rest; rest != nil {
  994. e.c.emitAssign(rest, e.c.compileEmitterExpr(
  995. func() {
  996. emitArgsRestMark = len(e.c.p.code)
  997. e.c.emit(createArgsRestStack(paramsCount))
  998. }, rest.Idx0()),
  999. func(target, init compiledExpr) {
  1000. e.c.emitPatternLexicalAssign(target, init)
  1001. })
  1002. }
  1003. if firstForwardRef != -1 {
  1004. for _, b := range s.bindings {
  1005. b.inStash = true
  1006. }
  1007. s.argsInStash = true
  1008. s.needStash = true
  1009. }
  1010. e.c.newBlockScope()
  1011. varScope := e.c.scope
  1012. varScope.variable = true
  1013. enterFunc2Mark = len(e.c.p.code)
  1014. e.c.emit(nil)
  1015. e.c.compileDeclList(e.declarationList, false)
  1016. e.c.createFunctionBindings(funcs)
  1017. e.c.compileLexicalDeclarationsFuncBody(body, calleeBinding)
  1018. for _, b := range varScope.bindings {
  1019. if b.isVar {
  1020. if parentBinding := s.boundNames[b.name]; parentBinding != nil && parentBinding != calleeBinding {
  1021. parentBinding.emitGet()
  1022. b.emitSetP()
  1023. }
  1024. }
  1025. }
  1026. } else {
  1027. // To avoid triggering variable conflict when binding from non-strict direct eval().
  1028. // Parameters are supposed to be in a parent scope, hence no conflict.
  1029. for _, b := range s.bindings[:paramsCount] {
  1030. b.isVar = true
  1031. }
  1032. e.c.compileDeclList(e.declarationList, true)
  1033. e.c.createFunctionBindings(funcs)
  1034. e.c.compileLexicalDeclarations(body, true)
  1035. if e.isExpr && e.name != nil {
  1036. if b, created := s.bindNameLexical(e.name.Name, false, 0); created {
  1037. b.isConst = true
  1038. calleeBinding = b
  1039. }
  1040. }
  1041. if calleeBinding != nil {
  1042. e.c.emit(loadCallee)
  1043. calleeBinding.emitInit()
  1044. }
  1045. }
  1046. e.c.compileFunctions(funcs)
  1047. e.c.compileStatements(body, false)
  1048. var last ast.Statement
  1049. if l := len(body); l > 0 {
  1050. last = body[l-1]
  1051. }
  1052. if _, ok := last.(*ast.ReturnStatement); !ok {
  1053. e.c.emit(loadUndef, ret)
  1054. }
  1055. delta := 0
  1056. code := e.c.p.code
  1057. if calleeBinding != nil && !s.isDynamic() && calleeBinding.useCount() == 1 {
  1058. s.deleteBinding(calleeBinding)
  1059. preambleLen += 2
  1060. }
  1061. if !s.argsInStash && (s.argsNeeded || s.isDynamic()) {
  1062. s.moveArgsToStash()
  1063. }
  1064. if s.argsNeeded {
  1065. b, created := s.bindNameLexical("arguments", false, 0)
  1066. if !created && !b.isVar {
  1067. s.argsNeeded = false
  1068. } else {
  1069. if s.strict {
  1070. b.isConst = true
  1071. } else {
  1072. b.isVar = e.c.scope.function
  1073. }
  1074. pos := preambleLen - 2
  1075. delta += 2
  1076. if s.strict || hasPatterns || hasInits {
  1077. code[pos] = createArgsUnmapped(paramsCount)
  1078. } else {
  1079. code[pos] = createArgsMapped(paramsCount)
  1080. }
  1081. pos++
  1082. b.markAccessPointAtScope(s, pos)
  1083. code[pos] = storeStashP(0)
  1084. }
  1085. }
  1086. stashSize, stackSize := s.finaliseVarAlloc(0)
  1087. if !s.strict && s.thisNeeded {
  1088. delta++
  1089. code[preambleLen-delta] = boxThis
  1090. }
  1091. delta++
  1092. delta = preambleLen - delta
  1093. var enter instruction
  1094. if stashSize > 0 || s.argsInStash {
  1095. if firstForwardRef == -1 {
  1096. enter1 := enterFunc{
  1097. numArgs: uint32(paramsCount),
  1098. argsToStash: s.argsInStash,
  1099. stashSize: uint32(stashSize),
  1100. stackSize: uint32(stackSize),
  1101. extensible: s.dynamic,
  1102. }
  1103. if s.isDynamic() {
  1104. enter1.names = s.makeNamesMap()
  1105. }
  1106. enter = &enter1
  1107. if enterFunc2Mark != -1 {
  1108. ef2 := &enterFuncBody{
  1109. extensible: e.c.scope.dynamic,
  1110. }
  1111. e.c.updateEnterBlock(&ef2.enterBlock)
  1112. e.c.p.code[enterFunc2Mark] = ef2
  1113. }
  1114. } else {
  1115. enter1 := enterFunc1{
  1116. stashSize: uint32(stashSize),
  1117. numArgs: uint32(paramsCount),
  1118. argsToCopy: uint32(firstForwardRef),
  1119. extensible: s.dynamic,
  1120. }
  1121. if s.isDynamic() {
  1122. enter1.names = s.makeNamesMap()
  1123. }
  1124. enter = &enter1
  1125. if enterFunc2Mark != -1 {
  1126. ef2 := &enterFuncBody{
  1127. adjustStack: true,
  1128. extensible: e.c.scope.dynamic,
  1129. }
  1130. e.c.updateEnterBlock(&ef2.enterBlock)
  1131. e.c.p.code[enterFunc2Mark] = ef2
  1132. }
  1133. }
  1134. if emitArgsRestMark != -1 && s.argsInStash {
  1135. e.c.p.code[emitArgsRestMark] = createArgsRestStash
  1136. }
  1137. } else {
  1138. enter = &enterFuncStashless{
  1139. stackSize: uint32(stackSize),
  1140. args: uint32(paramsCount),
  1141. }
  1142. if enterFunc2Mark != -1 {
  1143. ef2 := &enterFuncBody{
  1144. extensible: e.c.scope.dynamic,
  1145. }
  1146. e.c.updateEnterBlock(&ef2.enterBlock)
  1147. e.c.p.code[enterFunc2Mark] = ef2
  1148. }
  1149. }
  1150. code[delta] = enter
  1151. if delta != 0 {
  1152. e.c.p.code = code[delta:]
  1153. for i := range e.c.p.srcMap {
  1154. e.c.p.srcMap[i].pc -= delta
  1155. }
  1156. s.adjustBase(-delta)
  1157. }
  1158. strict := s.strict
  1159. p := e.c.p
  1160. // e.c.p.dumpCode()
  1161. if enterFunc2Mark != -1 {
  1162. e.c.popScope()
  1163. }
  1164. e.c.popScope()
  1165. e.c.p = savedPrg
  1166. if e.isArrow {
  1167. e.c.emit(&newArrowFunc{newFunc: newFunc{prg: p, length: length, name: name, source: e.source, strict: strict}})
  1168. } else {
  1169. if e.isMethod {
  1170. e.c.emit(&newMethod{prg: p, length: length, name: name, source: e.source, strict: strict})
  1171. } else {
  1172. e.c.emit(&newFunc{prg: p, length: length, name: name, source: e.source, strict: strict})
  1173. }
  1174. }
  1175. if !putOnStack {
  1176. e.c.emit(pop)
  1177. }
  1178. }
  1179. func (c *compiler) compileFunctionLiteral(v *ast.FunctionLiteral, isExpr bool) *compiledFunctionLiteral {
  1180. strictBody := c.isStrictStatement(v.Body)
  1181. if v.Name != nil && (c.scope.strict || strictBody != nil) {
  1182. c.checkIdentifierLName(v.Name.Name, int(v.Name.Idx)-1)
  1183. }
  1184. r := &compiledFunctionLiteral{
  1185. name: v.Name,
  1186. parameterList: v.ParameterList,
  1187. body: v.Body.List,
  1188. source: v.Source,
  1189. declarationList: v.DeclarationList,
  1190. isExpr: isExpr,
  1191. strict: strictBody,
  1192. }
  1193. r.init(c, v.Idx0())
  1194. return r
  1195. }
  1196. func (c *compiler) compileArrowFunctionLiteral(v *ast.ArrowFunctionLiteral) *compiledFunctionLiteral {
  1197. var strictBody *ast.StringLiteral
  1198. var body []ast.Statement
  1199. switch b := v.Body.(type) {
  1200. case *ast.BlockStatement:
  1201. strictBody = c.isStrictStatement(b)
  1202. body = b.List
  1203. case *ast.ExpressionBody:
  1204. body = []ast.Statement{
  1205. &ast.ReturnStatement{
  1206. Argument: b.Expression,
  1207. },
  1208. }
  1209. default:
  1210. c.throwSyntaxError(int(b.Idx0())-1, "Unsupported ConciseBody type: %T", b)
  1211. }
  1212. r := &compiledFunctionLiteral{
  1213. parameterList: v.ParameterList,
  1214. body: body,
  1215. source: v.Source,
  1216. declarationList: v.DeclarationList,
  1217. isExpr: true,
  1218. isArrow: true,
  1219. strict: strictBody,
  1220. }
  1221. r.init(c, v.Idx0())
  1222. return r
  1223. }
  1224. func (e *compiledThisExpr) emitGetter(putOnStack bool) {
  1225. if putOnStack {
  1226. e.addSrcMap()
  1227. scope := e.c.scope
  1228. for ; scope != nil && (scope.arrow || !scope.function && !scope.eval); scope = scope.outer {
  1229. }
  1230. if scope != nil {
  1231. scope.thisNeeded = true
  1232. e.c.emit(loadStack(0))
  1233. } else {
  1234. e.c.emit(loadGlobalObject)
  1235. }
  1236. }
  1237. }
  1238. func (e *compiledNewExpr) emitGetter(putOnStack bool) {
  1239. if e.isVariadic {
  1240. e.c.emit(startVariadic)
  1241. }
  1242. e.callee.emitGetter(true)
  1243. for _, expr := range e.args {
  1244. expr.emitGetter(true)
  1245. }
  1246. e.addSrcMap()
  1247. if e.isVariadic {
  1248. e.c.emit(newVariadic, endVariadic)
  1249. } else {
  1250. e.c.emit(_new(len(e.args)))
  1251. }
  1252. if !putOnStack {
  1253. e.c.emit(pop)
  1254. }
  1255. }
  1256. func (c *compiler) compileCallArgs(list []ast.Expression) (args []compiledExpr, isVariadic bool) {
  1257. args = make([]compiledExpr, len(list))
  1258. for i, argExpr := range list {
  1259. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  1260. args[i] = c.compileSpreadCallArgument(spread)
  1261. isVariadic = true
  1262. } else {
  1263. args[i] = c.compileExpression(argExpr)
  1264. }
  1265. }
  1266. return
  1267. }
  1268. func (c *compiler) compileNewExpression(v *ast.NewExpression) compiledExpr {
  1269. args, isVariadic := c.compileCallArgs(v.ArgumentList)
  1270. r := &compiledNewExpr{
  1271. compiledCallExpr: compiledCallExpr{
  1272. callee: c.compileExpression(v.Callee),
  1273. args: args,
  1274. isVariadic: isVariadic,
  1275. },
  1276. }
  1277. r.init(c, v.Idx0())
  1278. return r
  1279. }
  1280. func (e *compiledNewTarget) emitGetter(putOnStack bool) {
  1281. if putOnStack {
  1282. e.addSrcMap()
  1283. e.c.emit(loadNewTarget)
  1284. }
  1285. }
  1286. func (c *compiler) compileMetaProperty(v *ast.MetaProperty) compiledExpr {
  1287. if v.Meta.Name == "new" || v.Property.Name != "target" {
  1288. r := &compiledNewTarget{}
  1289. r.init(c, v.Idx0())
  1290. return r
  1291. }
  1292. c.throwSyntaxError(int(v.Idx)-1, "Unsupported meta property: %s.%s", v.Meta.Name, v.Property.Name)
  1293. return nil
  1294. }
  1295. func (e *compiledSequenceExpr) emitGetter(putOnStack bool) {
  1296. if len(e.sequence) > 0 {
  1297. for i := 0; i < len(e.sequence)-1; i++ {
  1298. e.sequence[i].emitGetter(false)
  1299. }
  1300. e.sequence[len(e.sequence)-1].emitGetter(putOnStack)
  1301. }
  1302. }
  1303. func (c *compiler) compileSequenceExpression(v *ast.SequenceExpression) compiledExpr {
  1304. s := make([]compiledExpr, len(v.Sequence))
  1305. for i, expr := range v.Sequence {
  1306. s[i] = c.compileExpression(expr)
  1307. }
  1308. r := &compiledSequenceExpr{
  1309. sequence: s,
  1310. }
  1311. var idx file.Idx
  1312. if len(v.Sequence) > 0 {
  1313. idx = v.Idx0()
  1314. }
  1315. r.init(c, idx)
  1316. return r
  1317. }
  1318. func (c *compiler) emitThrow(v Value) {
  1319. if o, ok := v.(*Object); ok {
  1320. t := nilSafe(o.self.getStr("name", nil)).toString().String()
  1321. switch t {
  1322. case "TypeError":
  1323. c.emit(loadDynamic(t))
  1324. msg := o.self.getStr("message", nil)
  1325. if msg != nil {
  1326. c.emit(loadVal(c.p.defineLiteralValue(msg)))
  1327. c.emit(_new(1))
  1328. } else {
  1329. c.emit(_new(0))
  1330. }
  1331. c.emit(throw)
  1332. return
  1333. }
  1334. }
  1335. panic(fmt.Errorf("unknown exception type thrown while evaliating constant expression: %s", v.String()))
  1336. }
  1337. func (c *compiler) emitConst(expr compiledExpr, putOnStack bool) {
  1338. v, ex := c.evalConst(expr)
  1339. if ex == nil {
  1340. if putOnStack {
  1341. c.emit(loadVal(c.p.defineLiteralValue(v)))
  1342. }
  1343. } else {
  1344. c.emitThrow(ex.val)
  1345. }
  1346. }
  1347. func (c *compiler) evalConst(expr compiledExpr) (Value, *Exception) {
  1348. if expr, ok := expr.(*compiledLiteral); ok {
  1349. return expr.val, nil
  1350. }
  1351. if c.evalVM == nil {
  1352. c.evalVM = New().vm
  1353. }
  1354. var savedPrg *Program
  1355. createdPrg := false
  1356. if c.evalVM.prg == nil {
  1357. c.evalVM.prg = &Program{}
  1358. savedPrg = c.p
  1359. c.p = c.evalVM.prg
  1360. createdPrg = true
  1361. }
  1362. savedPc := len(c.p.code)
  1363. expr.emitGetter(true)
  1364. c.emit(halt)
  1365. c.evalVM.pc = savedPc
  1366. ex := c.evalVM.runTry()
  1367. if createdPrg {
  1368. c.evalVM.prg = nil
  1369. c.evalVM.pc = 0
  1370. c.p = savedPrg
  1371. } else {
  1372. c.evalVM.prg.code = c.evalVM.prg.code[:savedPc]
  1373. c.p.code = c.evalVM.prg.code
  1374. }
  1375. if ex == nil {
  1376. return c.evalVM.pop(), nil
  1377. }
  1378. return nil, ex
  1379. }
  1380. func (e *compiledUnaryExpr) constant() bool {
  1381. return e.operand.constant()
  1382. }
  1383. func (e *compiledUnaryExpr) emitGetter(putOnStack bool) {
  1384. var prepare, body func()
  1385. toNumber := func() {
  1386. e.addSrcMap()
  1387. e.c.emit(toNumber)
  1388. }
  1389. switch e.operator {
  1390. case token.NOT:
  1391. e.operand.emitGetter(true)
  1392. e.c.emit(not)
  1393. goto end
  1394. case token.BITWISE_NOT:
  1395. e.operand.emitGetter(true)
  1396. e.c.emit(bnot)
  1397. goto end
  1398. case token.TYPEOF:
  1399. if o, ok := e.operand.(compiledExprOrRef); ok {
  1400. o.emitGetterOrRef()
  1401. } else {
  1402. e.operand.emitGetter(true)
  1403. }
  1404. e.c.emit(typeof)
  1405. goto end
  1406. case token.DELETE:
  1407. e.operand.deleteExpr().emitGetter(putOnStack)
  1408. return
  1409. case token.MINUS:
  1410. e.c.emitExpr(e.operand, true)
  1411. e.c.emit(neg)
  1412. goto end
  1413. case token.PLUS:
  1414. e.c.emitExpr(e.operand, true)
  1415. e.c.emit(plus)
  1416. goto end
  1417. case token.INCREMENT:
  1418. prepare = toNumber
  1419. body = func() {
  1420. e.c.emit(inc)
  1421. }
  1422. case token.DECREMENT:
  1423. prepare = toNumber
  1424. body = func() {
  1425. e.c.emit(dec)
  1426. }
  1427. case token.VOID:
  1428. e.c.emitExpr(e.operand, false)
  1429. if putOnStack {
  1430. e.c.emit(loadUndef)
  1431. }
  1432. return
  1433. default:
  1434. panic(fmt.Errorf("Unknown unary operator: %s", e.operator.String()))
  1435. }
  1436. e.operand.emitUnary(prepare, body, e.postfix, putOnStack)
  1437. return
  1438. end:
  1439. if !putOnStack {
  1440. e.c.emit(pop)
  1441. }
  1442. }
  1443. func (c *compiler) compileUnaryExpression(v *ast.UnaryExpression) compiledExpr {
  1444. r := &compiledUnaryExpr{
  1445. operand: c.compileExpression(v.Operand),
  1446. operator: v.Operator,
  1447. postfix: v.Postfix,
  1448. }
  1449. r.init(c, v.Idx0())
  1450. return r
  1451. }
  1452. func (e *compiledConditionalExpr) emitGetter(putOnStack bool) {
  1453. e.test.emitGetter(true)
  1454. j := len(e.c.p.code)
  1455. e.c.emit(nil)
  1456. e.consequent.emitGetter(putOnStack)
  1457. j1 := len(e.c.p.code)
  1458. e.c.emit(nil)
  1459. e.c.p.code[j] = jne(len(e.c.p.code) - j)
  1460. e.alternate.emitGetter(putOnStack)
  1461. e.c.p.code[j1] = jump(len(e.c.p.code) - j1)
  1462. }
  1463. func (c *compiler) compileConditionalExpression(v *ast.ConditionalExpression) compiledExpr {
  1464. r := &compiledConditionalExpr{
  1465. test: c.compileExpression(v.Test),
  1466. consequent: c.compileExpression(v.Consequent),
  1467. alternate: c.compileExpression(v.Alternate),
  1468. }
  1469. r.init(c, v.Idx0())
  1470. return r
  1471. }
  1472. func (e *compiledLogicalOr) constant() bool {
  1473. if e.left.constant() {
  1474. if v, ex := e.c.evalConst(e.left); ex == nil {
  1475. if v.ToBoolean() {
  1476. return true
  1477. }
  1478. return e.right.constant()
  1479. } else {
  1480. return true
  1481. }
  1482. }
  1483. return false
  1484. }
  1485. func (e *compiledLogicalOr) emitGetter(putOnStack bool) {
  1486. if e.left.constant() {
  1487. if v, ex := e.c.evalConst(e.left); ex == nil {
  1488. if !v.ToBoolean() {
  1489. e.c.emitExpr(e.right, putOnStack)
  1490. } else {
  1491. if putOnStack {
  1492. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  1493. }
  1494. }
  1495. } else {
  1496. e.c.emitThrow(ex.val)
  1497. }
  1498. return
  1499. }
  1500. e.c.emitExpr(e.left, true)
  1501. j := len(e.c.p.code)
  1502. e.addSrcMap()
  1503. e.c.emit(nil)
  1504. e.c.emitExpr(e.right, true)
  1505. e.c.p.code[j] = jeq1(len(e.c.p.code) - j)
  1506. if !putOnStack {
  1507. e.c.emit(pop)
  1508. }
  1509. }
  1510. func (e *compiledCoalesce) constant() bool {
  1511. if e.left.constant() {
  1512. if v, ex := e.c.evalConst(e.left); ex == nil {
  1513. if v != _null && v != _undefined {
  1514. return true
  1515. }
  1516. return e.right.constant()
  1517. } else {
  1518. return true
  1519. }
  1520. }
  1521. return false
  1522. }
  1523. func (e *compiledCoalesce) emitGetter(putOnStack bool) {
  1524. if e.left.constant() {
  1525. if v, ex := e.c.evalConst(e.left); ex == nil {
  1526. if v == _undefined || v == _null {
  1527. e.c.emitExpr(e.right, putOnStack)
  1528. } else {
  1529. if putOnStack {
  1530. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  1531. }
  1532. }
  1533. } else {
  1534. e.c.emitThrow(ex.val)
  1535. }
  1536. return
  1537. }
  1538. e.c.emitExpr(e.left, true)
  1539. j := len(e.c.p.code)
  1540. e.addSrcMap()
  1541. e.c.emit(nil)
  1542. e.c.emitExpr(e.right, true)
  1543. e.c.p.code[j] = jcoalesc(len(e.c.p.code) - j)
  1544. if !putOnStack {
  1545. e.c.emit(pop)
  1546. }
  1547. }
  1548. func (e *compiledLogicalAnd) constant() bool {
  1549. if e.left.constant() {
  1550. if v, ex := e.c.evalConst(e.left); ex == nil {
  1551. if !v.ToBoolean() {
  1552. return true
  1553. } else {
  1554. return e.right.constant()
  1555. }
  1556. } else {
  1557. return true
  1558. }
  1559. }
  1560. return false
  1561. }
  1562. func (e *compiledLogicalAnd) emitGetter(putOnStack bool) {
  1563. var j int
  1564. if e.left.constant() {
  1565. if v, ex := e.c.evalConst(e.left); ex == nil {
  1566. if !v.ToBoolean() {
  1567. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  1568. } else {
  1569. e.c.emitExpr(e.right, putOnStack)
  1570. }
  1571. } else {
  1572. e.c.emitThrow(ex.val)
  1573. }
  1574. return
  1575. }
  1576. e.left.emitGetter(true)
  1577. j = len(e.c.p.code)
  1578. e.addSrcMap()
  1579. e.c.emit(nil)
  1580. e.c.emitExpr(e.right, true)
  1581. e.c.p.code[j] = jneq1(len(e.c.p.code) - j)
  1582. if !putOnStack {
  1583. e.c.emit(pop)
  1584. }
  1585. }
  1586. func (e *compiledBinaryExpr) constant() bool {
  1587. return e.left.constant() && e.right.constant()
  1588. }
  1589. func (e *compiledBinaryExpr) emitGetter(putOnStack bool) {
  1590. e.c.emitExpr(e.left, true)
  1591. e.c.emitExpr(e.right, true)
  1592. e.addSrcMap()
  1593. switch e.operator {
  1594. case token.LESS:
  1595. e.c.emit(op_lt)
  1596. case token.GREATER:
  1597. e.c.emit(op_gt)
  1598. case token.LESS_OR_EQUAL:
  1599. e.c.emit(op_lte)
  1600. case token.GREATER_OR_EQUAL:
  1601. e.c.emit(op_gte)
  1602. case token.EQUAL:
  1603. e.c.emit(op_eq)
  1604. case token.NOT_EQUAL:
  1605. e.c.emit(op_neq)
  1606. case token.STRICT_EQUAL:
  1607. e.c.emit(op_strict_eq)
  1608. case token.STRICT_NOT_EQUAL:
  1609. e.c.emit(op_strict_neq)
  1610. case token.PLUS:
  1611. e.c.emit(add)
  1612. case token.MINUS:
  1613. e.c.emit(sub)
  1614. case token.MULTIPLY:
  1615. e.c.emit(mul)
  1616. case token.EXPONENT:
  1617. e.c.emit(exp)
  1618. case token.SLASH:
  1619. e.c.emit(div)
  1620. case token.REMAINDER:
  1621. e.c.emit(mod)
  1622. case token.AND:
  1623. e.c.emit(and)
  1624. case token.OR:
  1625. e.c.emit(or)
  1626. case token.EXCLUSIVE_OR:
  1627. e.c.emit(xor)
  1628. case token.INSTANCEOF:
  1629. e.c.emit(op_instanceof)
  1630. case token.IN:
  1631. e.c.emit(op_in)
  1632. case token.SHIFT_LEFT:
  1633. e.c.emit(sal)
  1634. case token.SHIFT_RIGHT:
  1635. e.c.emit(sar)
  1636. case token.UNSIGNED_SHIFT_RIGHT:
  1637. e.c.emit(shr)
  1638. default:
  1639. panic(fmt.Errorf("Unknown operator: %s", e.operator.String()))
  1640. }
  1641. if !putOnStack {
  1642. e.c.emit(pop)
  1643. }
  1644. }
  1645. func (c *compiler) compileBinaryExpression(v *ast.BinaryExpression) compiledExpr {
  1646. switch v.Operator {
  1647. case token.LOGICAL_OR:
  1648. return c.compileLogicalOr(v.Left, v.Right, v.Idx0())
  1649. case token.COALESCE:
  1650. return c.compileCoalesce(v.Left, v.Right, v.Idx0())
  1651. case token.LOGICAL_AND:
  1652. return c.compileLogicalAnd(v.Left, v.Right, v.Idx0())
  1653. }
  1654. r := &compiledBinaryExpr{
  1655. left: c.compileExpression(v.Left),
  1656. right: c.compileExpression(v.Right),
  1657. operator: v.Operator,
  1658. }
  1659. r.init(c, v.Idx0())
  1660. return r
  1661. }
  1662. func (c *compiler) compileLogicalOr(left, right ast.Expression, idx file.Idx) compiledExpr {
  1663. r := &compiledLogicalOr{
  1664. left: c.compileExpression(left),
  1665. right: c.compileExpression(right),
  1666. }
  1667. r.init(c, idx)
  1668. return r
  1669. }
  1670. func (c *compiler) compileCoalesce(left, right ast.Expression, idx file.Idx) compiledExpr {
  1671. r := &compiledCoalesce{
  1672. left: c.compileExpression(left),
  1673. right: c.compileExpression(right),
  1674. }
  1675. r.init(c, idx)
  1676. return r
  1677. }
  1678. func (c *compiler) compileLogicalAnd(left, right ast.Expression, idx file.Idx) compiledExpr {
  1679. r := &compiledLogicalAnd{
  1680. left: c.compileExpression(left),
  1681. right: c.compileExpression(right),
  1682. }
  1683. r.init(c, idx)
  1684. return r
  1685. }
  1686. func (e *compiledObjectLiteral) emitGetter(putOnStack bool) {
  1687. e.addSrcMap()
  1688. e.c.emit(newObject)
  1689. hasProto := false
  1690. for _, prop := range e.expr.Value {
  1691. switch prop := prop.(type) {
  1692. case *ast.PropertyKeyed:
  1693. keyExpr := e.c.compileExpression(prop.Key)
  1694. computed := false
  1695. var key unistring.String
  1696. switch keyExpr := keyExpr.(type) {
  1697. case *compiledLiteral:
  1698. key = keyExpr.val.string()
  1699. default:
  1700. keyExpr.emitGetter(true)
  1701. computed = true
  1702. }
  1703. valueExpr := e.c.compileExpression(prop.Value)
  1704. var anonFn *compiledFunctionLiteral
  1705. if fn, ok := valueExpr.(*compiledFunctionLiteral); ok {
  1706. if fn.name == nil {
  1707. anonFn = fn
  1708. }
  1709. switch prop.Kind {
  1710. case ast.PropertyKindMethod, ast.PropertyKindGet, ast.PropertyKindSet:
  1711. fn.isMethod = true
  1712. }
  1713. }
  1714. if computed {
  1715. e.c.emit(_toPropertyKey{})
  1716. e.c.emitExpr(valueExpr, true)
  1717. switch prop.Kind {
  1718. case ast.PropertyKindValue, ast.PropertyKindMethod:
  1719. if anonFn != nil {
  1720. e.c.emit(setElem1Named)
  1721. } else {
  1722. e.c.emit(setElem1)
  1723. }
  1724. case ast.PropertyKindGet:
  1725. e.c.emit(setPropGetter1)
  1726. case ast.PropertyKindSet:
  1727. e.c.emit(setPropSetter1)
  1728. default:
  1729. panic(fmt.Errorf("unknown property kind: %s", prop.Kind))
  1730. }
  1731. } else {
  1732. isProto := key == __proto__ && !prop.Computed
  1733. if isProto {
  1734. if hasProto {
  1735. e.c.throwSyntaxError(int(prop.Idx0())-1, "Duplicate __proto__ fields are not allowed in object literals")
  1736. } else {
  1737. hasProto = true
  1738. }
  1739. }
  1740. if anonFn != nil && !isProto {
  1741. anonFn.lhsName = key
  1742. }
  1743. e.c.emitExpr(valueExpr, true)
  1744. switch prop.Kind {
  1745. case ast.PropertyKindValue:
  1746. if isProto {
  1747. e.c.emit(setProto)
  1748. } else {
  1749. e.c.emit(setProp1(key))
  1750. }
  1751. case ast.PropertyKindMethod:
  1752. e.c.emit(setProp1(key))
  1753. case ast.PropertyKindGet:
  1754. e.c.emit(setPropGetter(key))
  1755. case ast.PropertyKindSet:
  1756. e.c.emit(setPropSetter(key))
  1757. default:
  1758. panic(fmt.Errorf("unknown property kind: %s", prop.Kind))
  1759. }
  1760. }
  1761. case *ast.PropertyShort:
  1762. key := prop.Name.Name
  1763. if prop.Initializer != nil {
  1764. e.c.throwSyntaxError(int(prop.Initializer.Idx0())-1, "Invalid shorthand property initializer")
  1765. }
  1766. if e.c.scope.strict && key == "let" {
  1767. e.c.throwSyntaxError(e.offset, "'let' cannot be used as a shorthand property in strict mode")
  1768. }
  1769. e.c.compileIdentifierExpression(&prop.Name).emitGetter(true)
  1770. e.c.emit(setProp1(key))
  1771. case *ast.SpreadElement:
  1772. e.c.compileExpression(prop.Expression).emitGetter(true)
  1773. e.c.emit(copySpread)
  1774. default:
  1775. panic(fmt.Errorf("unknown Property type: %T", prop))
  1776. }
  1777. }
  1778. if !putOnStack {
  1779. e.c.emit(pop)
  1780. }
  1781. }
  1782. func (c *compiler) compileObjectLiteral(v *ast.ObjectLiteral) compiledExpr {
  1783. r := &compiledObjectLiteral{
  1784. expr: v,
  1785. }
  1786. r.init(c, v.Idx0())
  1787. return r
  1788. }
  1789. func (e *compiledArrayLiteral) emitGetter(putOnStack bool) {
  1790. e.addSrcMap()
  1791. hasSpread := false
  1792. mark := len(e.c.p.code)
  1793. e.c.emit(nil)
  1794. for _, v := range e.expr.Value {
  1795. if spread, ok := v.(*ast.SpreadElement); ok {
  1796. hasSpread = true
  1797. e.c.compileExpression(spread.Expression).emitGetter(true)
  1798. e.c.emit(pushArraySpread)
  1799. } else {
  1800. if v != nil {
  1801. e.c.emitExpr(e.c.compileExpression(v), true)
  1802. } else {
  1803. e.c.emit(loadNil)
  1804. }
  1805. e.c.emit(pushArrayItem)
  1806. }
  1807. }
  1808. var objCount uint32
  1809. if !hasSpread {
  1810. objCount = uint32(len(e.expr.Value))
  1811. }
  1812. e.c.p.code[mark] = newArray(objCount)
  1813. if !putOnStack {
  1814. e.c.emit(pop)
  1815. }
  1816. }
  1817. func (c *compiler) compileArrayLiteral(v *ast.ArrayLiteral) compiledExpr {
  1818. r := &compiledArrayLiteral{
  1819. expr: v,
  1820. }
  1821. r.init(c, v.Idx0())
  1822. return r
  1823. }
  1824. func (e *compiledRegexpLiteral) emitGetter(putOnStack bool) {
  1825. if putOnStack {
  1826. pattern, err := compileRegexp(e.expr.Pattern, e.expr.Flags)
  1827. if err != nil {
  1828. e.c.throwSyntaxError(e.offset, err.Error())
  1829. }
  1830. e.c.emit(&newRegexp{pattern: pattern, src: newStringValue(e.expr.Pattern)})
  1831. }
  1832. }
  1833. func (c *compiler) compileRegexpLiteral(v *ast.RegExpLiteral) compiledExpr {
  1834. r := &compiledRegexpLiteral{
  1835. expr: v,
  1836. }
  1837. r.init(c, v.Idx0())
  1838. return r
  1839. }
  1840. func (c *compiler) emitCallee(callee compiledExpr) (calleeName unistring.String) {
  1841. switch callee := callee.(type) {
  1842. case *compiledDotExpr:
  1843. callee.left.emitGetter(true)
  1844. c.emit(dup)
  1845. c.emit(getPropCallee(callee.name))
  1846. case *compiledBracketExpr:
  1847. callee.left.emitGetter(true)
  1848. c.emit(dup)
  1849. callee.member.emitGetter(true)
  1850. c.emit(getElemCallee)
  1851. case *compiledIdentifierExpr:
  1852. calleeName = callee.name
  1853. callee.emitGetterAndCallee()
  1854. case *compiledOptionalChain:
  1855. c.startOptChain()
  1856. c.emitCallee(callee.expr)
  1857. c.endOptChain()
  1858. case *compiledOptional:
  1859. c.emitCallee(callee.expr)
  1860. c.block.conts = append(c.block.conts, len(c.p.code))
  1861. c.emit(nil)
  1862. default:
  1863. c.emit(loadUndef)
  1864. callee.emitGetter(true)
  1865. }
  1866. return
  1867. }
  1868. func (e *compiledCallExpr) emitGetter(putOnStack bool) {
  1869. if e.isVariadic {
  1870. e.c.emit(startVariadic)
  1871. }
  1872. calleeName := e.c.emitCallee(e.callee)
  1873. for _, expr := range e.args {
  1874. expr.emitGetter(true)
  1875. }
  1876. e.addSrcMap()
  1877. if calleeName == "eval" {
  1878. foundFunc, foundVar := false, false
  1879. for sc := e.c.scope; sc != nil; sc = sc.outer {
  1880. if !foundFunc && sc.function && !sc.arrow {
  1881. foundFunc = true
  1882. sc.thisNeeded, sc.argsNeeded = true, true
  1883. }
  1884. if !foundVar && (sc.variable || sc.function) {
  1885. foundVar = true
  1886. if !sc.strict {
  1887. sc.dynamic = true
  1888. }
  1889. }
  1890. sc.dynLookup = true
  1891. }
  1892. if e.c.scope.strict {
  1893. if e.isVariadic {
  1894. e.c.emit(callEvalVariadicStrict)
  1895. } else {
  1896. e.c.emit(callEvalStrict(len(e.args)))
  1897. }
  1898. } else {
  1899. if e.isVariadic {
  1900. e.c.emit(callEvalVariadic)
  1901. } else {
  1902. e.c.emit(callEval(len(e.args)))
  1903. }
  1904. }
  1905. } else {
  1906. if e.isVariadic {
  1907. e.c.emit(callVariadic)
  1908. } else {
  1909. e.c.emit(call(len(e.args)))
  1910. }
  1911. }
  1912. if e.isVariadic {
  1913. e.c.emit(endVariadic)
  1914. }
  1915. if !putOnStack {
  1916. e.c.emit(pop)
  1917. }
  1918. }
  1919. func (e *compiledCallExpr) deleteExpr() compiledExpr {
  1920. r := &defaultDeleteExpr{
  1921. expr: e,
  1922. }
  1923. r.init(e.c, file.Idx(e.offset+1))
  1924. return r
  1925. }
  1926. func (c *compiler) compileSpreadCallArgument(spread *ast.SpreadElement) compiledExpr {
  1927. r := &compiledSpreadCallArgument{
  1928. expr: c.compileExpression(spread.Expression),
  1929. }
  1930. r.init(c, spread.Idx0())
  1931. return r
  1932. }
  1933. func (c *compiler) compileCallExpression(v *ast.CallExpression) compiledExpr {
  1934. args := make([]compiledExpr, len(v.ArgumentList))
  1935. isVariadic := false
  1936. for i, argExpr := range v.ArgumentList {
  1937. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  1938. args[i] = c.compileSpreadCallArgument(spread)
  1939. isVariadic = true
  1940. } else {
  1941. args[i] = c.compileExpression(argExpr)
  1942. }
  1943. }
  1944. r := &compiledCallExpr{
  1945. args: args,
  1946. callee: c.compileExpression(v.Callee),
  1947. isVariadic: isVariadic,
  1948. }
  1949. r.init(c, v.LeftParenthesis)
  1950. return r
  1951. }
  1952. func (c *compiler) compileIdentifierExpression(v *ast.Identifier) compiledExpr {
  1953. if c.scope.strict {
  1954. c.checkIdentifierName(v.Name, int(v.Idx)-1)
  1955. }
  1956. r := &compiledIdentifierExpr{
  1957. name: v.Name,
  1958. }
  1959. r.offset = int(v.Idx) - 1
  1960. r.init(c, v.Idx0())
  1961. return r
  1962. }
  1963. func (c *compiler) compileNumberLiteral(v *ast.NumberLiteral) compiledExpr {
  1964. if c.scope.strict && len(v.Literal) > 1 && v.Literal[0] == '0' && v.Literal[1] <= '7' && v.Literal[1] >= '0' {
  1965. c.throwSyntaxError(int(v.Idx)-1, "Octal literals are not allowed in strict mode")
  1966. panic("Unreachable")
  1967. }
  1968. var val Value
  1969. switch num := v.Value.(type) {
  1970. case int64:
  1971. val = intToValue(num)
  1972. case float64:
  1973. val = floatToValue(num)
  1974. default:
  1975. panic(fmt.Errorf("Unsupported number literal type: %T", v.Value))
  1976. }
  1977. r := &compiledLiteral{
  1978. val: val,
  1979. }
  1980. r.init(c, v.Idx0())
  1981. return r
  1982. }
  1983. func (c *compiler) compileStringLiteral(v *ast.StringLiteral) compiledExpr {
  1984. r := &compiledLiteral{
  1985. val: stringValueFromRaw(v.Value),
  1986. }
  1987. r.init(c, v.Idx0())
  1988. return r
  1989. }
  1990. func (c *compiler) compileTemplateLiteral(v *ast.TemplateLiteral) compiledExpr {
  1991. r := &compiledTemplateLiteral{}
  1992. if v.Tag != nil {
  1993. r.tag = c.compileExpression(v.Tag)
  1994. }
  1995. ce := make([]compiledExpr, len(v.Expressions))
  1996. for i, expr := range v.Expressions {
  1997. ce[i] = c.compileExpression(expr)
  1998. }
  1999. r.expressions = ce
  2000. r.elements = v.Elements
  2001. r.init(c, v.Idx0())
  2002. return r
  2003. }
  2004. func (c *compiler) compileBooleanLiteral(v *ast.BooleanLiteral) compiledExpr {
  2005. var val Value
  2006. if v.Value {
  2007. val = valueTrue
  2008. } else {
  2009. val = valueFalse
  2010. }
  2011. r := &compiledLiteral{
  2012. val: val,
  2013. }
  2014. r.init(c, v.Idx0())
  2015. return r
  2016. }
  2017. func (c *compiler) compileAssignExpression(v *ast.AssignExpression) compiledExpr {
  2018. // log.Printf("compileAssignExpression(): %+v", v)
  2019. r := &compiledAssignExpr{
  2020. left: c.compileExpression(v.Left),
  2021. right: c.compileExpression(v.Right),
  2022. operator: v.Operator,
  2023. }
  2024. r.init(c, v.Idx0())
  2025. return r
  2026. }
  2027. func (e *compiledEnumGetExpr) emitGetter(putOnStack bool) {
  2028. e.c.emit(enumGet)
  2029. if !putOnStack {
  2030. e.c.emit(pop)
  2031. }
  2032. }
  2033. func (c *compiler) compileObjectAssignmentPattern(v *ast.ObjectPattern) compiledExpr {
  2034. r := &compiledObjectAssignmentPattern{
  2035. expr: v,
  2036. }
  2037. r.init(c, v.Idx0())
  2038. return r
  2039. }
  2040. func (e *compiledObjectAssignmentPattern) emitGetter(putOnStack bool) {
  2041. if putOnStack {
  2042. e.c.emit(loadUndef)
  2043. }
  2044. }
  2045. func (c *compiler) compileArrayAssignmentPattern(v *ast.ArrayPattern) compiledExpr {
  2046. r := &compiledArrayAssignmentPattern{
  2047. expr: v,
  2048. }
  2049. r.init(c, v.Idx0())
  2050. return r
  2051. }
  2052. func (e *compiledArrayAssignmentPattern) emitGetter(putOnStack bool) {
  2053. if putOnStack {
  2054. e.c.emit(loadUndef)
  2055. }
  2056. }
  2057. func (c *compiler) emitExpr(expr compiledExpr, putOnStack bool) {
  2058. if expr.constant() {
  2059. c.emitConst(expr, putOnStack)
  2060. } else {
  2061. expr.emitGetter(putOnStack)
  2062. }
  2063. }
  2064. func (c *compiler) emitNamed(expr compiledExpr, name unistring.String) {
  2065. if en, ok := expr.(interface {
  2066. emitNamed(name unistring.String)
  2067. }); ok {
  2068. en.emitNamed(name)
  2069. } else {
  2070. expr.emitGetter(true)
  2071. }
  2072. }
  2073. func (c *compiler) emitNamedOrConst(expr compiledExpr, name unistring.String) {
  2074. if expr.constant() {
  2075. c.emitConst(expr, true)
  2076. } else {
  2077. c.emitNamed(expr, name)
  2078. }
  2079. }
  2080. func (e *compiledFunctionLiteral) emitNamed(name unistring.String) {
  2081. e.lhsName = name
  2082. e.emitGetter(true)
  2083. }
  2084. func (c *compiler) emitPattern(pattern ast.Pattern, emitter func(target, init compiledExpr), putOnStack bool) {
  2085. switch pattern := pattern.(type) {
  2086. case *ast.ObjectPattern:
  2087. c.emitObjectPattern(pattern, emitter, putOnStack)
  2088. case *ast.ArrayPattern:
  2089. c.emitArrayPattern(pattern, emitter, putOnStack)
  2090. default:
  2091. panic(fmt.Errorf("unsupported Pattern: %T", pattern))
  2092. }
  2093. }
  2094. func (c *compiler) emitAssign(target ast.Expression, init compiledExpr, emitAssignSimple func(target, init compiledExpr)) {
  2095. pattern, isPattern := target.(ast.Pattern)
  2096. if isPattern {
  2097. init.emitGetter(true)
  2098. c.emitPattern(pattern, emitAssignSimple, false)
  2099. } else {
  2100. emitAssignSimple(c.compileExpression(target), init)
  2101. }
  2102. }
  2103. func (c *compiler) emitObjectPattern(pattern *ast.ObjectPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  2104. if pattern.Rest != nil {
  2105. c.emit(createDestructSrc)
  2106. } else {
  2107. c.emit(checkObjectCoercible)
  2108. }
  2109. for _, prop := range pattern.Properties {
  2110. switch prop := prop.(type) {
  2111. case *ast.PropertyShort:
  2112. c.emit(dup)
  2113. emitAssign(c.compileIdentifierExpression(&prop.Name), c.compilePatternInitExpr(func() {
  2114. c.emit(getProp(prop.Name.Name))
  2115. }, prop.Initializer, prop.Idx0()))
  2116. case *ast.PropertyKeyed:
  2117. c.emit(dup)
  2118. c.compileExpression(prop.Key).emitGetter(true)
  2119. c.emit(_toPropertyKey{})
  2120. var target ast.Expression
  2121. var initializer ast.Expression
  2122. if e, ok := prop.Value.(*ast.AssignExpression); ok {
  2123. target = e.Left
  2124. initializer = e.Right
  2125. } else {
  2126. target = prop.Value
  2127. }
  2128. c.emitAssign(target, c.compilePatternInitExpr(func() {
  2129. c.emit(getKey)
  2130. }, initializer, prop.Idx0()), emitAssign)
  2131. default:
  2132. c.throwSyntaxError(int(prop.Idx0()-1), "Unsupported AssignmentProperty type: %T", prop)
  2133. }
  2134. }
  2135. if pattern.Rest != nil {
  2136. emitAssign(c.compileExpression(pattern.Rest), c.compileEmitterExpr(func() {
  2137. c.emit(copyRest)
  2138. }, pattern.Rest.Idx0()))
  2139. c.emit(pop)
  2140. }
  2141. if !putOnStack {
  2142. c.emit(pop)
  2143. }
  2144. }
  2145. func (c *compiler) emitArrayPattern(pattern *ast.ArrayPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  2146. c.emit(iterate)
  2147. for _, elt := range pattern.Elements {
  2148. switch elt := elt.(type) {
  2149. case nil:
  2150. c.emit(iterGetNextOrUndef{}, pop)
  2151. case *ast.AssignExpression:
  2152. c.emitAssign(elt.Left, c.compilePatternInitExpr(func() {
  2153. c.emit(iterGetNextOrUndef{})
  2154. }, elt.Right, elt.Idx0()), emitAssign)
  2155. default:
  2156. c.emitAssign(elt, c.compileEmitterExpr(func() {
  2157. c.emit(iterGetNextOrUndef{})
  2158. }, elt.Idx0()), emitAssign)
  2159. }
  2160. }
  2161. if pattern.Rest != nil {
  2162. c.emitAssign(pattern.Rest, c.compileEmitterExpr(func() {
  2163. c.emit(newArrayFromIter)
  2164. }, pattern.Rest.Idx0()), emitAssign)
  2165. } else {
  2166. c.emit(enumPopClose)
  2167. }
  2168. if !putOnStack {
  2169. c.emit(pop)
  2170. }
  2171. }
  2172. func (e *compiledObjectAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  2173. valueExpr.emitGetter(true)
  2174. e.c.emitObjectPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  2175. }
  2176. func (e *compiledArrayAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  2177. valueExpr.emitGetter(true)
  2178. e.c.emitArrayPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  2179. }
  2180. type compiledPatternInitExpr struct {
  2181. baseCompiledExpr
  2182. emitSrc func()
  2183. def compiledExpr
  2184. }
  2185. func (e *compiledPatternInitExpr) emitGetter(putOnStack bool) {
  2186. if !putOnStack {
  2187. return
  2188. }
  2189. e.emitSrc()
  2190. if e.def != nil {
  2191. mark := len(e.c.p.code)
  2192. e.c.emit(nil)
  2193. e.c.emitExpr(e.def, true)
  2194. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  2195. }
  2196. }
  2197. func (e *compiledPatternInitExpr) emitNamed(name unistring.String) {
  2198. e.emitSrc()
  2199. if e.def != nil {
  2200. mark := len(e.c.p.code)
  2201. e.c.emit(nil)
  2202. e.c.emitNamedOrConst(e.def, name)
  2203. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  2204. }
  2205. }
  2206. func (c *compiler) compilePatternInitExpr(emitSrc func(), def ast.Expression, idx file.Idx) compiledExpr {
  2207. r := &compiledPatternInitExpr{
  2208. emitSrc: emitSrc,
  2209. def: c.compileExpression(def),
  2210. }
  2211. r.init(c, idx)
  2212. return r
  2213. }
  2214. type compiledEmitterExpr struct {
  2215. baseCompiledExpr
  2216. emitter func()
  2217. namedEmitter func(name unistring.String)
  2218. }
  2219. func (e *compiledEmitterExpr) emitGetter(putOnStack bool) {
  2220. if e.emitter != nil {
  2221. e.emitter()
  2222. } else {
  2223. e.namedEmitter("")
  2224. }
  2225. if !putOnStack {
  2226. e.c.emit(pop)
  2227. }
  2228. }
  2229. func (e *compiledEmitterExpr) emitNamed(name unistring.String) {
  2230. if e.namedEmitter != nil {
  2231. e.namedEmitter(name)
  2232. } else {
  2233. e.emitter()
  2234. }
  2235. }
  2236. func (c *compiler) compileEmitterExpr(emitter func(), idx file.Idx) *compiledEmitterExpr {
  2237. r := &compiledEmitterExpr{
  2238. emitter: emitter,
  2239. }
  2240. r.init(c, idx)
  2241. return r
  2242. }
  2243. func (e *compiledSpreadCallArgument) emitGetter(putOnStack bool) {
  2244. e.expr.emitGetter(putOnStack)
  2245. if putOnStack {
  2246. e.c.emit(pushSpread)
  2247. }
  2248. }
  2249. func (c *compiler) startOptChain() {
  2250. c.block = &block{
  2251. typ: blockOptChain,
  2252. outer: c.block,
  2253. }
  2254. }
  2255. func (c *compiler) endOptChain() {
  2256. lbl := len(c.p.code)
  2257. for _, item := range c.block.breaks {
  2258. c.p.code[item] = jopt(lbl - item)
  2259. }
  2260. for _, item := range c.block.conts {
  2261. c.p.code[item] = joptc(lbl - item)
  2262. }
  2263. c.block = c.block.outer
  2264. }
  2265. func (e *compiledOptionalChain) emitGetter(putOnStack bool) {
  2266. e.c.startOptChain()
  2267. e.expr.emitGetter(true)
  2268. e.c.endOptChain()
  2269. if !putOnStack {
  2270. e.c.emit(pop)
  2271. }
  2272. }
  2273. func (e *compiledOptional) emitGetter(putOnStack bool) {
  2274. e.expr.emitGetter(putOnStack)
  2275. if putOnStack {
  2276. e.c.block.breaks = append(e.c.block.breaks, len(e.c.p.code))
  2277. e.c.emit(nil)
  2278. }
  2279. }