compiler_expr.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  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. case ast.Pattern:
  808. b := e.c.scope.addBinding(int(item.Idx0()) - 1)
  809. b.isArg = true
  810. hasPatterns = true
  811. default:
  812. e.c.throwSyntaxError(int(item.Idx0())-1, "Unsupported BindingElement type: %T", item)
  813. return
  814. }
  815. if item.Initializer != nil {
  816. hasInits = true
  817. }
  818. if hasPatterns || hasInits {
  819. if firstDupIdx >= 0 {
  820. e.c.throwSyntaxError(firstDupIdx, "Duplicate parameter name not allowed in this context")
  821. return
  822. }
  823. if e.strict != nil {
  824. e.c.throwSyntaxError(int(e.strict.Idx)-1, "Illegal 'use strict' directive in function with non-simple parameter list")
  825. return
  826. }
  827. }
  828. if !hasInits {
  829. length++
  830. }
  831. }
  832. // create pattern bindings
  833. if hasPatterns {
  834. for _, item := range e.expr.ParameterList.List {
  835. switch tgt := item.Target.(type) {
  836. case *ast.Identifier:
  837. // we already created those in the previous loop, skipping
  838. default:
  839. e.c.compileParameterPatternBinding(tgt)
  840. }
  841. }
  842. if rest := e.expr.ParameterList.Rest; rest != nil {
  843. e.c.compileParameterPatternBinding(rest)
  844. }
  845. }
  846. paramsCount := len(e.expr.ParameterList.List)
  847. e.c.scope.numArgs = paramsCount
  848. body := e.expr.Body.List
  849. funcs := e.c.extractFunctions(body)
  850. s := e.c.scope
  851. var calleeBinding *binding
  852. preambleLen := 4 // enter, boxThis, createArgs, set
  853. e.c.p.code = make([]instruction, preambleLen, 8)
  854. emitArgsRestMark := -1
  855. firstForwardRef := -1
  856. enterFunc2Mark := -1
  857. if hasPatterns || hasInits {
  858. if e.isExpr && e.expr.Name != nil {
  859. if b, created := s.bindNameLexical(e.expr.Name.Name, false, 0); created {
  860. b.isConst = true
  861. calleeBinding = b
  862. }
  863. }
  864. if calleeBinding != nil {
  865. e.c.emit(loadCallee)
  866. calleeBinding.emitInit()
  867. }
  868. for i, item := range e.expr.ParameterList.List {
  869. if pattern, ok := item.Target.(ast.Pattern); ok {
  870. i := i
  871. e.c.compilePatternInitExpr(func() {
  872. if firstForwardRef == -1 {
  873. s.bindings[i].emitGet()
  874. } else {
  875. e.c.emit(loadStackLex(-i - 1))
  876. }
  877. }, item.Initializer, item.Target.Idx0()).emitGetter(true)
  878. e.c.emitPattern(pattern, func(target, init compiledExpr) {
  879. e.c.emitPatternLexicalAssign(target, init, false)
  880. }, false)
  881. } else if item.Initializer != nil {
  882. markGet := len(e.c.p.code)
  883. e.c.emit(nil)
  884. mark := len(e.c.p.code)
  885. e.c.emit(nil)
  886. e.c.compileExpression(item.Initializer).emitGetter(true)
  887. if firstForwardRef == -1 && (s.isDynamic() || s.bindings[i].useCount() > 0) {
  888. firstForwardRef = i
  889. }
  890. if firstForwardRef == -1 {
  891. s.bindings[i].emitGetAt(markGet)
  892. } else {
  893. e.c.p.code[markGet] = loadStackLex(-i - 1)
  894. }
  895. s.bindings[i].emitInit()
  896. e.c.p.code[mark] = jdefP(len(e.c.p.code) - mark)
  897. } else {
  898. if firstForwardRef == -1 && s.bindings[i].useCount() > 0 {
  899. firstForwardRef = i
  900. }
  901. if firstForwardRef != -1 {
  902. e.c.emit(loadStackLex(-i - 1))
  903. s.bindings[i].emitInit()
  904. }
  905. }
  906. }
  907. if rest := e.expr.ParameterList.Rest; rest != nil {
  908. e.c.emitAssign(rest, e.c.compileEmitterExpr(
  909. func() {
  910. emitArgsRestMark = len(e.c.p.code)
  911. e.c.emit(createArgsRestStack(paramsCount))
  912. }, rest.Idx0()),
  913. func(target, init compiledExpr) {
  914. e.c.emitPatternLexicalAssign(target, init, false)
  915. })
  916. }
  917. if firstForwardRef != -1 {
  918. for _, b := range s.bindings {
  919. b.inStash = true
  920. }
  921. s.argsInStash = true
  922. s.needStash = true
  923. }
  924. e.c.newBlockScope()
  925. varScope := e.c.scope
  926. varScope.variable = true
  927. enterFunc2Mark = len(e.c.p.code)
  928. e.c.emit(nil)
  929. e.c.compileDeclList(e.expr.DeclarationList, true)
  930. e.c.createFunctionBindings(funcs)
  931. e.c.compileLexicalDeclarationsFuncBody(body, calleeBinding)
  932. for _, b := range varScope.bindings {
  933. if b.isVar {
  934. if parentBinding := s.boundNames[b.name]; parentBinding != nil && parentBinding != calleeBinding {
  935. parentBinding.emitGet()
  936. b.emitSetP()
  937. }
  938. }
  939. }
  940. } else {
  941. // To avoid triggering variable conflict when binding from non-strict direct eval().
  942. // Parameters are supposed to be in a parent scope, hence no conflict.
  943. for _, b := range s.bindings[:paramsCount] {
  944. b.isVar = true
  945. }
  946. e.c.compileDeclList(e.expr.DeclarationList, true)
  947. e.c.createFunctionBindings(funcs)
  948. e.c.compileLexicalDeclarations(body, true)
  949. if e.isExpr && e.expr.Name != nil {
  950. if b, created := s.bindNameLexical(e.expr.Name.Name, false, 0); created {
  951. b.isConst = true
  952. calleeBinding = b
  953. }
  954. }
  955. if calleeBinding != nil {
  956. e.c.emit(loadCallee)
  957. calleeBinding.emitInit()
  958. }
  959. }
  960. e.c.compileFunctions(funcs)
  961. e.c.compileStatements(body, false)
  962. var last ast.Statement
  963. if l := len(body); l > 0 {
  964. last = body[l-1]
  965. }
  966. if _, ok := last.(*ast.ReturnStatement); !ok {
  967. e.c.emit(loadUndef, ret)
  968. }
  969. delta := 0
  970. code := e.c.p.code
  971. if calleeBinding != nil && !s.isDynamic() && calleeBinding.useCount() == 1 {
  972. s.deleteBinding(calleeBinding)
  973. preambleLen += 2
  974. }
  975. if !s.argsInStash && (s.argsNeeded || s.isDynamic()) {
  976. s.moveArgsToStash()
  977. }
  978. if s.argsNeeded {
  979. b, created := s.bindNameLexical("arguments", false, 0)
  980. if !created && !b.isVar {
  981. s.argsNeeded = false
  982. } else {
  983. if s.strict {
  984. b.isConst = true
  985. } else {
  986. b.isVar = true
  987. }
  988. pos := preambleLen - 2
  989. delta += 2
  990. if s.strict || hasPatterns || hasInits {
  991. code[pos] = createArgsUnmapped(paramsCount)
  992. } else {
  993. code[pos] = createArgsMapped(paramsCount)
  994. }
  995. pos++
  996. b.markAccessPointAtScope(s, pos)
  997. code[pos] = storeStashP(0)
  998. }
  999. }
  1000. stashSize, stackSize := s.finaliseVarAlloc(0)
  1001. if !s.strict && s.thisNeeded {
  1002. delta++
  1003. code[preambleLen-delta] = boxThis
  1004. }
  1005. delta++
  1006. delta = preambleLen - delta
  1007. var enter instruction
  1008. if stashSize > 0 || s.argsInStash {
  1009. if firstForwardRef == -1 {
  1010. enter1 := enterFunc{
  1011. numArgs: uint32(paramsCount),
  1012. argsToStash: s.argsInStash,
  1013. stashSize: uint32(stashSize),
  1014. stackSize: uint32(stackSize),
  1015. extensible: s.dynamic,
  1016. }
  1017. if s.isDynamic() {
  1018. enter1.names = s.makeNamesMap()
  1019. }
  1020. enter = &enter1
  1021. if enterFunc2Mark != -1 {
  1022. ef2 := &enterFuncBody{
  1023. extensible: e.c.scope.dynamic,
  1024. }
  1025. e.c.updateEnterBlock(&ef2.enterBlock)
  1026. e.c.p.code[enterFunc2Mark] = ef2
  1027. }
  1028. } else {
  1029. enter1 := enterFunc1{
  1030. stashSize: uint32(stashSize),
  1031. numArgs: uint32(paramsCount),
  1032. argsToCopy: uint32(firstForwardRef),
  1033. extensible: s.dynamic,
  1034. }
  1035. if s.isDynamic() {
  1036. enter1.names = s.makeNamesMap()
  1037. }
  1038. enter = &enter1
  1039. if enterFunc2Mark != -1 {
  1040. ef2 := &enterFuncBody{
  1041. adjustStack: true,
  1042. extensible: e.c.scope.dynamic,
  1043. }
  1044. e.c.updateEnterBlock(&ef2.enterBlock)
  1045. e.c.p.code[enterFunc2Mark] = ef2
  1046. }
  1047. }
  1048. if emitArgsRestMark != -1 {
  1049. e.c.p.code[emitArgsRestMark] = createArgsRestStash
  1050. }
  1051. } else {
  1052. enter = &enterFuncStashless{
  1053. stackSize: uint32(stackSize),
  1054. args: uint32(paramsCount),
  1055. }
  1056. if enterFunc2Mark != -1 {
  1057. ef2 := &enterFuncBody{
  1058. extensible: e.c.scope.dynamic,
  1059. }
  1060. e.c.updateEnterBlock(&ef2.enterBlock)
  1061. e.c.p.code[enterFunc2Mark] = ef2
  1062. }
  1063. }
  1064. code[delta] = enter
  1065. if delta != 0 {
  1066. e.c.p.code = code[delta:]
  1067. for i := range e.c.p.srcMap {
  1068. e.c.p.srcMap[i].pc -= delta
  1069. }
  1070. s.adjustBase(-delta)
  1071. }
  1072. strict := s.strict
  1073. p := e.c.p
  1074. // e.c.p.dumpCode()
  1075. if enterFunc2Mark != -1 {
  1076. e.c.popScope()
  1077. }
  1078. e.c.popScope()
  1079. e.c.p = savedPrg
  1080. 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})
  1081. if !putOnStack {
  1082. e.c.emit(pop)
  1083. }
  1084. }
  1085. func (c *compiler) compileFunctionLiteral(v *ast.FunctionLiteral, isExpr bool) *compiledFunctionLiteral {
  1086. strictBody := c.isStrictStatement(v.Body)
  1087. if v.Name != nil && (c.scope.strict || strictBody != nil) {
  1088. c.checkIdentifierLName(v.Name.Name, int(v.Name.Idx)-1)
  1089. }
  1090. r := &compiledFunctionLiteral{
  1091. expr: v,
  1092. isExpr: isExpr,
  1093. strict: strictBody,
  1094. }
  1095. r.init(c, v.Idx0())
  1096. return r
  1097. }
  1098. func (e *compiledThisExpr) emitGetter(putOnStack bool) {
  1099. if putOnStack {
  1100. e.addSrcMap()
  1101. scope := e.c.scope
  1102. for ; scope != nil && !scope.function && !scope.eval; scope = scope.outer {
  1103. }
  1104. if scope != nil {
  1105. scope.thisNeeded = true
  1106. e.c.emit(loadStack(0))
  1107. } else {
  1108. e.c.emit(loadGlobalObject)
  1109. }
  1110. }
  1111. }
  1112. func (e *compiledNewExpr) emitGetter(putOnStack bool) {
  1113. if e.isVariadic {
  1114. e.c.emit(startVariadic)
  1115. }
  1116. e.callee.emitGetter(true)
  1117. for _, expr := range e.args {
  1118. expr.emitGetter(true)
  1119. }
  1120. e.addSrcMap()
  1121. if e.isVariadic {
  1122. e.c.emit(newVariadic, endVariadic)
  1123. } else {
  1124. e.c.emit(_new(len(e.args)))
  1125. }
  1126. if !putOnStack {
  1127. e.c.emit(pop)
  1128. }
  1129. }
  1130. func (c *compiler) compileCallArgs(list []ast.Expression) (args []compiledExpr, isVariadic bool) {
  1131. args = make([]compiledExpr, len(list))
  1132. for i, argExpr := range list {
  1133. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  1134. args[i] = c.compileSpreadCallArgument(spread)
  1135. isVariadic = true
  1136. } else {
  1137. args[i] = c.compileExpression(argExpr)
  1138. }
  1139. }
  1140. return
  1141. }
  1142. func (c *compiler) compileNewExpression(v *ast.NewExpression) compiledExpr {
  1143. args, isVariadic := c.compileCallArgs(v.ArgumentList)
  1144. r := &compiledNewExpr{
  1145. compiledCallExpr: compiledCallExpr{
  1146. callee: c.compileExpression(v.Callee),
  1147. args: args,
  1148. isVariadic: isVariadic,
  1149. },
  1150. }
  1151. r.init(c, v.Idx0())
  1152. return r
  1153. }
  1154. func (e *compiledNewTarget) emitGetter(putOnStack bool) {
  1155. if putOnStack {
  1156. e.addSrcMap()
  1157. e.c.emit(loadNewTarget)
  1158. }
  1159. }
  1160. func (c *compiler) compileMetaProperty(v *ast.MetaProperty) compiledExpr {
  1161. if v.Meta.Name == "new" || v.Property.Name != "target" {
  1162. r := &compiledNewTarget{}
  1163. r.init(c, v.Idx0())
  1164. return r
  1165. }
  1166. c.throwSyntaxError(int(v.Idx)-1, "Unsupported meta property: %s.%s", v.Meta.Name, v.Property.Name)
  1167. return nil
  1168. }
  1169. func (e *compiledSequenceExpr) emitGetter(putOnStack bool) {
  1170. if len(e.sequence) > 0 {
  1171. for i := 0; i < len(e.sequence)-1; i++ {
  1172. e.sequence[i].emitGetter(false)
  1173. }
  1174. e.sequence[len(e.sequence)-1].emitGetter(putOnStack)
  1175. }
  1176. }
  1177. func (c *compiler) compileSequenceExpression(v *ast.SequenceExpression) compiledExpr {
  1178. s := make([]compiledExpr, len(v.Sequence))
  1179. for i, expr := range v.Sequence {
  1180. s[i] = c.compileExpression(expr)
  1181. }
  1182. r := &compiledSequenceExpr{
  1183. sequence: s,
  1184. }
  1185. var idx file.Idx
  1186. if len(v.Sequence) > 0 {
  1187. idx = v.Idx0()
  1188. }
  1189. r.init(c, idx)
  1190. return r
  1191. }
  1192. func (c *compiler) emitThrow(v Value) {
  1193. if o, ok := v.(*Object); ok {
  1194. t := nilSafe(o.self.getStr("name", nil)).toString().String()
  1195. switch t {
  1196. case "TypeError":
  1197. c.emit(loadDynamic(t))
  1198. msg := o.self.getStr("message", nil)
  1199. if msg != nil {
  1200. c.emit(loadVal(c.p.defineLiteralValue(msg)))
  1201. c.emit(_new(1))
  1202. } else {
  1203. c.emit(_new(0))
  1204. }
  1205. c.emit(throw)
  1206. return
  1207. }
  1208. }
  1209. panic(fmt.Errorf("unknown exception type thrown while evaliating constant expression: %s", v.String()))
  1210. }
  1211. func (c *compiler) emitConst(expr compiledExpr, putOnStack bool) {
  1212. v, ex := c.evalConst(expr)
  1213. if ex == nil {
  1214. if putOnStack {
  1215. c.emit(loadVal(c.p.defineLiteralValue(v)))
  1216. }
  1217. } else {
  1218. c.emitThrow(ex.val)
  1219. }
  1220. }
  1221. func (c *compiler) emitExpr(expr compiledExpr, putOnStack bool) {
  1222. if expr.constant() {
  1223. c.emitConst(expr, putOnStack)
  1224. } else {
  1225. expr.emitGetter(putOnStack)
  1226. }
  1227. }
  1228. func (c *compiler) evalConst(expr compiledExpr) (Value, *Exception) {
  1229. if expr, ok := expr.(*compiledLiteral); ok {
  1230. return expr.val, nil
  1231. }
  1232. if c.evalVM == nil {
  1233. c.evalVM = New().vm
  1234. }
  1235. var savedPrg *Program
  1236. createdPrg := false
  1237. if c.evalVM.prg == nil {
  1238. c.evalVM.prg = &Program{}
  1239. savedPrg = c.p
  1240. c.p = c.evalVM.prg
  1241. createdPrg = true
  1242. }
  1243. savedPc := len(c.p.code)
  1244. expr.emitGetter(true)
  1245. c.emit(halt)
  1246. c.evalVM.pc = savedPc
  1247. ex := c.evalVM.runTry()
  1248. if createdPrg {
  1249. c.evalVM.prg = nil
  1250. c.evalVM.pc = 0
  1251. c.p = savedPrg
  1252. } else {
  1253. c.evalVM.prg.code = c.evalVM.prg.code[:savedPc]
  1254. c.p.code = c.evalVM.prg.code
  1255. }
  1256. if ex == nil {
  1257. return c.evalVM.pop(), nil
  1258. }
  1259. return nil, ex
  1260. }
  1261. func (e *compiledUnaryExpr) constant() bool {
  1262. return e.operand.constant()
  1263. }
  1264. func (e *compiledUnaryExpr) emitGetter(putOnStack bool) {
  1265. var prepare, body func()
  1266. toNumber := func() {
  1267. e.c.emit(toNumber)
  1268. }
  1269. switch e.operator {
  1270. case token.NOT:
  1271. e.operand.emitGetter(true)
  1272. e.c.emit(not)
  1273. goto end
  1274. case token.BITWISE_NOT:
  1275. e.operand.emitGetter(true)
  1276. e.c.emit(bnot)
  1277. goto end
  1278. case token.TYPEOF:
  1279. if o, ok := e.operand.(compiledExprOrRef); ok {
  1280. o.emitGetterOrRef()
  1281. } else {
  1282. e.operand.emitGetter(true)
  1283. }
  1284. e.c.emit(typeof)
  1285. goto end
  1286. case token.DELETE:
  1287. e.operand.deleteExpr().emitGetter(putOnStack)
  1288. return
  1289. case token.MINUS:
  1290. e.c.emitExpr(e.operand, true)
  1291. e.c.emit(neg)
  1292. goto end
  1293. case token.PLUS:
  1294. e.c.emitExpr(e.operand, true)
  1295. e.c.emit(plus)
  1296. goto end
  1297. case token.INCREMENT:
  1298. prepare = toNumber
  1299. body = func() {
  1300. e.c.emit(inc)
  1301. }
  1302. case token.DECREMENT:
  1303. prepare = toNumber
  1304. body = func() {
  1305. e.c.emit(dec)
  1306. }
  1307. case token.VOID:
  1308. e.c.emitExpr(e.operand, false)
  1309. if putOnStack {
  1310. e.c.emit(loadUndef)
  1311. }
  1312. return
  1313. default:
  1314. panic(fmt.Errorf("Unknown unary operator: %s", e.operator.String()))
  1315. }
  1316. e.operand.emitUnary(prepare, body, e.postfix, putOnStack)
  1317. return
  1318. end:
  1319. if !putOnStack {
  1320. e.c.emit(pop)
  1321. }
  1322. }
  1323. func (c *compiler) compileUnaryExpression(v *ast.UnaryExpression) compiledExpr {
  1324. r := &compiledUnaryExpr{
  1325. operand: c.compileExpression(v.Operand),
  1326. operator: v.Operator,
  1327. postfix: v.Postfix,
  1328. }
  1329. r.init(c, v.Idx0())
  1330. return r
  1331. }
  1332. func (e *compiledConditionalExpr) emitGetter(putOnStack bool) {
  1333. e.test.emitGetter(true)
  1334. j := len(e.c.p.code)
  1335. e.c.emit(nil)
  1336. e.consequent.emitGetter(putOnStack)
  1337. j1 := len(e.c.p.code)
  1338. e.c.emit(nil)
  1339. e.c.p.code[j] = jne(len(e.c.p.code) - j)
  1340. e.alternate.emitGetter(putOnStack)
  1341. e.c.p.code[j1] = jump(len(e.c.p.code) - j1)
  1342. }
  1343. func (c *compiler) compileConditionalExpression(v *ast.ConditionalExpression) compiledExpr {
  1344. r := &compiledConditionalExpr{
  1345. test: c.compileExpression(v.Test),
  1346. consequent: c.compileExpression(v.Consequent),
  1347. alternate: c.compileExpression(v.Alternate),
  1348. }
  1349. r.init(c, v.Idx0())
  1350. return r
  1351. }
  1352. func (e *compiledLogicalOr) constant() bool {
  1353. if e.left.constant() {
  1354. if v, ex := e.c.evalConst(e.left); ex == nil {
  1355. if v.ToBoolean() {
  1356. return true
  1357. }
  1358. return e.right.constant()
  1359. } else {
  1360. return true
  1361. }
  1362. }
  1363. return false
  1364. }
  1365. func (e *compiledLogicalOr) emitGetter(putOnStack bool) {
  1366. if e.left.constant() {
  1367. if v, ex := e.c.evalConst(e.left); ex == nil {
  1368. if !v.ToBoolean() {
  1369. e.c.emitExpr(e.right, putOnStack)
  1370. } else {
  1371. if putOnStack {
  1372. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  1373. }
  1374. }
  1375. } else {
  1376. e.c.emitThrow(ex.val)
  1377. }
  1378. return
  1379. }
  1380. e.c.emitExpr(e.left, true)
  1381. j := len(e.c.p.code)
  1382. e.addSrcMap()
  1383. e.c.emit(nil)
  1384. e.c.emit(pop)
  1385. e.c.emitExpr(e.right, true)
  1386. e.c.p.code[j] = jeq1(len(e.c.p.code) - j)
  1387. if !putOnStack {
  1388. e.c.emit(pop)
  1389. }
  1390. }
  1391. func (e *compiledLogicalAnd) constant() bool {
  1392. if e.left.constant() {
  1393. if v, ex := e.c.evalConst(e.left); ex == nil {
  1394. if !v.ToBoolean() {
  1395. return true
  1396. } else {
  1397. return e.right.constant()
  1398. }
  1399. } else {
  1400. return true
  1401. }
  1402. }
  1403. return false
  1404. }
  1405. func (e *compiledLogicalAnd) emitGetter(putOnStack bool) {
  1406. var j int
  1407. if e.left.constant() {
  1408. if v, ex := e.c.evalConst(e.left); ex == nil {
  1409. if !v.ToBoolean() {
  1410. e.c.emit(loadVal(e.c.p.defineLiteralValue(v)))
  1411. } else {
  1412. e.c.emitExpr(e.right, putOnStack)
  1413. }
  1414. } else {
  1415. e.c.emitThrow(ex.val)
  1416. }
  1417. return
  1418. }
  1419. e.left.emitGetter(true)
  1420. j = len(e.c.p.code)
  1421. e.addSrcMap()
  1422. e.c.emit(nil)
  1423. e.c.emit(pop)
  1424. e.c.emitExpr(e.right, true)
  1425. e.c.p.code[j] = jneq1(len(e.c.p.code) - j)
  1426. if !putOnStack {
  1427. e.c.emit(pop)
  1428. }
  1429. }
  1430. func (e *compiledBinaryExpr) constant() bool {
  1431. return e.left.constant() && e.right.constant()
  1432. }
  1433. func (e *compiledBinaryExpr) emitGetter(putOnStack bool) {
  1434. e.c.emitExpr(e.left, true)
  1435. e.c.emitExpr(e.right, true)
  1436. e.addSrcMap()
  1437. switch e.operator {
  1438. case token.LESS:
  1439. e.c.emit(op_lt)
  1440. case token.GREATER:
  1441. e.c.emit(op_gt)
  1442. case token.LESS_OR_EQUAL:
  1443. e.c.emit(op_lte)
  1444. case token.GREATER_OR_EQUAL:
  1445. e.c.emit(op_gte)
  1446. case token.EQUAL:
  1447. e.c.emit(op_eq)
  1448. case token.NOT_EQUAL:
  1449. e.c.emit(op_neq)
  1450. case token.STRICT_EQUAL:
  1451. e.c.emit(op_strict_eq)
  1452. case token.STRICT_NOT_EQUAL:
  1453. e.c.emit(op_strict_neq)
  1454. case token.PLUS:
  1455. e.c.emit(add)
  1456. case token.MINUS:
  1457. e.c.emit(sub)
  1458. case token.MULTIPLY:
  1459. e.c.emit(mul)
  1460. case token.SLASH:
  1461. e.c.emit(div)
  1462. case token.REMAINDER:
  1463. e.c.emit(mod)
  1464. case token.AND:
  1465. e.c.emit(and)
  1466. case token.OR:
  1467. e.c.emit(or)
  1468. case token.EXCLUSIVE_OR:
  1469. e.c.emit(xor)
  1470. case token.INSTANCEOF:
  1471. e.c.emit(op_instanceof)
  1472. case token.IN:
  1473. e.c.emit(op_in)
  1474. case token.SHIFT_LEFT:
  1475. e.c.emit(sal)
  1476. case token.SHIFT_RIGHT:
  1477. e.c.emit(sar)
  1478. case token.UNSIGNED_SHIFT_RIGHT:
  1479. e.c.emit(shr)
  1480. default:
  1481. panic(fmt.Errorf("Unknown operator: %s", e.operator.String()))
  1482. }
  1483. if !putOnStack {
  1484. e.c.emit(pop)
  1485. }
  1486. }
  1487. func (c *compiler) compileBinaryExpression(v *ast.BinaryExpression) compiledExpr {
  1488. switch v.Operator {
  1489. case token.LOGICAL_OR:
  1490. return c.compileLogicalOr(v.Left, v.Right, v.Idx0())
  1491. case token.LOGICAL_AND:
  1492. return c.compileLogicalAnd(v.Left, v.Right, v.Idx0())
  1493. }
  1494. r := &compiledBinaryExpr{
  1495. left: c.compileExpression(v.Left),
  1496. right: c.compileExpression(v.Right),
  1497. operator: v.Operator,
  1498. }
  1499. r.init(c, v.Idx0())
  1500. return r
  1501. }
  1502. func (c *compiler) compileLogicalOr(left, right ast.Expression, idx file.Idx) compiledExpr {
  1503. r := &compiledLogicalOr{
  1504. left: c.compileExpression(left),
  1505. right: c.compileExpression(right),
  1506. }
  1507. r.init(c, idx)
  1508. return r
  1509. }
  1510. func (c *compiler) compileLogicalAnd(left, right ast.Expression, idx file.Idx) compiledExpr {
  1511. r := &compiledLogicalAnd{
  1512. left: c.compileExpression(left),
  1513. right: c.compileExpression(right),
  1514. }
  1515. r.init(c, idx)
  1516. return r
  1517. }
  1518. func (e *compiledObjectLiteral) emitGetter(putOnStack bool) {
  1519. e.addSrcMap()
  1520. e.c.emit(newObject)
  1521. for _, prop := range e.expr.Value {
  1522. switch prop := prop.(type) {
  1523. case *ast.PropertyKeyed:
  1524. keyExpr := e.c.compileExpression(prop.Key)
  1525. computed := false
  1526. var key unistring.String
  1527. switch keyExpr := keyExpr.(type) {
  1528. case *compiledLiteral:
  1529. key = keyExpr.val.string()
  1530. default:
  1531. keyExpr.emitGetter(true)
  1532. computed = true
  1533. //e.c.throwSyntaxError(e.offset, "non-literal properties in object literal are not supported yet")
  1534. }
  1535. valueExpr := e.c.compileExpression(prop.Value)
  1536. var anonFn *compiledFunctionLiteral
  1537. if fn, ok := valueExpr.(*compiledFunctionLiteral); ok {
  1538. if fn.expr.Name == nil {
  1539. anonFn = fn
  1540. fn.lhsName = key
  1541. }
  1542. }
  1543. if computed {
  1544. e.c.emit(_toPropertyKey{})
  1545. valueExpr.emitGetter(true)
  1546. switch prop.Kind {
  1547. case ast.PropertyKindValue, ast.PropertyKindMethod:
  1548. if anonFn != nil {
  1549. e.c.emit(setElem1Named)
  1550. } else {
  1551. e.c.emit(setElem1)
  1552. }
  1553. case ast.PropertyKindGet:
  1554. e.c.emit(setPropGetter1)
  1555. case ast.PropertyKindSet:
  1556. e.c.emit(setPropSetter1)
  1557. default:
  1558. panic(fmt.Errorf("unknown property kind: %s", prop.Kind))
  1559. }
  1560. } else {
  1561. if anonFn != nil {
  1562. anonFn.lhsName = key
  1563. }
  1564. valueExpr.emitGetter(true)
  1565. switch prop.Kind {
  1566. case ast.PropertyKindValue:
  1567. if key == __proto__ {
  1568. e.c.emit(setProto)
  1569. } else {
  1570. e.c.emit(setProp1(key))
  1571. }
  1572. case ast.PropertyKindMethod:
  1573. e.c.emit(setProp1(key))
  1574. case ast.PropertyKindGet:
  1575. e.c.emit(setPropGetter(key))
  1576. case ast.PropertyKindSet:
  1577. e.c.emit(setPropSetter(key))
  1578. default:
  1579. panic(fmt.Errorf("unknown property kind: %s", prop.Kind))
  1580. }
  1581. }
  1582. case *ast.PropertyShort:
  1583. key := prop.Name.Name
  1584. if prop.Initializer != nil {
  1585. e.c.throwSyntaxError(int(prop.Initializer.Idx0())-1, "Invalid shorthand property initializer")
  1586. }
  1587. if e.c.scope.strict && key == "let" {
  1588. e.c.throwSyntaxError(e.offset, "'let' cannot be used as a shorthand property in strict mode")
  1589. }
  1590. e.c.compileIdentifierExpression(&prop.Name).emitGetter(true)
  1591. e.c.emit(setProp1(key))
  1592. case *ast.SpreadElement:
  1593. e.c.compileExpression(prop.Expression).emitGetter(true)
  1594. e.c.emit(copySpread)
  1595. default:
  1596. panic(fmt.Errorf("unknown Property type: %T", prop))
  1597. }
  1598. }
  1599. if !putOnStack {
  1600. e.c.emit(pop)
  1601. }
  1602. }
  1603. func (c *compiler) compileObjectLiteral(v *ast.ObjectLiteral) compiledExpr {
  1604. r := &compiledObjectLiteral{
  1605. expr: v,
  1606. }
  1607. r.init(c, v.Idx0())
  1608. return r
  1609. }
  1610. func (e *compiledArrayLiteral) emitGetter(putOnStack bool) {
  1611. e.addSrcMap()
  1612. hasSpread := false
  1613. mark := len(e.c.p.code)
  1614. e.c.emit(nil)
  1615. for _, v := range e.expr.Value {
  1616. if spread, ok := v.(*ast.SpreadElement); ok {
  1617. hasSpread = true
  1618. e.c.compileExpression(spread.Expression).emitGetter(true)
  1619. e.c.emit(pushArraySpread)
  1620. } else {
  1621. if v != nil {
  1622. e.c.compileExpression(v).emitGetter(true)
  1623. } else {
  1624. e.c.emit(loadNil)
  1625. }
  1626. e.c.emit(pushArrayItem)
  1627. }
  1628. }
  1629. var objCount uint32
  1630. if !hasSpread {
  1631. objCount = uint32(len(e.expr.Value))
  1632. }
  1633. e.c.p.code[mark] = newArray(objCount)
  1634. if !putOnStack {
  1635. e.c.emit(pop)
  1636. }
  1637. }
  1638. func (c *compiler) compileArrayLiteral(v *ast.ArrayLiteral) compiledExpr {
  1639. r := &compiledArrayLiteral{
  1640. expr: v,
  1641. }
  1642. r.init(c, v.Idx0())
  1643. return r
  1644. }
  1645. func (e *compiledRegexpLiteral) emitGetter(putOnStack bool) {
  1646. if putOnStack {
  1647. pattern, err := compileRegexp(e.expr.Pattern, e.expr.Flags)
  1648. if err != nil {
  1649. e.c.throwSyntaxError(e.offset, err.Error())
  1650. }
  1651. e.c.emit(&newRegexp{pattern: pattern, src: newStringValue(e.expr.Pattern)})
  1652. }
  1653. }
  1654. func (c *compiler) compileRegexpLiteral(v *ast.RegExpLiteral) compiledExpr {
  1655. r := &compiledRegexpLiteral{
  1656. expr: v,
  1657. }
  1658. r.init(c, v.Idx0())
  1659. return r
  1660. }
  1661. func (e *compiledCallExpr) emitGetter(putOnStack bool) {
  1662. var calleeName unistring.String
  1663. if e.isVariadic {
  1664. e.c.emit(startVariadic)
  1665. }
  1666. switch callee := e.callee.(type) {
  1667. case *compiledDotExpr:
  1668. callee.left.emitGetter(true)
  1669. e.c.emit(dup)
  1670. e.c.emit(getPropCallee(callee.name))
  1671. case *compiledBracketExpr:
  1672. callee.left.emitGetter(true)
  1673. e.c.emit(dup)
  1674. callee.member.emitGetter(true)
  1675. e.c.emit(getElemCallee)
  1676. case *compiledIdentifierExpr:
  1677. calleeName = callee.name
  1678. callee.emitGetterAndCallee()
  1679. default:
  1680. e.c.emit(loadUndef)
  1681. callee.emitGetter(true)
  1682. }
  1683. for _, expr := range e.args {
  1684. expr.emitGetter(true)
  1685. }
  1686. e.addSrcMap()
  1687. if calleeName == "eval" {
  1688. foundFunc, foundVar := false, false
  1689. for sc := e.c.scope; sc != nil; sc = sc.outer {
  1690. if !foundFunc && sc.function {
  1691. foundFunc = true
  1692. sc.thisNeeded, sc.argsNeeded = true, true
  1693. }
  1694. if !foundVar && (sc.variable || sc.function) {
  1695. foundVar = true
  1696. if !sc.strict {
  1697. sc.dynamic = true
  1698. }
  1699. }
  1700. sc.dynLookup = true
  1701. }
  1702. if e.c.scope.strict {
  1703. if e.isVariadic {
  1704. e.c.emit(callEvalVariadicStrict)
  1705. } else {
  1706. e.c.emit(callEvalStrict(len(e.args)))
  1707. }
  1708. } else {
  1709. if e.isVariadic {
  1710. e.c.emit(callEvalVariadic)
  1711. } else {
  1712. e.c.emit(callEval(len(e.args)))
  1713. }
  1714. }
  1715. } else {
  1716. if e.isVariadic {
  1717. e.c.emit(callVariadic)
  1718. } else {
  1719. e.c.emit(call(len(e.args)))
  1720. }
  1721. }
  1722. if e.isVariadic {
  1723. e.c.emit(endVariadic)
  1724. }
  1725. if !putOnStack {
  1726. e.c.emit(pop)
  1727. }
  1728. }
  1729. func (e *compiledCallExpr) deleteExpr() compiledExpr {
  1730. r := &defaultDeleteExpr{
  1731. expr: e,
  1732. }
  1733. r.init(e.c, file.Idx(e.offset+1))
  1734. return r
  1735. }
  1736. func (c *compiler) compileSpreadCallArgument(spread *ast.SpreadElement) compiledExpr {
  1737. r := &compiledSpreadCallArgument{
  1738. expr: c.compileExpression(spread.Expression),
  1739. }
  1740. r.init(c, spread.Idx0())
  1741. return r
  1742. }
  1743. func (c *compiler) compileCallExpression(v *ast.CallExpression) compiledExpr {
  1744. args := make([]compiledExpr, len(v.ArgumentList))
  1745. isVariadic := false
  1746. for i, argExpr := range v.ArgumentList {
  1747. if spread, ok := argExpr.(*ast.SpreadElement); ok {
  1748. args[i] = c.compileSpreadCallArgument(spread)
  1749. isVariadic = true
  1750. } else {
  1751. args[i] = c.compileExpression(argExpr)
  1752. }
  1753. }
  1754. r := &compiledCallExpr{
  1755. args: args,
  1756. callee: c.compileExpression(v.Callee),
  1757. isVariadic: isVariadic,
  1758. }
  1759. r.init(c, v.LeftParenthesis)
  1760. return r
  1761. }
  1762. func (c *compiler) compileIdentifierExpression(v *ast.Identifier) compiledExpr {
  1763. if c.scope.strict {
  1764. c.checkIdentifierName(v.Name, int(v.Idx)-1)
  1765. }
  1766. r := &compiledIdentifierExpr{
  1767. name: v.Name,
  1768. }
  1769. r.offset = int(v.Idx) - 1
  1770. r.init(c, v.Idx0())
  1771. return r
  1772. }
  1773. func (c *compiler) compileNumberLiteral(v *ast.NumberLiteral) compiledExpr {
  1774. if c.scope.strict && octalRegexp.MatchString(v.Literal) {
  1775. c.throwSyntaxError(int(v.Idx)-1, "Octal literals are not allowed in strict mode")
  1776. panic("Unreachable")
  1777. }
  1778. var val Value
  1779. switch num := v.Value.(type) {
  1780. case int64:
  1781. val = intToValue(num)
  1782. case float64:
  1783. val = floatToValue(num)
  1784. default:
  1785. panic(fmt.Errorf("Unsupported number literal type: %T", v.Value))
  1786. }
  1787. r := &compiledLiteral{
  1788. val: val,
  1789. }
  1790. r.init(c, v.Idx0())
  1791. return r
  1792. }
  1793. func (c *compiler) compileStringLiteral(v *ast.StringLiteral) compiledExpr {
  1794. r := &compiledLiteral{
  1795. val: stringValueFromRaw(v.Value),
  1796. }
  1797. r.init(c, v.Idx0())
  1798. return r
  1799. }
  1800. func (c *compiler) compileBooleanLiteral(v *ast.BooleanLiteral) compiledExpr {
  1801. var val Value
  1802. if v.Value {
  1803. val = valueTrue
  1804. } else {
  1805. val = valueFalse
  1806. }
  1807. r := &compiledLiteral{
  1808. val: val,
  1809. }
  1810. r.init(c, v.Idx0())
  1811. return r
  1812. }
  1813. func (c *compiler) compileAssignExpression(v *ast.AssignExpression) compiledExpr {
  1814. // log.Printf("compileAssignExpression(): %+v", v)
  1815. r := &compiledAssignExpr{
  1816. left: c.compileExpression(v.Left),
  1817. right: c.compileExpression(v.Right),
  1818. operator: v.Operator,
  1819. }
  1820. r.init(c, v.Idx0())
  1821. return r
  1822. }
  1823. func (e *compiledEnumGetExpr) emitGetter(putOnStack bool) {
  1824. e.c.emit(enumGet)
  1825. if !putOnStack {
  1826. e.c.emit(pop)
  1827. }
  1828. }
  1829. func (c *compiler) compileObjectAssignmentPattern(v *ast.ObjectPattern) compiledExpr {
  1830. r := &compiledObjectAssignmentPattern{
  1831. expr: v,
  1832. }
  1833. r.init(c, v.Idx0())
  1834. return r
  1835. }
  1836. func (e *compiledObjectAssignmentPattern) emitGetter(putOnStack bool) {
  1837. if putOnStack {
  1838. e.c.emit(loadUndef)
  1839. }
  1840. }
  1841. func (c *compiler) compileArrayAssignmentPattern(v *ast.ArrayPattern) compiledExpr {
  1842. r := &compiledArrayAssignmentPattern{
  1843. expr: v,
  1844. }
  1845. r.init(c, v.Idx0())
  1846. return r
  1847. }
  1848. func (e *compiledArrayAssignmentPattern) emitGetter(putOnStack bool) {
  1849. if putOnStack {
  1850. e.c.emit(loadUndef)
  1851. }
  1852. }
  1853. func (c *compiler) emitNamed(expr compiledExpr, name unistring.String) {
  1854. if en, ok := expr.(interface {
  1855. emitNamed(name unistring.String)
  1856. }); ok {
  1857. en.emitNamed(name)
  1858. } else {
  1859. expr.emitGetter(true)
  1860. }
  1861. }
  1862. func (e *compiledFunctionLiteral) emitNamed(name unistring.String) {
  1863. e.lhsName = name
  1864. e.emitGetter(true)
  1865. }
  1866. func (c *compiler) emitPattern(pattern ast.Pattern, emitter func(target, init compiledExpr), putOnStack bool) {
  1867. switch pattern := pattern.(type) {
  1868. case *ast.ObjectPattern:
  1869. c.emitObjectPattern(pattern, emitter, putOnStack)
  1870. case *ast.ArrayPattern:
  1871. c.emitArrayPattern(pattern, emitter, putOnStack)
  1872. default:
  1873. panic(fmt.Errorf("unsupported Pattern: %T", pattern))
  1874. }
  1875. }
  1876. func (c *compiler) emitAssign(target ast.Expression, init compiledExpr, emitAssignSimple func(target, init compiledExpr)) {
  1877. pattern, isPattern := target.(ast.Pattern)
  1878. if isPattern {
  1879. init.emitGetter(true)
  1880. c.emitPattern(pattern, emitAssignSimple, false)
  1881. } else {
  1882. emitAssignSimple(c.compileExpression(target), init)
  1883. }
  1884. }
  1885. func (c *compiler) emitObjectPattern(pattern *ast.ObjectPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  1886. if pattern.Rest != nil {
  1887. c.emit(createDestructSrc)
  1888. } else {
  1889. c.emit(checkObjectCoercible)
  1890. }
  1891. for _, prop := range pattern.Properties {
  1892. switch prop := prop.(type) {
  1893. case *ast.PropertyShort:
  1894. c.emit(dup)
  1895. emitAssign(c.compileIdentifierExpression(&prop.Name), c.compilePatternInitExpr(func() {
  1896. c.emit(getProp(prop.Name.Name))
  1897. }, prop.Initializer, prop.Idx0()))
  1898. case *ast.PropertyKeyed:
  1899. c.emit(dup)
  1900. c.compileExpression(prop.Key).emitGetter(true)
  1901. c.emit(_toPropertyKey{})
  1902. var target ast.Expression
  1903. var initializer ast.Expression
  1904. if e, ok := prop.Value.(*ast.AssignExpression); ok {
  1905. target = e.Left
  1906. initializer = e.Right
  1907. } else {
  1908. target = prop.Value
  1909. }
  1910. c.emitAssign(target, c.compilePatternInitExpr(func() {
  1911. c.emit(getKey)
  1912. }, initializer, prop.Idx0()), emitAssign)
  1913. default:
  1914. c.throwSyntaxError(int(prop.Idx0()-1), "Unsupported AssignmentProperty type: %T", prop)
  1915. }
  1916. }
  1917. if pattern.Rest != nil {
  1918. emitAssign(c.compileExpression(pattern.Rest), c.compileEmitterExpr(func() {
  1919. c.emit(copyRest)
  1920. }, pattern.Rest.Idx0()))
  1921. c.emit(pop)
  1922. }
  1923. if !putOnStack {
  1924. c.emit(pop)
  1925. }
  1926. }
  1927. func (c *compiler) emitArrayPattern(pattern *ast.ArrayPattern, emitAssign func(target, init compiledExpr), putOnStack bool) {
  1928. var marks []int
  1929. c.emit(iterate)
  1930. for _, elt := range pattern.Elements {
  1931. switch elt := elt.(type) {
  1932. case nil:
  1933. marks = append(marks, len(c.p.code))
  1934. c.emit(nil)
  1935. case *ast.AssignExpression:
  1936. c.emitAssign(elt.Left, c.compilePatternInitExpr(func() {
  1937. marks = append(marks, len(c.p.code))
  1938. c.emit(nil, enumGet)
  1939. }, elt.Right, elt.Idx0()), emitAssign)
  1940. default:
  1941. c.emitAssign(elt, c.compileEmitterExpr(func() {
  1942. marks = append(marks, len(c.p.code))
  1943. c.emit(nil, enumGet)
  1944. }, elt.Idx0()), emitAssign)
  1945. }
  1946. }
  1947. if pattern.Rest != nil {
  1948. c.emitAssign(pattern.Rest, c.compileEmitterExpr(func() {
  1949. c.emit(newArrayFromIter)
  1950. }, pattern.Rest.Idx0()), emitAssign)
  1951. } else {
  1952. c.emit(enumPopClose)
  1953. }
  1954. mark1 := len(c.p.code)
  1955. c.emit(nil)
  1956. for i, elt := range pattern.Elements {
  1957. switch elt := elt.(type) {
  1958. case nil:
  1959. c.p.code[marks[i]] = iterNext(len(c.p.code) - marks[i])
  1960. case *ast.Identifier:
  1961. emitAssign(c.compileIdentifierExpression(elt), c.compileEmitterExpr(func() {
  1962. c.p.code[marks[i]] = iterNext(len(c.p.code) - marks[i])
  1963. c.emit(loadUndef)
  1964. }, elt.Idx0()))
  1965. case *ast.AssignExpression:
  1966. c.emitAssign(elt.Left, c.compileNamedEmitterExpr(func(name unistring.String) {
  1967. c.p.code[marks[i]] = iterNext(len(c.p.code) - marks[i])
  1968. c.emitNamed(c.compileExpression(elt.Right), name)
  1969. }, elt.Idx0()), emitAssign)
  1970. default:
  1971. c.emitAssign(elt, c.compileEmitterExpr(
  1972. func() {
  1973. c.p.code[marks[i]] = iterNext(len(c.p.code) - marks[i])
  1974. c.emit(loadUndef)
  1975. }, elt.Idx0()), emitAssign)
  1976. }
  1977. }
  1978. c.emit(enumPop)
  1979. if pattern.Rest != nil {
  1980. c.emitAssign(pattern.Rest, c.compileExpression(
  1981. &ast.ArrayLiteral{
  1982. LeftBracket: pattern.Rest.Idx0(),
  1983. RightBracket: pattern.Rest.Idx0(),
  1984. }), emitAssign)
  1985. }
  1986. c.p.code[mark1] = jump(len(c.p.code) - mark1)
  1987. if !putOnStack {
  1988. c.emit(pop)
  1989. }
  1990. }
  1991. func (e *compiledObjectAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  1992. valueExpr.emitGetter(true)
  1993. e.c.emitObjectPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  1994. }
  1995. func (e *compiledArrayAssignmentPattern) emitSetter(valueExpr compiledExpr, putOnStack bool) {
  1996. valueExpr.emitGetter(true)
  1997. e.c.emitArrayPattern(e.expr, e.c.emitPatternAssign, putOnStack)
  1998. }
  1999. type compiledPatternInitExpr struct {
  2000. baseCompiledExpr
  2001. emitSrc func()
  2002. def compiledExpr
  2003. }
  2004. func (e *compiledPatternInitExpr) emitGetter(putOnStack bool) {
  2005. if !putOnStack {
  2006. return
  2007. }
  2008. e.emitSrc()
  2009. if e.def != nil {
  2010. mark := len(e.c.p.code)
  2011. e.c.emit(nil)
  2012. e.def.emitGetter(true)
  2013. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  2014. }
  2015. }
  2016. func (e *compiledPatternInitExpr) emitNamed(name unistring.String) {
  2017. e.emitSrc()
  2018. if e.def != nil {
  2019. mark := len(e.c.p.code)
  2020. e.c.emit(nil)
  2021. e.c.emitNamed(e.def, name)
  2022. e.c.p.code[mark] = jdef(len(e.c.p.code) - mark)
  2023. }
  2024. }
  2025. func (c *compiler) compilePatternInitExpr(emitSrc func(), def ast.Expression, idx file.Idx) compiledExpr {
  2026. r := &compiledPatternInitExpr{
  2027. emitSrc: emitSrc,
  2028. def: c.compileExpression(def),
  2029. }
  2030. r.init(c, idx)
  2031. return r
  2032. }
  2033. type compiledEmitterExpr struct {
  2034. baseCompiledExpr
  2035. emitter func()
  2036. namedEmitter func(name unistring.String)
  2037. }
  2038. func (e *compiledEmitterExpr) emitGetter(putOnStack bool) {
  2039. if e.emitter != nil {
  2040. e.emitter()
  2041. } else {
  2042. e.namedEmitter("")
  2043. }
  2044. if !putOnStack {
  2045. e.c.emit(pop)
  2046. }
  2047. }
  2048. func (e *compiledEmitterExpr) emitNamed(name unistring.String) {
  2049. if e.namedEmitter != nil {
  2050. e.namedEmitter(name)
  2051. } else {
  2052. e.emitter()
  2053. }
  2054. }
  2055. func (c *compiler) compileEmitterExpr(emitter func(), idx file.Idx) *compiledEmitterExpr {
  2056. r := &compiledEmitterExpr{
  2057. emitter: emitter,
  2058. }
  2059. r.init(c, idx)
  2060. return r
  2061. }
  2062. func (c *compiler) compileNamedEmitterExpr(namedEmitter func(unistring.String), idx file.Idx) *compiledEmitterExpr {
  2063. r := &compiledEmitterExpr{
  2064. namedEmitter: namedEmitter,
  2065. }
  2066. r.init(c, idx)
  2067. return r
  2068. }
  2069. func (e *compiledSpreadCallArgument) emitGetter(putOnStack bool) {
  2070. e.expr.emitGetter(putOnStack)
  2071. if putOnStack {
  2072. e.c.emit(pushSpread)
  2073. }
  2074. }