compiler_expr.go 49 KB

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