runtime.go 34 KB

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