runtime.go 41 KB

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