compiler.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. package goja
  2. import (
  3. "fmt"
  4. "github.com/dop251/goja/ast"
  5. "github.com/dop251/goja/file"
  6. "sort"
  7. "strconv"
  8. )
  9. const (
  10. blockLoop = iota
  11. blockTry
  12. blockBranch
  13. blockSwitch
  14. blockWith
  15. )
  16. type CompilerError struct {
  17. Message string
  18. File *SrcFile
  19. Offset int
  20. }
  21. type CompilerSyntaxError struct {
  22. CompilerError
  23. }
  24. type CompilerReferenceError struct {
  25. CompilerError
  26. }
  27. type srcMapItem struct {
  28. pc int
  29. srcPos int
  30. }
  31. type Program struct {
  32. code []instruction
  33. values []Value
  34. funcName string
  35. src *SrcFile
  36. srcMap []srcMapItem
  37. }
  38. type compiler struct {
  39. p *Program
  40. scope *scope
  41. block *block
  42. blockStart int
  43. enumGetExpr compiledEnumGetExpr
  44. evalVM *vm
  45. }
  46. type scope struct {
  47. names map[string]uint32
  48. outer *scope
  49. strict bool
  50. eval bool
  51. lexical bool
  52. dynamic bool
  53. accessed bool
  54. argsNeeded bool
  55. thisNeeded bool
  56. namesMap map[string]string
  57. lastFreeTmp int
  58. }
  59. type block struct {
  60. typ int
  61. label string
  62. needResult bool
  63. cont int
  64. breaks []int
  65. conts []int
  66. outer *block
  67. }
  68. func (c *compiler) leaveBlock() {
  69. lbl := len(c.p.code)
  70. for _, item := range c.block.breaks {
  71. c.p.code[item] = jump(lbl - item)
  72. }
  73. if c.block.typ == blockLoop {
  74. for _, item := range c.block.conts {
  75. c.p.code[item] = jump(c.block.cont - item)
  76. }
  77. }
  78. c.block = c.block.outer
  79. }
  80. func (e *CompilerSyntaxError) Error() string {
  81. if e.File != nil {
  82. return fmt.Sprintf("SyntaxError: %s at %s", e.Message, e.File.Position(e.Offset))
  83. }
  84. return fmt.Sprintf("SyntaxError: %s", e.Message)
  85. }
  86. func (e *CompilerReferenceError) Error() string {
  87. return fmt.Sprintf("ReferenceError: %s", e.Message)
  88. }
  89. func (c *compiler) newScope() {
  90. strict := false
  91. if c.scope != nil {
  92. strict = c.scope.strict
  93. }
  94. c.scope = &scope{
  95. outer: c.scope,
  96. names: make(map[string]uint32),
  97. strict: strict,
  98. namesMap: make(map[string]string),
  99. }
  100. }
  101. func (c *compiler) popScope() {
  102. c.scope = c.scope.outer
  103. }
  104. func newCompiler() *compiler {
  105. c := &compiler{
  106. p: &Program{},
  107. }
  108. c.enumGetExpr.init(c, file.Idx(0))
  109. c.newScope()
  110. c.scope.dynamic = true
  111. return c
  112. }
  113. func (p *Program) defineLiteralValue(val Value) uint32 {
  114. for idx, v := range p.values {
  115. if v.SameAs(val) {
  116. return uint32(idx)
  117. }
  118. }
  119. idx := uint32(len(p.values))
  120. p.values = append(p.values, val)
  121. return idx
  122. }
  123. func (p *Program) dumpCode(logger func(format string, args ...interface{})) {
  124. p._dumpCode("", logger)
  125. }
  126. func (p *Program) _dumpCode(indent string, logger func(format string, args ...interface{})) {
  127. logger("values: %+v", p.values)
  128. for pc, ins := range p.code {
  129. logger("%s %d: %T(%v)", indent, pc, ins, ins)
  130. if f, ok := ins.(*newFunc); ok {
  131. f.prg._dumpCode(indent+">", logger)
  132. }
  133. }
  134. }
  135. func (p *Program) sourceOffset(pc int) int {
  136. i := sort.Search(len(p.srcMap), func(idx int) bool {
  137. return p.srcMap[idx].pc > pc
  138. }) - 1
  139. if i >= 0 {
  140. return p.srcMap[i].srcPos
  141. }
  142. return 0
  143. }
  144. func (s *scope) isFunction() bool {
  145. if !s.lexical {
  146. return s.outer != nil
  147. }
  148. return s.outer.isFunction()
  149. }
  150. func (s *scope) lookupName(name string) (idx uint32, found, noDynamics bool) {
  151. var level uint32 = 0
  152. noDynamics = true
  153. for curScope := s; curScope != nil; curScope = curScope.outer {
  154. if curScope != s {
  155. curScope.accessed = true
  156. }
  157. if curScope.dynamic {
  158. noDynamics = false
  159. } else {
  160. var mapped string
  161. if m, exists := curScope.namesMap[name]; exists {
  162. mapped = m
  163. } else {
  164. mapped = name
  165. }
  166. if i, exists := curScope.names[mapped]; exists {
  167. idx = i | (level << 24)
  168. found = true
  169. return
  170. }
  171. }
  172. if name == "arguments" && !s.lexical && s.isFunction() {
  173. s.argsNeeded = true
  174. s.accessed = true
  175. idx, _ = s.bindName(name)
  176. found = true
  177. return
  178. }
  179. level++
  180. }
  181. return
  182. }
  183. func (s *scope) bindName(name string) (uint32, bool) {
  184. if s.lexical {
  185. return s.outer.bindName(name)
  186. }
  187. if idx, exists := s.names[name]; exists {
  188. return idx, false
  189. }
  190. idx := uint32(len(s.names))
  191. s.names[name] = idx
  192. return idx, true
  193. }
  194. func (s *scope) bindNameShadow(name string) (uint32, bool) {
  195. if s.lexical {
  196. return s.outer.bindName(name)
  197. }
  198. unique := true
  199. if idx, exists := s.names[name]; exists {
  200. unique = false
  201. // shadow the var
  202. delete(s.names, name)
  203. n := strconv.Itoa(int(idx))
  204. s.names[n] = idx
  205. }
  206. idx := uint32(len(s.names))
  207. s.names[name] = idx
  208. return idx, unique
  209. }
  210. func (c *compiler) markBlockStart() {
  211. c.blockStart = len(c.p.code)
  212. }
  213. func (c *compiler) compile(in *ast.Program) {
  214. c.p.src = NewSrcFile(in.File.Name(), in.File.Source(), in.SourceMap)
  215. if len(in.Body) > 0 {
  216. if !c.scope.strict {
  217. c.scope.strict = c.isStrict(in.Body)
  218. }
  219. }
  220. c.compileDeclList(in.DeclarationList, false)
  221. c.compileFunctions(in.DeclarationList)
  222. c.markBlockStart()
  223. c.compileStatements(in.Body, true)
  224. c.p.code = append(c.p.code, halt)
  225. code := c.p.code
  226. c.p.code = make([]instruction, 0, len(code)+len(c.scope.names)+2)
  227. if c.scope.eval {
  228. if !c.scope.strict {
  229. c.emit(jne(2), newStash)
  230. } else {
  231. c.emit(pop, newStash)
  232. }
  233. }
  234. l := len(c.p.code)
  235. c.p.code = c.p.code[:l+len(c.scope.names)]
  236. for name, nameIdx := range c.scope.names {
  237. c.p.code[l+int(nameIdx)] = bindName(name)
  238. }
  239. c.p.code = append(c.p.code, code...)
  240. for i, _ := range c.p.srcMap {
  241. c.p.srcMap[i].pc += len(c.scope.names)
  242. }
  243. }
  244. func (c *compiler) compileDeclList(v []ast.Declaration, inFunc bool) {
  245. for _, value := range v {
  246. switch value := value.(type) {
  247. case *ast.FunctionDeclaration:
  248. c.compileFunctionDecl(value)
  249. case *ast.VariableDeclaration:
  250. c.compileVarDecl(value, inFunc)
  251. default:
  252. panic(fmt.Errorf("Unsupported declaration: %T", value))
  253. }
  254. }
  255. }
  256. func (c *compiler) compileFunctions(v []ast.Declaration) {
  257. for _, value := range v {
  258. if value, ok := value.(*ast.FunctionDeclaration); ok {
  259. c.compileFunction(value)
  260. }
  261. }
  262. }
  263. func (c *compiler) compileVarDecl(v *ast.VariableDeclaration, inFunc bool) {
  264. for _, item := range v.List {
  265. if c.scope.strict {
  266. c.checkIdentifierLName(item.Name, int(item.Idx)-1)
  267. c.checkIdentifierName(item.Name, int(item.Idx)-1)
  268. }
  269. if !inFunc || item.Name != "arguments" {
  270. idx, ok := c.scope.bindName(item.Name)
  271. _ = idx
  272. //log.Printf("Define var: %s: %x", item.Name, idx)
  273. if !ok {
  274. // TODO: error
  275. }
  276. }
  277. }
  278. }
  279. func (c *compiler) addDecls() []instruction {
  280. code := make([]instruction, len(c.scope.names))
  281. for name, nameIdx := range c.scope.names {
  282. code[nameIdx] = bindName(name)
  283. }
  284. return code
  285. }
  286. func (c *compiler) convertInstrToStashless(instr uint32, args int) (newIdx int, convert bool) {
  287. level := instr >> 24
  288. idx := instr & 0x00FFFFFF
  289. if level > 0 {
  290. level--
  291. newIdx = int((level << 24) | idx)
  292. } else {
  293. iidx := int(idx)
  294. if iidx < args {
  295. newIdx = -iidx - 1
  296. } else {
  297. newIdx = iidx - args + 1
  298. }
  299. convert = true
  300. }
  301. return
  302. }
  303. func (c *compiler) convertFunctionToStashless(code []instruction, args int) {
  304. code[0] = enterFuncStashless{stackSize: uint32(len(c.scope.names) - args), args: uint32(args)}
  305. for pc := 1; pc < len(code); pc++ {
  306. instr := code[pc]
  307. if instr == ret {
  308. code[pc] = retStashless
  309. }
  310. switch instr := instr.(type) {
  311. case getLocal:
  312. if newIdx, convert := c.convertInstrToStashless(uint32(instr), args); convert {
  313. code[pc] = loadStack(newIdx)
  314. } else {
  315. code[pc] = getLocal(newIdx)
  316. }
  317. case setLocal:
  318. if newIdx, convert := c.convertInstrToStashless(uint32(instr), args); convert {
  319. code[pc] = storeStack(newIdx)
  320. } else {
  321. code[pc] = setLocal(newIdx)
  322. }
  323. case setLocalP:
  324. if newIdx, convert := c.convertInstrToStashless(uint32(instr), args); convert {
  325. code[pc] = storeStackP(newIdx)
  326. } else {
  327. code[pc] = setLocalP(newIdx)
  328. }
  329. case getVar:
  330. level := instr.idx >> 24
  331. idx := instr.idx & 0x00FFFFFF
  332. level--
  333. instr.idx = level<<24 | idx
  334. code[pc] = instr
  335. case setVar:
  336. level := instr.idx >> 24
  337. idx := instr.idx & 0x00FFFFFF
  338. level--
  339. instr.idx = level<<24 | idx
  340. code[pc] = instr
  341. }
  342. }
  343. }
  344. func (c *compiler) compileFunctionDecl(v *ast.FunctionDeclaration) {
  345. idx, ok := c.scope.bindName(v.Function.Name.Name)
  346. if !ok {
  347. // TODO: error
  348. }
  349. _ = idx
  350. // log.Printf("Define function: %s: %x", v.Function.Name.Name, idx)
  351. }
  352. func (c *compiler) compileFunction(v *ast.FunctionDeclaration) {
  353. e := &compiledIdentifierExpr{
  354. name: v.Function.Name.Name,
  355. }
  356. e.init(c, v.Function.Idx0())
  357. e.emitSetter(c.compileFunctionLiteral(v.Function, false))
  358. c.emit(pop)
  359. }
  360. func (c *compiler) emit(instructions ...instruction) {
  361. c.p.code = append(c.p.code, instructions...)
  362. }
  363. func (c *compiler) throwSyntaxError(offset int, format string, args ...interface{}) {
  364. panic(&CompilerSyntaxError{
  365. CompilerError: CompilerError{
  366. File: c.p.src,
  367. Offset: offset,
  368. Message: fmt.Sprintf(format, args...),
  369. },
  370. })
  371. }
  372. func (c *compiler) isStrict(list []ast.Statement) bool {
  373. for _, st := range list {
  374. if st, ok := st.(*ast.ExpressionStatement); ok {
  375. if e, ok := st.Expression.(*ast.StringLiteral); ok {
  376. if e.Literal == `"use strict"` || e.Literal == `'use strict'` {
  377. return true
  378. }
  379. } else {
  380. break
  381. }
  382. } else {
  383. break
  384. }
  385. }
  386. return false
  387. }
  388. func (c *compiler) isStrictStatement(s ast.Statement) bool {
  389. if s, ok := s.(*ast.BlockStatement); ok {
  390. return c.isStrict(s.List)
  391. }
  392. return false
  393. }
  394. func (c *compiler) checkIdentifierName(name string, offset int) {
  395. switch name {
  396. case "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield":
  397. c.throwSyntaxError(offset, "Unexpected strict mode reserved word")
  398. }
  399. }
  400. func (c *compiler) checkIdentifierLName(name string, offset int) {
  401. switch name {
  402. case "eval", "arguments":
  403. c.throwSyntaxError(offset, "Assignment to eval or arguments is not allowed in strict mode")
  404. }
  405. }