runtime.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. package goja
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "go/ast"
  7. "math"
  8. "math/rand"
  9. "reflect"
  10. "strconv"
  11. js_ast "github.com/dop251/goja/ast"
  12. "github.com/dop251/goja/parser"
  13. )
  14. const (
  15. sqrt1_2 float64 = math.Sqrt2 / 2
  16. )
  17. var (
  18. typeCallable = reflect.TypeOf(Callable(nil))
  19. typeValue = reflect.TypeOf((*Value)(nil)).Elem()
  20. )
  21. type global struct {
  22. Object *Object
  23. Array *Object
  24. Function *Object
  25. String *Object
  26. Number *Object
  27. Boolean *Object
  28. RegExp *Object
  29. Date *Object
  30. ArrayBuffer *Object
  31. Error *Object
  32. TypeError *Object
  33. ReferenceError *Object
  34. SyntaxError *Object
  35. RangeError *Object
  36. EvalError *Object
  37. URIError *Object
  38. GoError *Object
  39. ObjectPrototype *Object
  40. ArrayPrototype *Object
  41. NumberPrototype *Object
  42. StringPrototype *Object
  43. BooleanPrototype *Object
  44. FunctionPrototype *Object
  45. RegExpPrototype *Object
  46. DatePrototype *Object
  47. ArrayBufferPrototype *Object
  48. ErrorPrototype *Object
  49. TypeErrorPrototype *Object
  50. SyntaxErrorPrototype *Object
  51. RangeErrorPrototype *Object
  52. ReferenceErrorPrototype *Object
  53. EvalErrorPrototype *Object
  54. URIErrorPrototype *Object
  55. GoErrorPrototype *Object
  56. Eval *Object
  57. thrower *Object
  58. throwerProperty Value
  59. }
  60. type Flag int
  61. const (
  62. FLAG_NOT_SET Flag = iota
  63. FLAG_FALSE
  64. FLAG_TRUE
  65. )
  66. func (f Flag) Bool() bool {
  67. return f == FLAG_TRUE
  68. }
  69. func ToFlag(b bool) Flag {
  70. if b {
  71. return FLAG_TRUE
  72. }
  73. return FLAG_FALSE
  74. }
  75. type RandSource func() float64
  76. type Runtime struct {
  77. global global
  78. globalObject *Object
  79. stringSingleton *stringObject
  80. rand RandSource
  81. typeInfoCache map[reflect.Type]*reflectTypeInfo
  82. fieldNameMapper FieldNameMapper
  83. vm *vm
  84. }
  85. type stackFrame struct {
  86. prg *Program
  87. funcName string
  88. pc int
  89. }
  90. func (f *stackFrame) position() Position {
  91. return f.prg.src.Position(f.prg.sourceOffset(f.pc))
  92. }
  93. func (f *stackFrame) write(b *bytes.Buffer) {
  94. if f.prg != nil {
  95. if n := f.prg.funcName; n != "" {
  96. b.WriteString(n)
  97. b.WriteString(" (")
  98. }
  99. if n := f.prg.src.name; n != "" {
  100. b.WriteString(n)
  101. } else {
  102. b.WriteString("<eval>")
  103. }
  104. b.WriteByte(':')
  105. b.WriteString(f.position().String())
  106. b.WriteByte('(')
  107. b.WriteString(strconv.Itoa(f.pc))
  108. b.WriteByte(')')
  109. if f.prg.funcName != "" {
  110. b.WriteByte(')')
  111. }
  112. } else {
  113. if f.funcName != "" {
  114. b.WriteString(f.funcName)
  115. b.WriteString(" (")
  116. }
  117. b.WriteString("native")
  118. if f.funcName != "" {
  119. b.WriteByte(')')
  120. }
  121. }
  122. }
  123. type Exception struct {
  124. val Value
  125. stack []stackFrame
  126. }
  127. type InterruptedError struct {
  128. Exception
  129. iface interface{}
  130. }
  131. func (e *InterruptedError) Value() interface{} {
  132. return e.iface
  133. }
  134. func (e *InterruptedError) String() string {
  135. if e == nil {
  136. return "<nil>"
  137. }
  138. var b bytes.Buffer
  139. if e.iface != nil {
  140. b.WriteString(fmt.Sprint(e.iface))
  141. b.WriteByte('\n')
  142. }
  143. e.writeFullStack(&b)
  144. return b.String()
  145. }
  146. func (e *InterruptedError) Error() string {
  147. if e == nil || e.iface == nil {
  148. return "<nil>"
  149. }
  150. var b bytes.Buffer
  151. b.WriteString(fmt.Sprint(e.iface))
  152. e.writeShortStack(&b)
  153. return b.String()
  154. }
  155. func (e *Exception) writeFullStack(b *bytes.Buffer) {
  156. for _, frame := range e.stack {
  157. b.WriteString("\tat ")
  158. frame.write(b)
  159. b.WriteByte('\n')
  160. }
  161. }
  162. func (e *Exception) writeShortStack(b *bytes.Buffer) {
  163. if len(e.stack) > 0 && (e.stack[0].prg != nil || e.stack[0].funcName != "") {
  164. b.WriteString(" at ")
  165. e.stack[0].write(b)
  166. }
  167. }
  168. func (e *Exception) String() string {
  169. if e == nil {
  170. return "<nil>"
  171. }
  172. var b bytes.Buffer
  173. if e.val != nil {
  174. b.WriteString(e.val.String())
  175. b.WriteByte('\n')
  176. }
  177. e.writeFullStack(&b)
  178. return b.String()
  179. }
  180. func (e *Exception) Error() string {
  181. if e == nil || e.val == nil {
  182. return "<nil>"
  183. }
  184. var b bytes.Buffer
  185. b.WriteString(e.val.String())
  186. e.writeShortStack(&b)
  187. return b.String()
  188. }
  189. func (e *Exception) Value() Value {
  190. return e.val
  191. }
  192. func (r *Runtime) addToGlobal(name string, value Value) {
  193. r.globalObject.self._putProp(name, value, true, false, true)
  194. }
  195. func (r *Runtime) init() {
  196. r.rand = rand.Float64
  197. r.global.ObjectPrototype = r.newBaseObject(nil, classObject).val
  198. r.globalObject = r.NewObject()
  199. r.vm = &vm{
  200. r: r,
  201. }
  202. r.vm.init()
  203. r.global.FunctionPrototype = r.newNativeFunc(nil, nil, "Empty", nil, 0)
  204. r.initObject()
  205. r.initFunction()
  206. r.initArray()
  207. r.initString()
  208. r.initNumber()
  209. r.initRegExp()
  210. r.initDate()
  211. r.initBoolean()
  212. r.initErrors()
  213. r.global.Eval = r.newNativeFunc(r.builtin_eval, nil, "eval", nil, 1)
  214. r.addToGlobal("eval", r.global.Eval)
  215. r.initGlobalObject()
  216. r.initMath()
  217. r.initJSON()
  218. //r.initTypedArrays()
  219. r.global.thrower = r.newNativeFunc(r.builtin_thrower, nil, "thrower", nil, 0)
  220. r.global.throwerProperty = &valueProperty{
  221. getterFunc: r.global.thrower,
  222. setterFunc: r.global.thrower,
  223. accessor: true,
  224. }
  225. }
  226. func (r *Runtime) typeErrorResult(throw bool, args ...interface{}) {
  227. if throw {
  228. panic(r.NewTypeError(args...))
  229. }
  230. }
  231. func (r *Runtime) newError(typ *Object, format string, args ...interface{}) Value {
  232. msg := fmt.Sprintf(format, args...)
  233. return r.builtin_new(typ, []Value{newStringValue(msg)})
  234. }
  235. func (r *Runtime) throwReferenceError(name string) {
  236. panic(r.newError(r.global.ReferenceError, "%s is not defined", name))
  237. }
  238. func (r *Runtime) newSyntaxError(msg string, offset int) Value {
  239. return r.builtin_new((r.global.SyntaxError), []Value{newStringValue(msg)})
  240. }
  241. func (r *Runtime) newArray(prototype *Object) (a *arrayObject) {
  242. v := &Object{runtime: r}
  243. a = &arrayObject{}
  244. a.class = classArray
  245. a.val = v
  246. a.extensible = true
  247. v.self = a
  248. a.prototype = prototype
  249. a.init()
  250. return
  251. }
  252. func (r *Runtime) newArrayObject() *arrayObject {
  253. return r.newArray(r.global.ArrayPrototype)
  254. }
  255. func (r *Runtime) newArrayValues(values []Value) *Object {
  256. v := &Object{runtime: r}
  257. a := &arrayObject{}
  258. a.class = classArray
  259. a.val = v
  260. a.extensible = true
  261. v.self = a
  262. a.prototype = r.global.ArrayPrototype
  263. a.init()
  264. a.values = values
  265. a.length = int64(len(values))
  266. a.objCount = a.length
  267. return v
  268. }
  269. func (r *Runtime) newArrayLength(l int64) *Object {
  270. a := r.newArrayValues(nil)
  271. a.self.putStr("length", intToValue(l), true)
  272. return a
  273. }
  274. func (r *Runtime) newBaseObject(proto *Object, class string) (o *baseObject) {
  275. v := &Object{runtime: r}
  276. o = &baseObject{}
  277. o.class = class
  278. o.val = v
  279. o.extensible = true
  280. v.self = o
  281. o.prototype = proto
  282. o.init()
  283. return
  284. }
  285. func (r *Runtime) NewObject() (v *Object) {
  286. return r.newBaseObject(r.global.ObjectPrototype, classObject).val
  287. }
  288. // CreateObject creates an object with given prototype. Equivalent of Object.create(proto).
  289. func (r *Runtime) CreateObject(proto *Object) *Object {
  290. return r.newBaseObject(proto, classObject).val
  291. }
  292. func (r *Runtime) NewTypeError(args ...interface{}) *Object {
  293. msg := ""
  294. if len(args) > 0 {
  295. f, _ := args[0].(string)
  296. msg = fmt.Sprintf(f, args[1:]...)
  297. }
  298. return r.builtin_new(r.global.TypeError, []Value{newStringValue(msg)})
  299. }
  300. func (r *Runtime) NewGoError(err error) *Object {
  301. e := r.newError(r.global.GoError, err.Error()).(*Object)
  302. e.Set("value", err)
  303. return e
  304. }
  305. func (r *Runtime) newFunc(name string, len int, strict bool) (f *funcObject) {
  306. v := &Object{runtime: r}
  307. f = &funcObject{}
  308. f.class = classFunction
  309. f.val = v
  310. f.extensible = true
  311. v.self = f
  312. f.prototype = r.global.FunctionPrototype
  313. f.init(name, len)
  314. if strict {
  315. f._put("caller", r.global.throwerProperty)
  316. f._put("arguments", r.global.throwerProperty)
  317. }
  318. return
  319. }
  320. func (r *Runtime) newNativeFuncObj(v *Object, call func(FunctionCall) Value, construct func(args []Value) *Object, name string, proto *Object, length int) *nativeFuncObject {
  321. f := &nativeFuncObject{
  322. baseFuncObject: baseFuncObject{
  323. baseObject: baseObject{
  324. class: classFunction,
  325. val: v,
  326. extensible: true,
  327. prototype: r.global.FunctionPrototype,
  328. },
  329. },
  330. f: call,
  331. construct: construct,
  332. }
  333. v.self = f
  334. f.init(name, length)
  335. if proto != nil {
  336. f._putProp("prototype", proto, false, false, false)
  337. }
  338. return f
  339. }
  340. func (r *Runtime) newNativeConstructor(call func(ConstructorCall) *Object, name string, length int) *Object {
  341. v := &Object{runtime: r}
  342. f := &nativeFuncObject{
  343. baseFuncObject: baseFuncObject{
  344. baseObject: baseObject{
  345. class: classFunction,
  346. val: v,
  347. extensible: true,
  348. prototype: r.global.FunctionPrototype,
  349. },
  350. },
  351. }
  352. f.f = func(c FunctionCall) Value {
  353. return f.defaultConstruct(call, c.Arguments)
  354. }
  355. f.construct = func(args []Value) *Object {
  356. return f.defaultConstruct(call, args)
  357. }
  358. v.self = f
  359. f.init(name, length)
  360. proto := r.NewObject()
  361. proto.self._putProp("constructor", v, true, false, true)
  362. f._putProp("prototype", proto, true, false, false)
  363. return v
  364. }
  365. func (r *Runtime) newNativeFunc(call func(FunctionCall) Value, construct func(args []Value) *Object, name string, proto *Object, length int) *Object {
  366. v := &Object{runtime: r}
  367. f := &nativeFuncObject{
  368. baseFuncObject: baseFuncObject{
  369. baseObject: baseObject{
  370. class: classFunction,
  371. val: v,
  372. extensible: true,
  373. prototype: r.global.FunctionPrototype,
  374. },
  375. },
  376. f: call,
  377. construct: construct,
  378. }
  379. v.self = f
  380. f.init(name, length)
  381. if proto != nil {
  382. f._putProp("prototype", proto, false, false, false)
  383. proto.self._putProp("constructor", v, true, false, true)
  384. }
  385. return v
  386. }
  387. func (r *Runtime) newNativeFuncConstructObj(v *Object, construct func(args []Value, proto *Object) *Object, name string, proto *Object, length int) *nativeFuncObject {
  388. f := &nativeFuncObject{
  389. baseFuncObject: baseFuncObject{
  390. baseObject: baseObject{
  391. class: classFunction,
  392. val: v,
  393. extensible: true,
  394. prototype: r.global.FunctionPrototype,
  395. },
  396. },
  397. f: r.constructWrap(construct, proto),
  398. construct: func(args []Value) *Object {
  399. return construct(args, proto)
  400. },
  401. }
  402. f.init(name, length)
  403. if proto != nil {
  404. f._putProp("prototype", proto, false, false, false)
  405. }
  406. return f
  407. }
  408. func (r *Runtime) newNativeFuncConstruct(construct func(args []Value, proto *Object) *Object, name string, prototype *Object, length int) *Object {
  409. return r.newNativeFuncConstructProto(construct, name, prototype, r.global.FunctionPrototype, length)
  410. }
  411. func (r *Runtime) newNativeFuncConstructProto(construct func(args []Value, proto *Object) *Object, name string, prototype, proto *Object, length int) *Object {
  412. v := &Object{runtime: r}
  413. f := &nativeFuncObject{}
  414. f.class = classFunction
  415. f.val = v
  416. f.extensible = true
  417. v.self = f
  418. f.prototype = proto
  419. f.f = r.constructWrap(construct, prototype)
  420. f.construct = func(args []Value) *Object {
  421. return construct(args, prototype)
  422. }
  423. f.init(name, length)
  424. if prototype != nil {
  425. f._putProp("prototype", prototype, false, false, false)
  426. prototype.self._putProp("constructor", v, true, false, true)
  427. }
  428. return v
  429. }
  430. func (r *Runtime) newPrimitiveObject(value Value, proto *Object, class string) *Object {
  431. v := &Object{runtime: r}
  432. o := &primitiveValueObject{}
  433. o.class = class
  434. o.val = v
  435. o.extensible = true
  436. v.self = o
  437. o.prototype = proto
  438. o.pValue = value
  439. o.init()
  440. return v
  441. }
  442. func (r *Runtime) builtin_Number(call FunctionCall) Value {
  443. if len(call.Arguments) > 0 {
  444. return call.Arguments[0].ToNumber()
  445. } else {
  446. return intToValue(0)
  447. }
  448. }
  449. func (r *Runtime) builtin_newNumber(args []Value) *Object {
  450. var v Value
  451. if len(args) > 0 {
  452. v = args[0].ToNumber()
  453. } else {
  454. v = intToValue(0)
  455. }
  456. return r.newPrimitiveObject(v, r.global.NumberPrototype, classNumber)
  457. }
  458. func (r *Runtime) builtin_Boolean(call FunctionCall) Value {
  459. if len(call.Arguments) > 0 {
  460. if call.Arguments[0].ToBoolean() {
  461. return valueTrue
  462. } else {
  463. return valueFalse
  464. }
  465. } else {
  466. return valueFalse
  467. }
  468. }
  469. func (r *Runtime) builtin_newBoolean(args []Value) *Object {
  470. var v Value
  471. if len(args) > 0 {
  472. if args[0].ToBoolean() {
  473. v = valueTrue
  474. } else {
  475. v = valueFalse
  476. }
  477. } else {
  478. v = valueFalse
  479. }
  480. return r.newPrimitiveObject(v, r.global.BooleanPrototype, classBoolean)
  481. }
  482. func (r *Runtime) error_toString(call FunctionCall) Value {
  483. obj := call.This.ToObject(r).self
  484. msg := obj.getStr("message")
  485. name := obj.getStr("name")
  486. var nameStr, msgStr string
  487. if name != nil && name != _undefined {
  488. nameStr = name.String()
  489. }
  490. if msg != nil && msg != _undefined {
  491. msgStr = msg.String()
  492. }
  493. if nameStr != "" && msgStr != "" {
  494. return newStringValue(fmt.Sprintf("%s: %s", name.String(), msgStr))
  495. } else {
  496. if nameStr != "" {
  497. return name.ToString()
  498. } else {
  499. return msg.ToString()
  500. }
  501. }
  502. }
  503. func (r *Runtime) builtin_Error(args []Value, proto *Object) *Object {
  504. obj := r.newBaseObject(proto, classError)
  505. if len(args) > 0 && args[0] != _undefined {
  506. obj._putProp("message", args[0], true, false, true)
  507. }
  508. return obj.val
  509. }
  510. func (r *Runtime) builtin_new(construct *Object, args []Value) *Object {
  511. repeat:
  512. switch f := construct.self.(type) {
  513. case *nativeFuncObject:
  514. if f.construct != nil {
  515. return f.construct(args)
  516. } else {
  517. panic("Not a constructor")
  518. }
  519. case *boundFuncObject:
  520. if f.construct != nil {
  521. return f.construct(args)
  522. } else {
  523. panic("Not a constructor")
  524. }
  525. case *funcObject:
  526. // TODO: implement
  527. panic("Not implemented")
  528. case *lazyObject:
  529. construct.self = f.create(construct)
  530. goto repeat
  531. default:
  532. panic("Not a constructor")
  533. }
  534. }
  535. func (r *Runtime) throw(e Value) {
  536. panic(e)
  537. }
  538. func (r *Runtime) builtin_thrower(call FunctionCall) Value {
  539. r.typeErrorResult(true, "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them")
  540. return nil
  541. }
  542. func (r *Runtime) eval(src string, direct, strict bool, this Value) Value {
  543. p, err := r.compile("<eval>", src, strict, true)
  544. if err != nil {
  545. panic(err)
  546. }
  547. vm := r.vm
  548. vm.pushCtx()
  549. vm.prg = p
  550. vm.pc = 0
  551. if !direct {
  552. vm.stash = nil
  553. }
  554. vm.sb = vm.sp
  555. vm.push(this)
  556. if strict {
  557. vm.push(valueTrue)
  558. } else {
  559. vm.push(valueFalse)
  560. }
  561. vm.run()
  562. vm.popCtx()
  563. vm.halt = false
  564. retval := vm.stack[vm.sp-1]
  565. vm.sp -= 2
  566. return retval
  567. }
  568. func (r *Runtime) builtin_eval(call FunctionCall) Value {
  569. if len(call.Arguments) == 0 {
  570. return _undefined
  571. }
  572. if str, ok := call.Arguments[0].assertString(); ok {
  573. return r.eval(str.String(), false, false, r.globalObject)
  574. }
  575. return call.Arguments[0]
  576. }
  577. func (r *Runtime) constructWrap(construct func(args []Value, proto *Object) *Object, proto *Object) func(call FunctionCall) Value {
  578. return func(call FunctionCall) Value {
  579. return construct(call.Arguments, proto)
  580. }
  581. }
  582. func (r *Runtime) toCallable(v Value) func(FunctionCall) Value {
  583. if call, ok := r.toObject(v).self.assertCallable(); ok {
  584. return call
  585. }
  586. r.typeErrorResult(true, "Value is not callable: %s", v.ToString())
  587. return nil
  588. }
  589. func (r *Runtime) checkObjectCoercible(v Value) {
  590. switch v.(type) {
  591. case valueUndefined, valueNull:
  592. r.typeErrorResult(true, "Value is not object coercible")
  593. }
  594. }
  595. func toUInt32(v Value) uint32 {
  596. v = v.ToNumber()
  597. if i, ok := v.assertInt(); ok {
  598. return uint32(i)
  599. }
  600. if f, ok := v.assertFloat(); ok {
  601. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  602. return uint32(int64(f))
  603. }
  604. }
  605. return 0
  606. }
  607. func toUInt16(v Value) uint16 {
  608. v = v.ToNumber()
  609. if i, ok := v.assertInt(); ok {
  610. return uint16(i)
  611. }
  612. if f, ok := v.assertFloat(); ok {
  613. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  614. return uint16(int64(f))
  615. }
  616. }
  617. return 0
  618. }
  619. func toLength(v Value) int64 {
  620. if v == nil {
  621. return 0
  622. }
  623. i := v.ToInteger()
  624. if i < 0 {
  625. return 0
  626. }
  627. if i >= maxInt {
  628. return maxInt - 1
  629. }
  630. return i
  631. }
  632. func toInt32(v Value) int32 {
  633. v = v.ToNumber()
  634. if i, ok := v.assertInt(); ok {
  635. return int32(i)
  636. }
  637. if f, ok := v.assertFloat(); ok {
  638. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  639. return int32(int64(f))
  640. }
  641. }
  642. return 0
  643. }
  644. func (r *Runtime) toBoolean(b bool) Value {
  645. if b {
  646. return valueTrue
  647. } else {
  648. return valueFalse
  649. }
  650. }
  651. // New creates an instance of a Javascript runtime that can be used to run code. Multiple instances may be created and
  652. // used simultaneously, however it is not possible to pass JS values across runtimes.
  653. func New() *Runtime {
  654. r := &Runtime{}
  655. r.init()
  656. return r
  657. }
  658. // Compile creates an internal representation of the JavaScript code that can be later run using the Runtime.RunProgram()
  659. // method. This representation is not linked to a runtime in any way and can be run in multiple runtimes (possibly
  660. // at the same time).
  661. func Compile(name, src string, strict bool) (*Program, error) {
  662. return compile(name, src, strict, false)
  663. }
  664. // CompileAST creates an internal representation of the JavaScript code that can be later run using the Runtime.RunProgram()
  665. // method. This representation is not linked to a runtime in any way and can be run in multiple runtimes (possibly
  666. // at the same time).
  667. func CompileAST(prg *js_ast.Program, strict bool) (*Program, error) {
  668. return compileAST(prg, strict, false)
  669. }
  670. // MustCompile is like Compile but panics if the code cannot be compiled.
  671. // It simplifies safe initialization of global variables holding compiled JavaScript code.
  672. func MustCompile(name, src string, strict bool) *Program {
  673. prg, err := Compile(name, src, strict)
  674. if err != nil {
  675. panic(err)
  676. }
  677. return prg
  678. }
  679. func compile(name, src string, strict, eval bool) (p *Program, err error) {
  680. prg, err1 := parser.ParseFile(nil, name, src, 0)
  681. if err1 != nil {
  682. switch err1 := err1.(type) {
  683. case parser.ErrorList:
  684. if len(err1) > 0 && err1[0].Message == "Invalid left-hand side in assignment" {
  685. err = &CompilerReferenceError{
  686. CompilerError: CompilerError{
  687. Message: err1.Error(),
  688. },
  689. }
  690. return
  691. }
  692. }
  693. // FIXME offset
  694. err = &CompilerSyntaxError{
  695. CompilerError: CompilerError{
  696. Message: err1.Error(),
  697. },
  698. }
  699. return
  700. }
  701. p, err = compileAST(prg, strict, eval)
  702. return
  703. }
  704. func compileAST(prg *js_ast.Program, strict, eval bool) (p *Program, err error) {
  705. c := newCompiler()
  706. c.scope.strict = strict
  707. c.scope.eval = eval
  708. defer func() {
  709. if x := recover(); x != nil {
  710. p = nil
  711. switch x1 := x.(type) {
  712. case *CompilerSyntaxError:
  713. err = x1
  714. default:
  715. panic(x)
  716. }
  717. }
  718. }()
  719. c.compile(prg)
  720. p = c.p
  721. return
  722. }
  723. func (r *Runtime) compile(name, src string, strict, eval bool) (p *Program, err error) {
  724. p, err = compile(name, src, strict, eval)
  725. if err != nil {
  726. switch x1 := err.(type) {
  727. case *CompilerSyntaxError:
  728. err = &Exception{
  729. val: r.builtin_new(r.global.SyntaxError, []Value{newStringValue(x1.Error())}),
  730. }
  731. case *CompilerReferenceError:
  732. err = &Exception{
  733. val: r.newError(r.global.ReferenceError, x1.Message),
  734. } // TODO proper message
  735. }
  736. }
  737. return
  738. }
  739. // RunString executes the given string in the global context.
  740. func (r *Runtime) RunString(str string) (Value, error) {
  741. return r.RunScript("", str)
  742. }
  743. // RunScript executes the given string in the global context.
  744. func (r *Runtime) RunScript(name, src string) (Value, error) {
  745. p, err := Compile(name, src, false)
  746. if err != nil {
  747. return nil, err
  748. }
  749. return r.RunProgram(p)
  750. }
  751. // RunProgram executes a pre-compiled (see Compile()) code in the global context.
  752. func (r *Runtime) RunProgram(p *Program) (result Value, err error) {
  753. defer func() {
  754. if x := recover(); x != nil {
  755. if intr, ok := x.(*InterruptedError); ok {
  756. err = intr
  757. } else {
  758. panic(x)
  759. }
  760. }
  761. }()
  762. recursive := false
  763. if len(r.vm.callStack) > 0 {
  764. recursive = true
  765. r.vm.pushCtx()
  766. }
  767. r.vm.prg = p
  768. r.vm.pc = 0
  769. ex := r.vm.runTry()
  770. if ex == nil {
  771. result = r.vm.pop()
  772. } else {
  773. err = ex
  774. }
  775. if recursive {
  776. r.vm.popCtx()
  777. r.vm.halt = false
  778. r.vm.clearStack()
  779. } else {
  780. r.vm.stack = nil
  781. }
  782. return
  783. }
  784. // Interrupt a running JavaScript. The corresponding Go call will return an *InterruptedError containing v.
  785. // Note, it only works while in JavaScript code, it does not interrupt native Go functions (which includes all built-ins).
  786. func (r *Runtime) Interrupt(v interface{}) {
  787. r.vm.Interrupt(v)
  788. }
  789. /*
  790. ToValue converts a Go value into JavaScript value.
  791. Primitive types (ints and uints, floats, string, bool) are converted to the corresponding JavaScript primitives.
  792. func(FunctionCall) Value is treated as a native JavaScript function.
  793. map[string]interface{} is converted into a host object that largely behaves like a JavaScript Object.
  794. []interface{} is converted into a host object that behaves largely like a JavaScript Array, however it's not extensible
  795. because extending it can change the pointer so it becomes detached from the original.
  796. *[]interface{} same as above, but the array becomes extensible.
  797. A function is wrapped within a native JavaScript function. When called the arguments are automatically converted to
  798. the appropriate Go types. If conversion is not possible, a TypeError is thrown.
  799. A slice type is converted into a generic reflect based host object that behaves similar to an unexpandable Array.
  800. Any other type is converted to a generic reflect based host object. Depending on the underlying type it behaves similar
  801. to a Number, String, Boolean or Object.
  802. Note that the underlying type is not lost, calling Export() returns the original Go value. This applies to all
  803. reflect based types.
  804. */
  805. func (r *Runtime) ToValue(i interface{}) Value {
  806. switch i := i.(type) {
  807. case nil:
  808. return _null
  809. case Value:
  810. // TODO: prevent importing Objects from a different runtime
  811. return i
  812. case string:
  813. return newStringValue(i)
  814. case bool:
  815. if i {
  816. return valueTrue
  817. } else {
  818. return valueFalse
  819. }
  820. case func(FunctionCall) Value:
  821. return r.newNativeFunc(i, nil, "", nil, 0)
  822. case func(ConstructorCall) *Object:
  823. return r.newNativeConstructor(i, "", 0)
  824. case int:
  825. return intToValue(int64(i))
  826. case int8:
  827. return intToValue(int64(i))
  828. case int16:
  829. return intToValue(int64(i))
  830. case int32:
  831. return intToValue(int64(i))
  832. case int64:
  833. return intToValue(i)
  834. case uint:
  835. if int64(i) <= math.MaxInt64 {
  836. return intToValue(int64(i))
  837. } else {
  838. return floatToValue(float64(i))
  839. }
  840. case uint8:
  841. return intToValue(int64(i))
  842. case uint16:
  843. return intToValue(int64(i))
  844. case uint32:
  845. return intToValue(int64(i))
  846. case uint64:
  847. if i <= math.MaxInt64 {
  848. return intToValue(int64(i))
  849. }
  850. return floatToValue(float64(i))
  851. case float32:
  852. return floatToValue(float64(i))
  853. case float64:
  854. return floatToValue(i)
  855. case map[string]interface{}:
  856. obj := &Object{runtime: r}
  857. m := &objectGoMapSimple{
  858. baseObject: baseObject{
  859. val: obj,
  860. extensible: true,
  861. },
  862. data: i,
  863. }
  864. obj.self = m
  865. m.init()
  866. return obj
  867. case []interface{}:
  868. obj := &Object{runtime: r}
  869. a := &objectGoSlice{
  870. baseObject: baseObject{
  871. val: obj,
  872. },
  873. data: &i,
  874. }
  875. obj.self = a
  876. a.init()
  877. return obj
  878. case *[]interface{}:
  879. obj := &Object{runtime: r}
  880. a := &objectGoSlice{
  881. baseObject: baseObject{
  882. val: obj,
  883. },
  884. data: i,
  885. sliceExtensible: true,
  886. }
  887. obj.self = a
  888. a.init()
  889. return obj
  890. }
  891. origValue := reflect.ValueOf(i)
  892. value := origValue
  893. for value.Kind() == reflect.Ptr {
  894. value = reflect.Indirect(value)
  895. }
  896. if !value.IsValid() {
  897. return _null
  898. }
  899. switch value.Kind() {
  900. case reflect.Map:
  901. if value.Type().NumMethod() == 0 {
  902. switch value.Type().Key().Kind() {
  903. case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  904. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
  905. reflect.Float64, reflect.Float32:
  906. obj := &Object{runtime: r}
  907. m := &objectGoMapReflect{
  908. objectGoReflect: objectGoReflect{
  909. baseObject: baseObject{
  910. val: obj,
  911. extensible: true,
  912. },
  913. origValue: origValue,
  914. value: value,
  915. },
  916. }
  917. m.init()
  918. obj.self = m
  919. return obj
  920. }
  921. }
  922. case reflect.Slice:
  923. obj := &Object{runtime: r}
  924. a := &objectGoSliceReflect{
  925. objectGoReflect: objectGoReflect{
  926. baseObject: baseObject{
  927. val: obj,
  928. },
  929. origValue: origValue,
  930. value: value,
  931. },
  932. }
  933. a.init()
  934. obj.self = a
  935. return obj
  936. case reflect.Func:
  937. return r.newNativeFunc(r.wrapReflectFunc(value), nil, "", nil, value.Type().NumIn())
  938. }
  939. obj := &Object{runtime: r}
  940. o := &objectGoReflect{
  941. baseObject: baseObject{
  942. val: obj,
  943. },
  944. origValue: origValue,
  945. value: value,
  946. }
  947. obj.self = o
  948. o.init()
  949. return obj
  950. }
  951. func (r *Runtime) wrapReflectFunc(value reflect.Value) func(FunctionCall) Value {
  952. return func(call FunctionCall) Value {
  953. typ := value.Type()
  954. nargs := typ.NumIn()
  955. var in []reflect.Value
  956. if l := len(call.Arguments); l < nargs {
  957. // fill missing arguments with zero values
  958. n := nargs
  959. if typ.IsVariadic() {
  960. n--
  961. }
  962. in = make([]reflect.Value, n)
  963. for i := l; i < n; i++ {
  964. in[i] = reflect.Zero(typ.In(i))
  965. }
  966. } else {
  967. if l > nargs && !typ.IsVariadic() {
  968. l = nargs
  969. }
  970. in = make([]reflect.Value, l)
  971. }
  972. callSlice := false
  973. for i, a := range call.Arguments {
  974. var t reflect.Type
  975. n := i
  976. if n >= nargs-1 && typ.IsVariadic() {
  977. if n > nargs-1 {
  978. n = nargs - 1
  979. }
  980. t = typ.In(n).Elem()
  981. } else if n > nargs-1 { // ignore extra arguments
  982. break
  983. } else {
  984. t = typ.In(n)
  985. }
  986. // if this is a variadic Go function, and the caller has supplied
  987. // exactly the number of JavaScript arguments required, and this
  988. // is the last JavaScript argument, try treating the it as the
  989. // actual set of variadic Go arguments. if that succeeds, break
  990. // out of the loop.
  991. if typ.IsVariadic() && len(call.Arguments) == nargs && i == nargs-1 {
  992. if v, err := r.toReflectValue(a, typ.In(n)); err == nil {
  993. in[i] = v
  994. callSlice = true
  995. break
  996. }
  997. }
  998. var err error
  999. in[i], err = r.toReflectValue(a, t)
  1000. if err != nil {
  1001. panic(r.newError(r.global.TypeError, "Could not convert function call parameter %v to %v", a, t))
  1002. }
  1003. }
  1004. var out []reflect.Value
  1005. if callSlice {
  1006. out = value.CallSlice(in)
  1007. } else {
  1008. out = value.Call(in)
  1009. }
  1010. if len(out) == 0 {
  1011. return _undefined
  1012. }
  1013. if last := out[len(out)-1]; last.Type().Name() == "error" {
  1014. if !last.IsNil() {
  1015. err := last.Interface()
  1016. if _, ok := err.(*Exception); ok {
  1017. panic(err)
  1018. }
  1019. panic(r.NewGoError(last.Interface().(error)))
  1020. }
  1021. out = out[:len(out)-1]
  1022. }
  1023. switch len(out) {
  1024. case 0:
  1025. return _undefined
  1026. case 1:
  1027. return r.ToValue(out[0].Interface())
  1028. default:
  1029. s := make([]interface{}, len(out))
  1030. for i, v := range out {
  1031. s[i] = v.Interface()
  1032. }
  1033. return r.ToValue(s)
  1034. }
  1035. }
  1036. }
  1037. func (r *Runtime) toReflectValue(v Value, typ reflect.Type) (reflect.Value, error) {
  1038. switch typ.Kind() {
  1039. case reflect.String:
  1040. return reflect.ValueOf(v.String()).Convert(typ), nil
  1041. case reflect.Bool:
  1042. return reflect.ValueOf(v.ToBoolean()).Convert(typ), nil
  1043. case reflect.Int:
  1044. i, _ := toInt(v)
  1045. return reflect.ValueOf(int(i)).Convert(typ), nil
  1046. case reflect.Int64:
  1047. i, _ := toInt(v)
  1048. return reflect.ValueOf(i).Convert(typ), nil
  1049. case reflect.Int32:
  1050. i, _ := toInt(v)
  1051. return reflect.ValueOf(int32(i)).Convert(typ), nil
  1052. case reflect.Int16:
  1053. i, _ := toInt(v)
  1054. return reflect.ValueOf(int16(i)).Convert(typ), nil
  1055. case reflect.Int8:
  1056. i, _ := toInt(v)
  1057. return reflect.ValueOf(int8(i)).Convert(typ), nil
  1058. case reflect.Uint:
  1059. i, _ := toInt(v)
  1060. return reflect.ValueOf(uint(i)).Convert(typ), nil
  1061. case reflect.Uint64:
  1062. i, _ := toInt(v)
  1063. return reflect.ValueOf(uint64(i)).Convert(typ), nil
  1064. case reflect.Uint32:
  1065. i, _ := toInt(v)
  1066. return reflect.ValueOf(uint32(i)).Convert(typ), nil
  1067. case reflect.Uint16:
  1068. i, _ := toInt(v)
  1069. return reflect.ValueOf(uint16(i)).Convert(typ), nil
  1070. case reflect.Uint8:
  1071. i, _ := toInt(v)
  1072. return reflect.ValueOf(uint8(i)).Convert(typ), nil
  1073. }
  1074. if typ == typeCallable {
  1075. if fn, ok := AssertFunction(v); ok {
  1076. return reflect.ValueOf(fn), nil
  1077. }
  1078. }
  1079. if typ.Implements(typeValue) {
  1080. return reflect.ValueOf(v), nil
  1081. }
  1082. et := v.ExportType()
  1083. if et == nil {
  1084. return reflect.Zero(typ), nil
  1085. }
  1086. if et.AssignableTo(typ) {
  1087. return reflect.ValueOf(v.Export()), nil
  1088. } else if et.ConvertibleTo(typ) {
  1089. return reflect.ValueOf(v.Export()).Convert(typ), nil
  1090. }
  1091. switch typ.Kind() {
  1092. case reflect.Slice:
  1093. if o, ok := v.(*Object); ok {
  1094. if o.self.className() == classArray {
  1095. l := int(toLength(o.self.getStr("length")))
  1096. s := reflect.MakeSlice(typ, l, l)
  1097. elemTyp := typ.Elem()
  1098. for i := 0; i < l; i++ {
  1099. item := o.self.get(intToValue(int64(i)))
  1100. itemval, err := r.toReflectValue(item, elemTyp)
  1101. if err != nil {
  1102. return reflect.Value{}, fmt.Errorf("Could not convert array element %v to %v at %d", v, typ, i)
  1103. }
  1104. s.Index(i).Set(itemval)
  1105. }
  1106. return s, nil
  1107. }
  1108. }
  1109. case reflect.Map:
  1110. if o, ok := v.(*Object); ok {
  1111. m := reflect.MakeMap(typ)
  1112. keyTyp := typ.Key()
  1113. elemTyp := typ.Elem()
  1114. needConvertKeys := !reflect.ValueOf("").Type().AssignableTo(keyTyp)
  1115. for item, f := o.self.enumerate(false, false)(); f != nil; item, f = f() {
  1116. var kv reflect.Value
  1117. var err error
  1118. if needConvertKeys {
  1119. kv, err = r.toReflectValue(newStringValue(item.name), keyTyp)
  1120. if err != nil {
  1121. return reflect.Value{}, fmt.Errorf("Could not convert map key %s to %v", item.name, typ)
  1122. }
  1123. } else {
  1124. kv = reflect.ValueOf(item.name)
  1125. }
  1126. ival := item.value
  1127. if ival == nil {
  1128. ival = o.self.getStr(item.name)
  1129. }
  1130. if ival != nil {
  1131. vv, err := r.toReflectValue(ival, elemTyp)
  1132. if err != nil {
  1133. return reflect.Value{}, fmt.Errorf("Could not convert map value %v to %v at key %s", ival, typ, item.name)
  1134. }
  1135. m.SetMapIndex(kv, vv)
  1136. } else {
  1137. m.SetMapIndex(kv, reflect.Zero(elemTyp))
  1138. }
  1139. }
  1140. return m, nil
  1141. }
  1142. case reflect.Struct:
  1143. if o, ok := v.(*Object); ok {
  1144. s := reflect.New(typ).Elem()
  1145. for i := 0; i < typ.NumField(); i++ {
  1146. field := typ.Field(i)
  1147. if ast.IsExported(field.Name) {
  1148. v := o.self.getStr(field.Name)
  1149. if v != nil {
  1150. vv, err := r.toReflectValue(v, field.Type)
  1151. if err != nil {
  1152. return reflect.Value{}, fmt.Errorf("Could not convert struct value %v to %v for field %s", v, field.Type, field.Name)
  1153. }
  1154. s.Field(i).Set(vv)
  1155. }
  1156. }
  1157. }
  1158. return s, nil
  1159. }
  1160. case reflect.Func:
  1161. if fn, ok := AssertFunction(v); ok {
  1162. return reflect.MakeFunc(typ, r.wrapJSFunc(fn, typ)), nil
  1163. }
  1164. }
  1165. return reflect.Value{}, fmt.Errorf("Could not convert %v to %v", v, typ)
  1166. }
  1167. func (r *Runtime) wrapJSFunc(fn Callable, typ reflect.Type) func(args []reflect.Value) (results []reflect.Value) {
  1168. return func(args []reflect.Value) (results []reflect.Value) {
  1169. jsArgs := make([]Value, len(args))
  1170. for i, arg := range args {
  1171. jsArgs[i] = r.ToValue(arg.Interface())
  1172. }
  1173. results = make([]reflect.Value, typ.NumOut())
  1174. res, err := fn(_undefined, jsArgs...)
  1175. if err == nil {
  1176. if typ.NumOut() > 0 {
  1177. results[0], err = r.toReflectValue(res, typ.Out(0))
  1178. }
  1179. }
  1180. if err != nil {
  1181. if typ.NumOut() == 2 && typ.Out(1).Name() == "error" {
  1182. results[1] = reflect.ValueOf(err).Convert(typ.Out(1))
  1183. } else {
  1184. panic(err)
  1185. }
  1186. }
  1187. for i, v := range results {
  1188. if !v.IsValid() {
  1189. results[i] = reflect.Zero(typ.Out(i))
  1190. }
  1191. }
  1192. return
  1193. }
  1194. }
  1195. // ExportTo converts a JavaScript value into the specified Go value. The second parameter must be a non-nil pointer.
  1196. // Returns error if conversion is not possible.
  1197. func (r *Runtime) ExportTo(v Value, target interface{}) error {
  1198. tval := reflect.ValueOf(target)
  1199. if tval.Kind() != reflect.Ptr || tval.IsNil() {
  1200. return errors.New("target must be a non-nil pointer")
  1201. }
  1202. vv, err := r.toReflectValue(v, tval.Elem().Type())
  1203. if err != nil {
  1204. return err
  1205. }
  1206. tval.Elem().Set(vv)
  1207. return nil
  1208. }
  1209. // GlobalObject returns the global object.
  1210. func (r *Runtime) GlobalObject() *Object {
  1211. return r.globalObject
  1212. }
  1213. // Set the specified value as a property of the global object.
  1214. // The value is first converted using ToValue()
  1215. func (r *Runtime) Set(name string, value interface{}) {
  1216. r.globalObject.self.putStr(name, r.ToValue(value), false)
  1217. }
  1218. // Get the specified property of the global object.
  1219. func (r *Runtime) Get(name string) Value {
  1220. return r.globalObject.self.getStr(name)
  1221. }
  1222. // SetRandSource sets random source for this Runtime. If not called, the default math/rand is used.
  1223. func (r *Runtime) SetRandSource(source RandSource) {
  1224. r.rand = source
  1225. }
  1226. // Callable represents a JavaScript function that can be called from Go.
  1227. type Callable func(this Value, args ...Value) (Value, error)
  1228. // AssertFunction checks if the Value is a function and returns a Callable.
  1229. func AssertFunction(v Value) (Callable, bool) {
  1230. if obj, ok := v.(*Object); ok {
  1231. if f, ok := obj.self.assertCallable(); ok {
  1232. return func(this Value, args ...Value) (ret Value, err error) {
  1233. defer func() {
  1234. if x := recover(); x != nil {
  1235. if ex, ok := x.(*InterruptedError); ok {
  1236. err = ex
  1237. } else {
  1238. panic(x)
  1239. }
  1240. }
  1241. }()
  1242. ex := obj.runtime.vm.try(func() {
  1243. ret = f(FunctionCall{
  1244. This: this,
  1245. Arguments: args,
  1246. })
  1247. })
  1248. if ex != nil {
  1249. err = ex
  1250. }
  1251. obj.runtime.vm.clearStack()
  1252. return
  1253. }, true
  1254. }
  1255. }
  1256. return nil, false
  1257. }
  1258. // IsUndefined returns true if the supplied Value is undefined. Note, it checks against the real undefined, not
  1259. // against the global object's 'undefined' property.
  1260. func IsUndefined(v Value) bool {
  1261. return v == _undefined
  1262. }
  1263. // IsNull returns true if the supplied Value is null.
  1264. func IsNull(v Value) bool {
  1265. return v == _null
  1266. }
  1267. // Undefined returns JS undefined value. Note if global 'undefined' property is changed this still returns the original value.
  1268. func Undefined() Value {
  1269. return _undefined
  1270. }
  1271. // Null returns JS null value.
  1272. func Null() Value {
  1273. return _undefined
  1274. }
  1275. func tryFunc(f func()) (err error) {
  1276. defer func() {
  1277. if x := recover(); x != nil {
  1278. switch x := x.(type) {
  1279. case *Exception:
  1280. err = x
  1281. case *InterruptedError:
  1282. err = x
  1283. case Value:
  1284. err = &Exception{
  1285. val: x,
  1286. }
  1287. default:
  1288. panic(x)
  1289. }
  1290. }
  1291. }()
  1292. f()
  1293. return nil
  1294. }