runtime.go 50 KB

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