compiler_expr.go 54 KB

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