compiler_expr.go 52 KB

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