runtime.go 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880
  1. package goja
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "github.com/dop251/goja/file"
  7. "go/ast"
  8. "hash/maphash"
  9. "math"
  10. "math/bits"
  11. "math/rand"
  12. "reflect"
  13. "runtime"
  14. "strconv"
  15. "time"
  16. "golang.org/x/text/collate"
  17. js_ast "github.com/dop251/goja/ast"
  18. "github.com/dop251/goja/parser"
  19. "github.com/dop251/goja/unistring"
  20. )
  21. const (
  22. sqrt1_2 float64 = math.Sqrt2 / 2
  23. deoptimiseRegexp = false
  24. )
  25. var (
  26. typeCallable = reflect.TypeOf(Callable(nil))
  27. typeValue = reflect.TypeOf((*Value)(nil)).Elem()
  28. typeObject = reflect.TypeOf((*Object)(nil))
  29. typeTime = reflect.TypeOf(time.Time{})
  30. typeBytes = reflect.TypeOf(([]byte)(nil))
  31. )
  32. type iterationKind int
  33. const (
  34. iterationKindKey iterationKind = iota
  35. iterationKindValue
  36. iterationKindKeyValue
  37. )
  38. type global struct {
  39. stash stash
  40. varNames map[unistring.String]struct{}
  41. Object *Object
  42. Array *Object
  43. Function *Object
  44. String *Object
  45. Number *Object
  46. Boolean *Object
  47. RegExp *Object
  48. Date *Object
  49. Symbol *Object
  50. Proxy *Object
  51. Promise *Object
  52. ArrayBuffer *Object
  53. DataView *Object
  54. TypedArray *Object
  55. Uint8Array *Object
  56. Uint8ClampedArray *Object
  57. Int8Array *Object
  58. Uint16Array *Object
  59. Int16Array *Object
  60. Uint32Array *Object
  61. Int32Array *Object
  62. Float32Array *Object
  63. Float64Array *Object
  64. WeakSet *Object
  65. WeakMap *Object
  66. Map *Object
  67. Set *Object
  68. Error *Object
  69. AggregateError *Object
  70. TypeError *Object
  71. ReferenceError *Object
  72. SyntaxError *Object
  73. RangeError *Object
  74. EvalError *Object
  75. URIError *Object
  76. GoError *Object
  77. ObjectPrototype *Object
  78. ArrayPrototype *Object
  79. NumberPrototype *Object
  80. StringPrototype *Object
  81. BooleanPrototype *Object
  82. FunctionPrototype *Object
  83. RegExpPrototype *Object
  84. DatePrototype *Object
  85. SymbolPrototype *Object
  86. ArrayBufferPrototype *Object
  87. DataViewPrototype *Object
  88. TypedArrayPrototype *Object
  89. WeakSetPrototype *Object
  90. WeakMapPrototype *Object
  91. MapPrototype *Object
  92. SetPrototype *Object
  93. PromisePrototype *Object
  94. IteratorPrototype *Object
  95. ArrayIteratorPrototype *Object
  96. MapIteratorPrototype *Object
  97. SetIteratorPrototype *Object
  98. StringIteratorPrototype *Object
  99. RegExpStringIteratorPrototype *Object
  100. ErrorPrototype *Object
  101. AggregateErrorPrototype *Object
  102. TypeErrorPrototype *Object
  103. SyntaxErrorPrototype *Object
  104. RangeErrorPrototype *Object
  105. ReferenceErrorPrototype *Object
  106. EvalErrorPrototype *Object
  107. URIErrorPrototype *Object
  108. GoErrorPrototype *Object
  109. Eval *Object
  110. thrower *Object
  111. throwerProperty Value
  112. stdRegexpProto *guardedObject
  113. weakSetAdder *Object
  114. weakMapAdder *Object
  115. mapAdder *Object
  116. setAdder *Object
  117. arrayValues *Object
  118. arrayToString *Object
  119. }
  120. type Flag int
  121. const (
  122. FLAG_NOT_SET Flag = iota
  123. FLAG_FALSE
  124. FLAG_TRUE
  125. )
  126. func (f Flag) Bool() bool {
  127. return f == FLAG_TRUE
  128. }
  129. func ToFlag(b bool) Flag {
  130. if b {
  131. return FLAG_TRUE
  132. }
  133. return FLAG_FALSE
  134. }
  135. type RandSource func() float64
  136. type Now func() time.Time
  137. type Runtime struct {
  138. global global
  139. globalObject *Object
  140. stringSingleton *stringObject
  141. rand RandSource
  142. now Now
  143. _collator *collate.Collator
  144. parserOptions []parser.Option
  145. symbolRegistry map[unistring.String]*Symbol
  146. typeInfoCache map[reflect.Type]*reflectTypeInfo
  147. fieldNameMapper FieldNameMapper
  148. vm *vm
  149. hash *maphash.Hash
  150. idSeq uint64
  151. jobQueue []func()
  152. promiseRejectionTracker PromiseRejectionTracker
  153. }
  154. type StackFrame struct {
  155. prg *Program
  156. funcName unistring.String
  157. pc int
  158. }
  159. func (f *StackFrame) SrcName() string {
  160. if f.prg == nil {
  161. return "<native>"
  162. }
  163. return f.prg.src.Name()
  164. }
  165. func (f *StackFrame) FuncName() string {
  166. if f.funcName == "" && f.prg == nil {
  167. return "<native>"
  168. }
  169. if f.funcName == "" {
  170. return "<anonymous>"
  171. }
  172. return f.funcName.String()
  173. }
  174. func (f *StackFrame) Position() file.Position {
  175. if f.prg == nil || f.prg.src == nil {
  176. return file.Position{}
  177. }
  178. return f.prg.src.Position(f.prg.sourceOffset(f.pc))
  179. }
  180. func (f *StackFrame) Write(b *bytes.Buffer) {
  181. if f.prg != nil {
  182. if n := f.prg.funcName; n != "" {
  183. b.WriteString(n.String())
  184. b.WriteString(" (")
  185. }
  186. p := f.Position()
  187. if p.Filename != "" {
  188. b.WriteString(p.Filename)
  189. } else {
  190. b.WriteString("<eval>")
  191. }
  192. b.WriteByte(':')
  193. b.WriteString(strconv.Itoa(p.Line))
  194. b.WriteByte(':')
  195. b.WriteString(strconv.Itoa(p.Column))
  196. b.WriteByte('(')
  197. b.WriteString(strconv.Itoa(f.pc))
  198. b.WriteByte(')')
  199. if f.prg.funcName != "" {
  200. b.WriteByte(')')
  201. }
  202. } else {
  203. if f.funcName != "" {
  204. b.WriteString(f.funcName.String())
  205. b.WriteString(" (")
  206. }
  207. b.WriteString("native")
  208. if f.funcName != "" {
  209. b.WriteByte(')')
  210. }
  211. }
  212. }
  213. type Exception struct {
  214. val Value
  215. stack []StackFrame
  216. }
  217. type uncatchableException struct {
  218. stack *[]StackFrame
  219. err error
  220. }
  221. type InterruptedError struct {
  222. Exception
  223. iface interface{}
  224. }
  225. type StackOverflowError struct {
  226. Exception
  227. }
  228. func (e *InterruptedError) Value() interface{} {
  229. return e.iface
  230. }
  231. func (e *InterruptedError) String() string {
  232. if e == nil {
  233. return "<nil>"
  234. }
  235. var b bytes.Buffer
  236. if e.iface != nil {
  237. b.WriteString(fmt.Sprint(e.iface))
  238. b.WriteByte('\n')
  239. }
  240. e.writeFullStack(&b)
  241. return b.String()
  242. }
  243. func (e *InterruptedError) Error() string {
  244. if e == nil || e.iface == nil {
  245. return "<nil>"
  246. }
  247. var b bytes.Buffer
  248. b.WriteString(fmt.Sprint(e.iface))
  249. e.writeShortStack(&b)
  250. return b.String()
  251. }
  252. func (e *Exception) writeFullStack(b *bytes.Buffer) {
  253. for _, frame := range e.stack {
  254. b.WriteString("\tat ")
  255. frame.Write(b)
  256. b.WriteByte('\n')
  257. }
  258. }
  259. func (e *Exception) writeShortStack(b *bytes.Buffer) {
  260. if len(e.stack) > 0 && (e.stack[0].prg != nil || e.stack[0].funcName != "") {
  261. b.WriteString(" at ")
  262. e.stack[0].Write(b)
  263. }
  264. }
  265. func (e *Exception) String() string {
  266. if e == nil {
  267. return "<nil>"
  268. }
  269. var b bytes.Buffer
  270. if e.val != nil {
  271. b.WriteString(e.val.String())
  272. b.WriteByte('\n')
  273. }
  274. e.writeFullStack(&b)
  275. return b.String()
  276. }
  277. func (e *Exception) Error() string {
  278. if e == nil || e.val == nil {
  279. return "<nil>"
  280. }
  281. var b bytes.Buffer
  282. b.WriteString(e.val.String())
  283. e.writeShortStack(&b)
  284. return b.String()
  285. }
  286. func (e *Exception) Value() Value {
  287. return e.val
  288. }
  289. func (r *Runtime) addToGlobal(name string, value Value) {
  290. r.globalObject.self._putProp(unistring.String(name), value, true, false, true)
  291. }
  292. func (r *Runtime) createIterProto(val *Object) objectImpl {
  293. o := newBaseObjectObj(val, r.global.ObjectPrototype, classObject)
  294. o._putSym(SymIterator, valueProp(r.newNativeFunc(r.returnThis, nil, "[Symbol.iterator]", nil, 0), true, false, true))
  295. return o
  296. }
  297. func (r *Runtime) init() {
  298. r.rand = rand.Float64
  299. r.now = time.Now
  300. r.global.ObjectPrototype = r.newBaseObject(nil, classObject).val
  301. r.globalObject = r.NewObject()
  302. r.vm = &vm{
  303. r: r,
  304. }
  305. r.vm.init()
  306. funcProto := r.newNativeFunc(func(FunctionCall) Value {
  307. return _undefined
  308. }, nil, " ", nil, 0)
  309. r.global.FunctionPrototype = funcProto
  310. funcProtoObj := funcProto.self.(*nativeFuncObject)
  311. r.global.IteratorPrototype = r.newLazyObject(r.createIterProto)
  312. r.initObject()
  313. r.initFunction()
  314. r.initArray()
  315. r.initString()
  316. r.initGlobalObject()
  317. r.initNumber()
  318. r.initRegExp()
  319. r.initDate()
  320. r.initBoolean()
  321. r.initProxy()
  322. r.initReflect()
  323. r.initErrors()
  324. r.global.Eval = r.newNativeFunc(r.builtin_eval, nil, "eval", nil, 1)
  325. r.addToGlobal("eval", r.global.Eval)
  326. r.initMath()
  327. r.initJSON()
  328. r.initTypedArrays()
  329. r.initSymbol()
  330. r.initWeakSet()
  331. r.initWeakMap()
  332. r.initMap()
  333. r.initSet()
  334. r.initPromise()
  335. r.global.thrower = r.newNativeFunc(r.builtin_thrower, nil, "", nil, 0)
  336. r.global.throwerProperty = &valueProperty{
  337. getterFunc: r.global.thrower,
  338. setterFunc: r.global.thrower,
  339. accessor: true,
  340. }
  341. r.object_freeze(FunctionCall{Arguments: []Value{r.global.thrower}})
  342. funcProtoObj._put("caller", &valueProperty{
  343. getterFunc: r.global.thrower,
  344. setterFunc: r.global.thrower,
  345. accessor: true,
  346. configurable: true,
  347. })
  348. funcProtoObj._put("arguments", &valueProperty{
  349. getterFunc: r.global.thrower,
  350. setterFunc: r.global.thrower,
  351. accessor: true,
  352. configurable: true,
  353. })
  354. }
  355. func (r *Runtime) typeErrorResult(throw bool, args ...interface{}) {
  356. if throw {
  357. panic(r.NewTypeError(args...))
  358. }
  359. }
  360. func (r *Runtime) newError(typ *Object, format string, args ...interface{}) Value {
  361. msg := fmt.Sprintf(format, args...)
  362. return r.builtin_new(typ, []Value{newStringValue(msg)})
  363. }
  364. func (r *Runtime) throwReferenceError(name unistring.String) {
  365. panic(r.newError(r.global.ReferenceError, "%s is not defined", name))
  366. }
  367. func (r *Runtime) newSyntaxError(msg string, offset int) Value {
  368. return r.builtin_new(r.global.SyntaxError, []Value{newStringValue(msg)})
  369. }
  370. func newBaseObjectObj(obj, proto *Object, class string) *baseObject {
  371. o := &baseObject{
  372. class: class,
  373. val: obj,
  374. extensible: true,
  375. prototype: proto,
  376. }
  377. obj.self = o
  378. o.init()
  379. return o
  380. }
  381. func newGuardedObj(proto *Object, class string) *guardedObject {
  382. return &guardedObject{
  383. baseObject: baseObject{
  384. class: class,
  385. extensible: true,
  386. prototype: proto,
  387. },
  388. }
  389. }
  390. func (r *Runtime) newBaseObject(proto *Object, class string) (o *baseObject) {
  391. v := &Object{runtime: r}
  392. return newBaseObjectObj(v, proto, class)
  393. }
  394. func (r *Runtime) newGuardedObject(proto *Object, class string) (o *guardedObject) {
  395. v := &Object{runtime: r}
  396. o = newGuardedObj(proto, class)
  397. v.self = o
  398. o.val = v
  399. o.init()
  400. return
  401. }
  402. func (r *Runtime) NewObject() (v *Object) {
  403. return r.newBaseObject(r.global.ObjectPrototype, classObject).val
  404. }
  405. // CreateObject creates an object with given prototype. Equivalent of Object.create(proto).
  406. func (r *Runtime) CreateObject(proto *Object) *Object {
  407. return r.newBaseObject(proto, classObject).val
  408. }
  409. func (r *Runtime) NewArray(items ...interface{}) *Object {
  410. values := make([]Value, len(items))
  411. for i, item := range items {
  412. values[i] = r.ToValue(item)
  413. }
  414. return r.newArrayValues(values)
  415. }
  416. func (r *Runtime) NewTypeError(args ...interface{}) *Object {
  417. msg := ""
  418. if len(args) > 0 {
  419. f, _ := args[0].(string)
  420. msg = fmt.Sprintf(f, args[1:]...)
  421. }
  422. return r.builtin_new(r.global.TypeError, []Value{newStringValue(msg)})
  423. }
  424. func (r *Runtime) NewGoError(err error) *Object {
  425. e := r.newError(r.global.GoError, err.Error()).(*Object)
  426. e.Set("value", err)
  427. return e
  428. }
  429. func (r *Runtime) newFunc(name unistring.String, length int, strict bool) (f *funcObject) {
  430. v := &Object{runtime: r}
  431. f = &funcObject{}
  432. f.class = classFunction
  433. f.val = v
  434. f.extensible = true
  435. f.strict = strict
  436. v.self = f
  437. f.prototype = r.global.FunctionPrototype
  438. f.init(name, intToValue(int64(length)))
  439. return
  440. }
  441. func (r *Runtime) newMethod(name unistring.String, length int, strict bool) (f *methodFuncObject) {
  442. v := &Object{runtime: r}
  443. f = &methodFuncObject{}
  444. f.class = classFunction
  445. f.val = v
  446. f.extensible = true
  447. f.strict = strict
  448. v.self = f
  449. f.prototype = r.global.FunctionPrototype
  450. f.init(name, intToValue(int64(length)))
  451. return
  452. }
  453. func (r *Runtime) newArrowFunc(name unistring.String, length int, strict bool) (f *arrowFuncObject) {
  454. v := &Object{runtime: r}
  455. f = &arrowFuncObject{}
  456. f.class = classFunction
  457. f.val = v
  458. f.extensible = true
  459. f.strict = strict
  460. vm := r.vm
  461. var this Value
  462. if vm.sb >= 0 {
  463. this = vm.stack[vm.sb]
  464. } else {
  465. this = vm.r.globalObject
  466. }
  467. f.this = this
  468. f.newTarget = vm.newTarget
  469. v.self = f
  470. f.prototype = r.global.FunctionPrototype
  471. f.init(name, intToValue(int64(length)))
  472. return
  473. }
  474. func (r *Runtime) newNativeFuncObj(v *Object, call func(FunctionCall) Value, construct func(args []Value, proto *Object) *Object, name unistring.String, proto *Object, length Value) *nativeFuncObject {
  475. f := &nativeFuncObject{
  476. baseFuncObject: baseFuncObject{
  477. baseObject: baseObject{
  478. class: classFunction,
  479. val: v,
  480. extensible: true,
  481. prototype: r.global.FunctionPrototype,
  482. },
  483. },
  484. f: call,
  485. construct: r.wrapNativeConstruct(construct, proto),
  486. }
  487. v.self = f
  488. f.init(name, length)
  489. if proto != nil {
  490. f._putProp("prototype", proto, false, false, false)
  491. }
  492. return f
  493. }
  494. func (r *Runtime) newNativeConstructor(call func(ConstructorCall) *Object, name unistring.String, length int64) *Object {
  495. v := &Object{runtime: r}
  496. f := &nativeFuncObject{
  497. baseFuncObject: baseFuncObject{
  498. baseObject: baseObject{
  499. class: classFunction,
  500. val: v,
  501. extensible: true,
  502. prototype: r.global.FunctionPrototype,
  503. },
  504. },
  505. }
  506. f.f = func(c FunctionCall) Value {
  507. thisObj, _ := c.This.(*Object)
  508. if thisObj != nil {
  509. res := call(ConstructorCall{
  510. This: thisObj,
  511. Arguments: c.Arguments,
  512. })
  513. if res == nil {
  514. return _undefined
  515. }
  516. return res
  517. }
  518. return f.defaultConstruct(call, c.Arguments, nil)
  519. }
  520. f.construct = func(args []Value, newTarget *Object) *Object {
  521. return f.defaultConstruct(call, args, newTarget)
  522. }
  523. v.self = f
  524. f.init(name, intToValue(length))
  525. proto := r.NewObject()
  526. proto.self._putProp("constructor", v, true, false, true)
  527. f._putProp("prototype", proto, true, false, false)
  528. return v
  529. }
  530. func (r *Runtime) newNativeConstructOnly(v *Object, ctor func(args []Value, newTarget *Object) *Object, defaultProto *Object, name unistring.String, length int64) *nativeFuncObject {
  531. if v == nil {
  532. v = &Object{runtime: r}
  533. }
  534. f := &nativeFuncObject{
  535. baseFuncObject: baseFuncObject{
  536. baseObject: baseObject{
  537. class: classFunction,
  538. val: v,
  539. extensible: true,
  540. prototype: r.global.FunctionPrototype,
  541. },
  542. },
  543. f: func(call FunctionCall) Value {
  544. return ctor(call.Arguments, nil)
  545. },
  546. construct: func(args []Value, newTarget *Object) *Object {
  547. if newTarget == nil {
  548. newTarget = v
  549. }
  550. return ctor(args, newTarget)
  551. },
  552. }
  553. v.self = f
  554. f.init(name, intToValue(length))
  555. if defaultProto != nil {
  556. f._putProp("prototype", defaultProto, false, false, false)
  557. }
  558. return f
  559. }
  560. func (r *Runtime) newNativeFunc(call func(FunctionCall) Value, construct func(args []Value, proto *Object) *Object, name unistring.String, proto *Object, length int) *Object {
  561. v := &Object{runtime: r}
  562. f := &nativeFuncObject{
  563. baseFuncObject: baseFuncObject{
  564. baseObject: baseObject{
  565. class: classFunction,
  566. val: v,
  567. extensible: true,
  568. prototype: r.global.FunctionPrototype,
  569. },
  570. },
  571. f: call,
  572. construct: r.wrapNativeConstruct(construct, proto),
  573. }
  574. v.self = f
  575. f.init(name, intToValue(int64(length)))
  576. if proto != nil {
  577. f._putProp("prototype", proto, false, false, false)
  578. proto.self._putProp("constructor", v, true, false, true)
  579. }
  580. return v
  581. }
  582. func (r *Runtime) newNativeFuncConstructObj(v *Object, construct func(args []Value, proto *Object) *Object, name unistring.String, proto *Object, length int) *nativeFuncObject {
  583. f := &nativeFuncObject{
  584. baseFuncObject: baseFuncObject{
  585. baseObject: baseObject{
  586. class: classFunction,
  587. val: v,
  588. extensible: true,
  589. prototype: r.global.FunctionPrototype,
  590. },
  591. },
  592. f: r.constructToCall(construct, proto),
  593. construct: r.wrapNativeConstruct(construct, proto),
  594. }
  595. f.init(name, intToValue(int64(length)))
  596. if proto != nil {
  597. f._putProp("prototype", proto, false, false, false)
  598. }
  599. return f
  600. }
  601. func (r *Runtime) newNativeFuncConstruct(construct func(args []Value, proto *Object) *Object, name unistring.String, prototype *Object, length int64) *Object {
  602. return r.newNativeFuncConstructProto(construct, name, prototype, r.global.FunctionPrototype, length)
  603. }
  604. func (r *Runtime) newNativeFuncConstructProto(construct func(args []Value, proto *Object) *Object, name unistring.String, prototype, proto *Object, length int64) *Object {
  605. v := &Object{runtime: r}
  606. f := &nativeFuncObject{}
  607. f.class = classFunction
  608. f.val = v
  609. f.extensible = true
  610. v.self = f
  611. f.prototype = proto
  612. f.f = r.constructToCall(construct, prototype)
  613. f.construct = r.wrapNativeConstruct(construct, prototype)
  614. f.init(name, intToValue(length))
  615. if prototype != nil {
  616. f._putProp("prototype", prototype, false, false, false)
  617. prototype.self._putProp("constructor", v, true, false, true)
  618. }
  619. return v
  620. }
  621. func (r *Runtime) newPrimitiveObject(value Value, proto *Object, class string) *Object {
  622. v := &Object{runtime: r}
  623. o := &primitiveValueObject{}
  624. o.class = class
  625. o.val = v
  626. o.extensible = true
  627. v.self = o
  628. o.prototype = proto
  629. o.pValue = value
  630. o.init()
  631. return v
  632. }
  633. func (r *Runtime) builtin_Number(call FunctionCall) Value {
  634. if len(call.Arguments) > 0 {
  635. return call.Arguments[0].ToNumber()
  636. } else {
  637. return valueInt(0)
  638. }
  639. }
  640. func (r *Runtime) builtin_newNumber(args []Value, proto *Object) *Object {
  641. var v Value
  642. if len(args) > 0 {
  643. v = args[0].ToNumber()
  644. } else {
  645. v = intToValue(0)
  646. }
  647. return r.newPrimitiveObject(v, proto, classNumber)
  648. }
  649. func (r *Runtime) builtin_Boolean(call FunctionCall) Value {
  650. if len(call.Arguments) > 0 {
  651. if call.Arguments[0].ToBoolean() {
  652. return valueTrue
  653. } else {
  654. return valueFalse
  655. }
  656. } else {
  657. return valueFalse
  658. }
  659. }
  660. func (r *Runtime) builtin_newBoolean(args []Value, proto *Object) *Object {
  661. var v Value
  662. if len(args) > 0 {
  663. if args[0].ToBoolean() {
  664. v = valueTrue
  665. } else {
  666. v = valueFalse
  667. }
  668. } else {
  669. v = valueFalse
  670. }
  671. return r.newPrimitiveObject(v, proto, classBoolean)
  672. }
  673. func (r *Runtime) error_toString(call FunctionCall) Value {
  674. var nameStr, msgStr valueString
  675. obj := r.toObject(call.This)
  676. name := obj.self.getStr("name", nil)
  677. if name == nil || name == _undefined {
  678. nameStr = asciiString("Error")
  679. } else {
  680. nameStr = name.toString()
  681. }
  682. msg := obj.self.getStr("message", nil)
  683. if msg == nil || msg == _undefined {
  684. msgStr = stringEmpty
  685. } else {
  686. msgStr = msg.toString()
  687. }
  688. if nameStr.length() == 0 {
  689. return msgStr
  690. }
  691. if msgStr.length() == 0 {
  692. return nameStr
  693. }
  694. var sb valueStringBuilder
  695. sb.WriteString(nameStr)
  696. sb.WriteString(asciiString(": "))
  697. sb.WriteString(msgStr)
  698. return sb.String()
  699. }
  700. func (r *Runtime) builtin_new(construct *Object, args []Value) *Object {
  701. return r.toConstructor(construct)(args, nil)
  702. }
  703. func (r *Runtime) throw(e Value) {
  704. panic(e)
  705. }
  706. func (r *Runtime) builtin_thrower(call FunctionCall) Value {
  707. obj := r.toObject(call.This)
  708. strict := true
  709. switch fn := obj.self.(type) {
  710. case *funcObject:
  711. strict = fn.strict
  712. }
  713. r.typeErrorResult(strict, "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them")
  714. return nil
  715. }
  716. func (r *Runtime) eval(srcVal valueString, direct, strict bool, this Value) Value {
  717. src := escapeInvalidUtf16(srcVal)
  718. vm := r.vm
  719. inGlobal := true
  720. if direct {
  721. for s := vm.stash; s != nil; s = s.outer {
  722. if s.variable {
  723. inGlobal = false
  724. break
  725. }
  726. }
  727. }
  728. p, err := r.compile("<eval>", src, strict, true, inGlobal)
  729. if err != nil {
  730. panic(err)
  731. }
  732. vm.pushCtx()
  733. vm.prg = p
  734. vm.pc = 0
  735. vm.args = 0
  736. vm.result = _undefined
  737. if !direct {
  738. vm.stash = &r.global.stash
  739. }
  740. vm.sb = vm.sp
  741. vm.push(this)
  742. vm.run()
  743. retval := vm.result
  744. vm.popCtx()
  745. vm.halt = false
  746. vm.sp -= 1
  747. return retval
  748. }
  749. func (r *Runtime) builtin_eval(call FunctionCall) Value {
  750. if len(call.Arguments) == 0 {
  751. return _undefined
  752. }
  753. if str, ok := call.Arguments[0].(valueString); ok {
  754. return r.eval(str, false, false, r.globalObject)
  755. }
  756. return call.Arguments[0]
  757. }
  758. func (r *Runtime) constructToCall(construct func(args []Value, proto *Object) *Object, proto *Object) func(call FunctionCall) Value {
  759. return func(call FunctionCall) Value {
  760. return construct(call.Arguments, proto)
  761. }
  762. }
  763. func (r *Runtime) wrapNativeConstruct(c func(args []Value, proto *Object) *Object, proto *Object) func(args []Value, newTarget *Object) *Object {
  764. if c == nil {
  765. return nil
  766. }
  767. return func(args []Value, newTarget *Object) *Object {
  768. var p *Object
  769. if newTarget != nil {
  770. if pp, ok := newTarget.self.getStr("prototype", nil).(*Object); ok {
  771. p = pp
  772. }
  773. }
  774. if p == nil {
  775. p = proto
  776. }
  777. return c(args, p)
  778. }
  779. }
  780. func (r *Runtime) toCallable(v Value) func(FunctionCall) Value {
  781. if call, ok := r.toObject(v).self.assertCallable(); ok {
  782. return call
  783. }
  784. r.typeErrorResult(true, "Value is not callable: %s", v.toString())
  785. return nil
  786. }
  787. func (r *Runtime) checkObjectCoercible(v Value) {
  788. switch v.(type) {
  789. case valueUndefined, valueNull:
  790. r.typeErrorResult(true, "Value is not object coercible")
  791. }
  792. }
  793. func toInt8(v Value) int8 {
  794. v = v.ToNumber()
  795. if i, ok := v.(valueInt); ok {
  796. return int8(i)
  797. }
  798. if f, ok := v.(valueFloat); ok {
  799. f := float64(f)
  800. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  801. return int8(int64(f))
  802. }
  803. }
  804. return 0
  805. }
  806. func toUint8(v Value) uint8 {
  807. v = v.ToNumber()
  808. if i, ok := v.(valueInt); ok {
  809. return uint8(i)
  810. }
  811. if f, ok := v.(valueFloat); ok {
  812. f := float64(f)
  813. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  814. return uint8(int64(f))
  815. }
  816. }
  817. return 0
  818. }
  819. func toUint8Clamp(v Value) uint8 {
  820. v = v.ToNumber()
  821. if i, ok := v.(valueInt); ok {
  822. if i < 0 {
  823. return 0
  824. }
  825. if i <= 255 {
  826. return uint8(i)
  827. }
  828. return 255
  829. }
  830. if num, ok := v.(valueFloat); ok {
  831. num := float64(num)
  832. if !math.IsNaN(num) {
  833. if num < 0 {
  834. return 0
  835. }
  836. if num > 255 {
  837. return 255
  838. }
  839. f := math.Floor(num)
  840. f1 := f + 0.5
  841. if f1 < num {
  842. return uint8(f + 1)
  843. }
  844. if f1 > num {
  845. return uint8(f)
  846. }
  847. r := uint8(f)
  848. if r&1 != 0 {
  849. return r + 1
  850. }
  851. return r
  852. }
  853. }
  854. return 0
  855. }
  856. func toInt16(v Value) int16 {
  857. v = v.ToNumber()
  858. if i, ok := v.(valueInt); ok {
  859. return int16(i)
  860. }
  861. if f, ok := v.(valueFloat); ok {
  862. f := float64(f)
  863. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  864. return int16(int64(f))
  865. }
  866. }
  867. return 0
  868. }
  869. func toUint16(v Value) uint16 {
  870. v = v.ToNumber()
  871. if i, ok := v.(valueInt); ok {
  872. return uint16(i)
  873. }
  874. if f, ok := v.(valueFloat); ok {
  875. f := float64(f)
  876. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  877. return uint16(int64(f))
  878. }
  879. }
  880. return 0
  881. }
  882. func toInt32(v Value) int32 {
  883. v = v.ToNumber()
  884. if i, ok := v.(valueInt); ok {
  885. return int32(i)
  886. }
  887. if f, ok := v.(valueFloat); ok {
  888. f := float64(f)
  889. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  890. return int32(int64(f))
  891. }
  892. }
  893. return 0
  894. }
  895. func toUint32(v Value) uint32 {
  896. v = v.ToNumber()
  897. if i, ok := v.(valueInt); ok {
  898. return uint32(i)
  899. }
  900. if f, ok := v.(valueFloat); ok {
  901. f := float64(f)
  902. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  903. return uint32(int64(f))
  904. }
  905. }
  906. return 0
  907. }
  908. func toInt64(v Value) int64 {
  909. v = v.ToNumber()
  910. if i, ok := v.(valueInt); ok {
  911. return int64(i)
  912. }
  913. if f, ok := v.(valueFloat); ok {
  914. f := float64(f)
  915. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  916. return int64(f)
  917. }
  918. }
  919. return 0
  920. }
  921. func toUint64(v Value) uint64 {
  922. v = v.ToNumber()
  923. if i, ok := v.(valueInt); ok {
  924. return uint64(i)
  925. }
  926. if f, ok := v.(valueFloat); ok {
  927. f := float64(f)
  928. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  929. return uint64(int64(f))
  930. }
  931. }
  932. return 0
  933. }
  934. func toInt(v Value) int {
  935. v = v.ToNumber()
  936. if i, ok := v.(valueInt); ok {
  937. return int(i)
  938. }
  939. if f, ok := v.(valueFloat); ok {
  940. f := float64(f)
  941. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  942. return int(f)
  943. }
  944. }
  945. return 0
  946. }
  947. func toUint(v Value) uint {
  948. v = v.ToNumber()
  949. if i, ok := v.(valueInt); ok {
  950. return uint(i)
  951. }
  952. if f, ok := v.(valueFloat); ok {
  953. f := float64(f)
  954. if !math.IsNaN(f) && !math.IsInf(f, 0) {
  955. return uint(int64(f))
  956. }
  957. }
  958. return 0
  959. }
  960. func toFloat32(v Value) float32 {
  961. return float32(v.ToFloat())
  962. }
  963. func toLength(v Value) int64 {
  964. if v == nil {
  965. return 0
  966. }
  967. i := v.ToInteger()
  968. if i < 0 {
  969. return 0
  970. }
  971. if i >= maxInt {
  972. return maxInt - 1
  973. }
  974. return i
  975. }
  976. func (r *Runtime) toLengthUint32(v Value) uint32 {
  977. var intVal int64
  978. repeat:
  979. switch num := v.(type) {
  980. case valueInt:
  981. intVal = int64(num)
  982. case valueFloat:
  983. if v != _negativeZero {
  984. if i, ok := floatToInt(float64(num)); ok {
  985. intVal = i
  986. } else {
  987. goto fail
  988. }
  989. }
  990. case valueString:
  991. v = num.ToNumber()
  992. goto repeat
  993. default:
  994. // Legacy behaviour as specified in https://tc39.es/ecma262/#sec-arraysetlength (see the note)
  995. n2 := toUint32(v)
  996. n1 := v.ToNumber()
  997. if f, ok := n1.(valueFloat); ok {
  998. f := float64(f)
  999. if f != 0 || !math.Signbit(f) {
  1000. goto fail
  1001. }
  1002. }
  1003. if n1.ToInteger() != int64(n2) {
  1004. goto fail
  1005. }
  1006. return n2
  1007. }
  1008. if intVal >= 0 && intVal <= math.MaxUint32 {
  1009. return uint32(intVal)
  1010. }
  1011. fail:
  1012. panic(r.newError(r.global.RangeError, "Invalid array length"))
  1013. }
  1014. func toIntStrict(i int64) int {
  1015. if bits.UintSize == 32 {
  1016. if i > math.MaxInt32 || i < math.MinInt32 {
  1017. panic(rangeError("Integer value overflows 32-bit int"))
  1018. }
  1019. }
  1020. return int(i)
  1021. }
  1022. func toIntClamp(i int64) int {
  1023. if bits.UintSize == 32 {
  1024. if i > math.MaxInt32 {
  1025. return math.MaxInt32
  1026. }
  1027. if i < math.MinInt32 {
  1028. return math.MinInt32
  1029. }
  1030. }
  1031. return int(i)
  1032. }
  1033. func (r *Runtime) toIndex(v Value) int {
  1034. num := v.ToInteger()
  1035. if num >= 0 && num < maxInt {
  1036. if bits.UintSize == 32 && num >= math.MaxInt32 {
  1037. panic(r.newError(r.global.RangeError, "Index %s overflows int", v.String()))
  1038. }
  1039. return int(num)
  1040. }
  1041. panic(r.newError(r.global.RangeError, "Invalid index %s", v.String()))
  1042. }
  1043. func (r *Runtime) toBoolean(b bool) Value {
  1044. if b {
  1045. return valueTrue
  1046. } else {
  1047. return valueFalse
  1048. }
  1049. }
  1050. // New creates an instance of a Javascript runtime that can be used to run code. Multiple instances may be created and
  1051. // used simultaneously, however it is not possible to pass JS values across runtimes.
  1052. func New() *Runtime {
  1053. r := &Runtime{}
  1054. r.init()
  1055. return r
  1056. }
  1057. // Compile creates an internal representation of the JavaScript code that can be later run using the Runtime.RunProgram()
  1058. // method. This representation is not linked to a runtime in any way and can be run in multiple runtimes (possibly
  1059. // at the same time).
  1060. func Compile(name, src string, strict bool) (*Program, error) {
  1061. return compile(name, src, strict, false, true)
  1062. }
  1063. // CompileAST creates an internal representation of the JavaScript code that can be later run using the Runtime.RunProgram()
  1064. // method. This representation is not linked to a runtime in any way and can be run in multiple runtimes (possibly
  1065. // at the same time).
  1066. func CompileAST(prg *js_ast.Program, strict bool) (*Program, error) {
  1067. return compileAST(prg, strict, false, true)
  1068. }
  1069. // MustCompile is like Compile but panics if the code cannot be compiled.
  1070. // It simplifies safe initialization of global variables holding compiled JavaScript code.
  1071. func MustCompile(name, src string, strict bool) *Program {
  1072. prg, err := Compile(name, src, strict)
  1073. if err != nil {
  1074. panic(err)
  1075. }
  1076. return prg
  1077. }
  1078. // Parse takes a source string and produces a parsed AST. Use this function if you want to pass options
  1079. // to the parser, e.g.:
  1080. //
  1081. // p, err := Parse("test.js", "var a = true", parser.WithDisableSourceMaps)
  1082. // if err != nil { /* ... */ }
  1083. // prg, err := CompileAST(p, true)
  1084. // // ...
  1085. //
  1086. // Otherwise use Compile which combines both steps.
  1087. func Parse(name, src string, options ...parser.Option) (prg *js_ast.Program, err error) {
  1088. prg, err1 := parser.ParseFile(nil, name, src, 0, options...)
  1089. if err1 != nil {
  1090. // FIXME offset
  1091. err = &CompilerSyntaxError{
  1092. CompilerError: CompilerError{
  1093. Message: err1.Error(),
  1094. },
  1095. }
  1096. }
  1097. return
  1098. }
  1099. func compile(name, src string, strict, eval, inGlobal bool, parserOptions ...parser.Option) (p *Program, err error) {
  1100. prg, err := Parse(name, src, parserOptions...)
  1101. if err != nil {
  1102. return
  1103. }
  1104. return compileAST(prg, strict, eval, inGlobal)
  1105. }
  1106. func compileAST(prg *js_ast.Program, strict, eval, inGlobal bool) (p *Program, err error) {
  1107. c := newCompiler()
  1108. defer func() {
  1109. if x := recover(); x != nil {
  1110. p = nil
  1111. switch x1 := x.(type) {
  1112. case *CompilerSyntaxError:
  1113. err = x1
  1114. default:
  1115. panic(x)
  1116. }
  1117. }
  1118. }()
  1119. c.compile(prg, strict, eval, inGlobal)
  1120. p = c.p
  1121. return
  1122. }
  1123. func (r *Runtime) compile(name, src string, strict, eval, inGlobal bool) (p *Program, err error) {
  1124. p, err = compile(name, src, strict, eval, inGlobal, r.parserOptions...)
  1125. if err != nil {
  1126. switch x1 := err.(type) {
  1127. case *CompilerSyntaxError:
  1128. err = &Exception{
  1129. val: r.builtin_new(r.global.SyntaxError, []Value{newStringValue(x1.Error())}),
  1130. }
  1131. case *CompilerReferenceError:
  1132. err = &Exception{
  1133. val: r.newError(r.global.ReferenceError, x1.Message),
  1134. } // TODO proper message
  1135. }
  1136. }
  1137. return
  1138. }
  1139. // RunString executes the given string in the global context.
  1140. func (r *Runtime) RunString(str string) (Value, error) {
  1141. return r.RunScript("", str)
  1142. }
  1143. // RunScript executes the given string in the global context.
  1144. func (r *Runtime) RunScript(name, src string) (Value, error) {
  1145. p, err := r.compile(name, src, false, false, true)
  1146. if err != nil {
  1147. return nil, err
  1148. }
  1149. return r.RunProgram(p)
  1150. }
  1151. // RunProgram executes a pre-compiled (see Compile()) code in the global context.
  1152. func (r *Runtime) RunProgram(p *Program) (result Value, err error) {
  1153. defer func() {
  1154. if x := recover(); x != nil {
  1155. if ex, ok := x.(*uncatchableException); ok {
  1156. err = ex.err
  1157. } else {
  1158. panic(x)
  1159. }
  1160. }
  1161. }()
  1162. vm := r.vm
  1163. recursive := false
  1164. if len(vm.callStack) > 0 {
  1165. recursive = true
  1166. vm.pushCtx()
  1167. vm.stash = &r.global.stash
  1168. vm.sb = vm.sp - 1
  1169. }
  1170. vm.prg = p
  1171. vm.pc = 0
  1172. vm.result = _undefined
  1173. ex := vm.runTry()
  1174. if ex == nil {
  1175. result = r.vm.result
  1176. } else {
  1177. err = ex
  1178. }
  1179. if recursive {
  1180. vm.popCtx()
  1181. vm.halt = false
  1182. vm.clearStack()
  1183. } else {
  1184. vm.stack = nil
  1185. vm.prg = nil
  1186. r.leave()
  1187. }
  1188. return
  1189. }
  1190. // CaptureCallStack appends the current call stack frames to the stack slice (which may be nil) up to the specified depth.
  1191. // The most recent frame will be the first one.
  1192. // If depth <= 0 or more than the number of available frames, returns the entire stack.
  1193. // This method is not safe for concurrent use and should only be called by a Go function that is
  1194. // called from a running script.
  1195. func (r *Runtime) CaptureCallStack(depth int, stack []StackFrame) []StackFrame {
  1196. l := len(r.vm.callStack)
  1197. var offset int
  1198. if depth > 0 {
  1199. offset = l - depth + 1
  1200. if offset < 0 {
  1201. offset = 0
  1202. }
  1203. }
  1204. if stack == nil {
  1205. stack = make([]StackFrame, 0, l-offset+1)
  1206. }
  1207. return r.vm.captureStack(stack, offset)
  1208. }
  1209. // Interrupt a running JavaScript. The corresponding Go call will return an *InterruptedError containing v.
  1210. // Note, it only works while in JavaScript code, it does not interrupt native Go functions (which includes all built-ins).
  1211. // If the runtime is currently not running, it will be immediately interrupted on the next Run*() call.
  1212. // To avoid that use ClearInterrupt()
  1213. func (r *Runtime) Interrupt(v interface{}) {
  1214. r.vm.Interrupt(v)
  1215. }
  1216. // ClearInterrupt resets the interrupt flag. Typically this needs to be called before the runtime
  1217. // is made available for re-use if there is a chance it could have been interrupted with Interrupt().
  1218. // Otherwise if Interrupt() was called when runtime was not running (e.g. if it had already finished)
  1219. // so that Interrupt() didn't actually trigger, an attempt to use the runtime will immediately cause
  1220. // an interruption. It is up to the user to ensure proper synchronisation so that ClearInterrupt() is
  1221. // only called when the runtime has finished and there is no chance of a concurrent Interrupt() call.
  1222. func (r *Runtime) ClearInterrupt() {
  1223. r.vm.ClearInterrupt()
  1224. }
  1225. /*
  1226. ToValue converts a Go value into a JavaScript value of a most appropriate type. Structural types (such as structs, maps
  1227. and slices) are wrapped so that changes are reflected on the original value which can be retrieved using Value.Export().
  1228. WARNING! There are two very important caveats to bear in mind when modifying wrapped Go structs, maps and
  1229. slices.
  1230. 1. If a slice is passed by value (not as a pointer), resizing the slice does not reflect on the original
  1231. value. Moreover, extending the slice may result in the underlying array being re-allocated and copied.
  1232. For example:
  1233. a := []interface{}{1}
  1234. vm.Set("a", a)
  1235. vm.RunString(`a.push(2); a[0] = 0;`)
  1236. fmt.Println(a[0]) // prints "1"
  1237. 2. If a regular JavaScript Object is assigned as an element of a wrapped Go struct, map or array, it is
  1238. Export()'ed and therefore copied. This may result in an unexpected behaviour in JavaScript:
  1239. m := map[string]interface{}{}
  1240. vm.Set("m", m)
  1241. vm.RunString(`
  1242. var obj = {test: false};
  1243. m.obj = obj; // obj gets Export()'ed, i.e. copied to a new map[string]interface{} and then this map is set as m["obj"]
  1244. obj.test = true; // note, m.obj.test is still false
  1245. `)
  1246. fmt.Println(m["obj"].(map[string]interface{})["test"]) // prints "false"
  1247. Notes on individual types:
  1248. Primitive types
  1249. Primitive types (numbers, string, bool) are converted to the corresponding JavaScript primitives.
  1250. Strings
  1251. Because of the difference in internal string representation between ECMAScript (which uses UTF-16) and Go (which uses
  1252. UTF-8) conversion from JS to Go may be lossy. In particular, code points that can be part of UTF-16 surrogate pairs
  1253. (0xD800-0xDFFF) cannot be represented in UTF-8 unless they form a valid surrogate pair and are replaced with
  1254. utf8.RuneError.
  1255. Nil
  1256. Nil is converted to null.
  1257. Functions
  1258. func(FunctionCall) Value is treated as a native JavaScript function. This increases performance because there are no
  1259. automatic argument and return value type conversions (which involves reflect). Attempting to use
  1260. the function as a constructor will result in a TypeError.
  1261. func(FunctionCall, *Runtime) Value is treated as above, except the *Runtime is also passed as a parameter.
  1262. func(ConstructorCall) *Object is treated as a native constructor, allowing to use it with the new
  1263. operator:
  1264. func MyObject(call goja.ConstructorCall) *goja.Object {
  1265. // call.This contains the newly created object as per http://www.ecma-international.org/ecma-262/5.1/index.html#sec-13.2.2
  1266. // call.Arguments contain arguments passed to the function
  1267. call.This.Set("method", method)
  1268. //...
  1269. // If return value is a non-nil *Object, it will be used instead of call.This
  1270. // This way it is possible to return a Go struct or a map converted
  1271. // into goja.Value using ToValue(), however in this case
  1272. // instanceof will not work as expected.
  1273. return nil
  1274. }
  1275. runtime.Set("MyObject", MyObject)
  1276. Then it can be used in JS as follows:
  1277. var o = new MyObject(arg);
  1278. var o1 = MyObject(arg); // same thing
  1279. o instanceof MyObject && o1 instanceof MyObject; // true
  1280. When a native constructor is called directly (without the new operator) its behavior depends on
  1281. this value: if it's an Object, it is passed through, otherwise a new one is created exactly as
  1282. if it was called with the new operator. In either case call.NewTarget will be nil.
  1283. func(ConstructorCall, *Runtime) *Object is treated as above, except the *Runtime is also passed as a parameter.
  1284. Any other Go function is wrapped so that the arguments are automatically converted into the required Go types and the
  1285. return value is converted to a JavaScript value (using this method). If conversion is not possible, a TypeError is
  1286. thrown.
  1287. Functions with multiple return values return an Array. If the last return value is an `error` it is not returned but
  1288. converted into a JS exception. If the error is *Exception, it is thrown as is, otherwise it's wrapped in a GoEerror.
  1289. Note that if there are exactly two return values and the last is an `error`, the function returns the first value as is,
  1290. not an Array.
  1291. Structs
  1292. Structs are converted to Object-like values. Fields and methods are available as properties, their values are
  1293. results of this method (ToValue()) applied to the corresponding Go value.
  1294. Field properties are writable (if the struct is addressable) and non-configurable.
  1295. Method properties are non-writable and non-configurable.
  1296. Attempt to define a new property or delete an existing property will fail (throw in strict mode) unless it's a Symbol
  1297. property. Symbol properties only exist in the wrapper and do not affect the underlying Go value.
  1298. Note that because a wrapper is created every time a property is accessed it may lead to unexpected results such as this:
  1299. type Field struct{
  1300. }
  1301. type S struct {
  1302. Field *Field
  1303. }
  1304. var s = S{
  1305. Field: &Field{},
  1306. }
  1307. vm := New()
  1308. vm.Set("s", &s)
  1309. res, err := vm.RunString(`
  1310. var sym = Symbol(66);
  1311. var field1 = s.Field;
  1312. field1[sym] = true;
  1313. var field2 = s.Field;
  1314. field1 === field2; // true, because the equality operation compares the wrapped values, not the wrappers
  1315. field1[sym] === true; // true
  1316. field2[sym] === undefined; // also true
  1317. `)
  1318. The same applies to values from maps and slices as well.
  1319. Handling of time.Time
  1320. time.Time does not get special treatment and therefore is converted just like any other `struct` providing access to
  1321. all its methods. This is done deliberately instead of converting it to a `Date` because these two types are not fully
  1322. compatible: `time.Time` includes zone, whereas JS `Date` doesn't. Doing the conversion implicitly therefore would
  1323. result in a loss of information.
  1324. If you need to convert it to a `Date`, it can be done either in JS:
  1325. var d = new Date(goval.UnixNano()/1e6);
  1326. ... or in Go:
  1327. now := time.Now()
  1328. vm := New()
  1329. val, err := vm.New(vm.Get("Date").ToObject(vm), vm.ToValue(now.UnixNano()/1e6))
  1330. if err != nil {
  1331. ...
  1332. }
  1333. vm.Set("d", val)
  1334. Note that Value.Export() for a `Date` value returns time.Time in local timezone.
  1335. Maps
  1336. Maps with string or integer key type are converted into host objects that largely behave like a JavaScript Object.
  1337. Maps with methods
  1338. If a map type has at least one method defined, the properties of the resulting Object represent methods, not map keys.
  1339. This is because in JavaScript there is no distinction between 'object.key` and `object[key]`, unlike Go.
  1340. If access to the map values is required, it can be achieved by defining another method or, if it's not possible, by
  1341. defining an external getter function.
  1342. Slices
  1343. Slices are converted into host objects that behave largely like JavaScript Array. It has the appropriate
  1344. prototype and all the usual methods should work. There is, however, a caveat: converted Arrays may not contain holes
  1345. (because Go slices cannot). This means that hasOwnProperty(n) always returns `true` if n < length. Deleting an item with
  1346. an index < length will set it to a zero value (but the property will remain). Nil slice elements are be converted to
  1347. `null`. Accessing an element beyond `length` returns `undefined`. Also see the warning above about passing slices as
  1348. values (as opposed to pointers).
  1349. Any other type is converted to a generic reflect based host object. Depending on the underlying type it behaves similar
  1350. to a Number, String, Boolean or Object.
  1351. Note that the underlying type is not lost, calling Export() returns the original Go value. This applies to all
  1352. reflect based types.
  1353. */
  1354. func (r *Runtime) ToValue(i interface{}) Value {
  1355. switch i := i.(type) {
  1356. case nil:
  1357. return _null
  1358. case *Object:
  1359. if i == nil || i.runtime == nil {
  1360. return _null
  1361. }
  1362. if i.runtime != r {
  1363. panic(r.NewTypeError("Illegal runtime transition of an Object"))
  1364. }
  1365. return i
  1366. case valueContainer:
  1367. return i.toValue(r)
  1368. case Value:
  1369. return i
  1370. case string:
  1371. return newStringValue(i)
  1372. case bool:
  1373. if i {
  1374. return valueTrue
  1375. } else {
  1376. return valueFalse
  1377. }
  1378. case func(FunctionCall) Value:
  1379. name := unistring.NewFromString(runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name())
  1380. return r.newNativeFunc(i, nil, name, nil, 0)
  1381. case func(FunctionCall, *Runtime) Value:
  1382. name := unistring.NewFromString(runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name())
  1383. return r.newNativeFunc(func(call FunctionCall) Value {
  1384. return i(call, r)
  1385. }, nil, name, nil, 0)
  1386. case func(ConstructorCall) *Object:
  1387. name := unistring.NewFromString(runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name())
  1388. return r.newNativeConstructor(i, name, 0)
  1389. case func(ConstructorCall, *Runtime) *Object:
  1390. name := unistring.NewFromString(runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name())
  1391. return r.newNativeConstructor(func(call ConstructorCall) *Object {
  1392. return i(call, r)
  1393. }, name, 0)
  1394. case int:
  1395. return intToValue(int64(i))
  1396. case int8:
  1397. return intToValue(int64(i))
  1398. case int16:
  1399. return intToValue(int64(i))
  1400. case int32:
  1401. return intToValue(int64(i))
  1402. case int64:
  1403. return intToValue(i)
  1404. case uint:
  1405. if uint64(i) <= math.MaxInt64 {
  1406. return intToValue(int64(i))
  1407. } else {
  1408. return floatToValue(float64(i))
  1409. }
  1410. case uint8:
  1411. return intToValue(int64(i))
  1412. case uint16:
  1413. return intToValue(int64(i))
  1414. case uint32:
  1415. return intToValue(int64(i))
  1416. case uint64:
  1417. if i <= math.MaxInt64 {
  1418. return intToValue(int64(i))
  1419. }
  1420. return floatToValue(float64(i))
  1421. case float32:
  1422. return floatToValue(float64(i))
  1423. case float64:
  1424. return floatToValue(i)
  1425. case map[string]interface{}:
  1426. if i == nil {
  1427. return _null
  1428. }
  1429. obj := &Object{runtime: r}
  1430. m := &objectGoMapSimple{
  1431. baseObject: baseObject{
  1432. val: obj,
  1433. extensible: true,
  1434. },
  1435. data: i,
  1436. }
  1437. obj.self = m
  1438. m.init()
  1439. return obj
  1440. case []interface{}:
  1441. if i == nil {
  1442. return _null
  1443. }
  1444. obj := &Object{runtime: r}
  1445. a := &objectGoSlice{
  1446. baseObject: baseObject{
  1447. val: obj,
  1448. },
  1449. data: &i,
  1450. }
  1451. obj.self = a
  1452. a.init()
  1453. return obj
  1454. case *[]interface{}:
  1455. if i == nil {
  1456. return _null
  1457. }
  1458. obj := &Object{runtime: r}
  1459. a := &objectGoSlice{
  1460. baseObject: baseObject{
  1461. val: obj,
  1462. },
  1463. data: i,
  1464. }
  1465. obj.self = a
  1466. a.init()
  1467. return obj
  1468. }
  1469. origValue := reflect.ValueOf(i)
  1470. value := origValue
  1471. for value.Kind() == reflect.Ptr {
  1472. value = reflect.Indirect(value)
  1473. }
  1474. if !value.IsValid() {
  1475. return _null
  1476. }
  1477. switch value.Kind() {
  1478. case reflect.Map:
  1479. if value.Type().NumMethod() == 0 {
  1480. switch value.Type().Key().Kind() {
  1481. case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  1482. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
  1483. reflect.Float64, reflect.Float32:
  1484. obj := &Object{runtime: r}
  1485. m := &objectGoMapReflect{
  1486. objectGoReflect: objectGoReflect{
  1487. baseObject: baseObject{
  1488. val: obj,
  1489. extensible: true,
  1490. },
  1491. origValue: origValue,
  1492. value: value,
  1493. },
  1494. }
  1495. m.init()
  1496. obj.self = m
  1497. return obj
  1498. }
  1499. }
  1500. case reflect.Slice:
  1501. obj := &Object{runtime: r}
  1502. a := &objectGoSliceReflect{
  1503. objectGoReflect: objectGoReflect{
  1504. baseObject: baseObject{
  1505. val: obj,
  1506. },
  1507. origValue: origValue,
  1508. value: value,
  1509. },
  1510. }
  1511. a.init()
  1512. obj.self = a
  1513. return obj
  1514. case reflect.Func:
  1515. name := unistring.NewFromString(runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name())
  1516. return r.newNativeFunc(r.wrapReflectFunc(value), nil, name, nil, value.Type().NumIn())
  1517. }
  1518. obj := &Object{runtime: r}
  1519. o := &objectGoReflect{
  1520. baseObject: baseObject{
  1521. val: obj,
  1522. },
  1523. origValue: origValue,
  1524. value: value,
  1525. }
  1526. obj.self = o
  1527. o.init()
  1528. return obj
  1529. }
  1530. func (r *Runtime) wrapReflectFunc(value reflect.Value) func(FunctionCall) Value {
  1531. return func(call FunctionCall) Value {
  1532. typ := value.Type()
  1533. nargs := typ.NumIn()
  1534. var in []reflect.Value
  1535. if l := len(call.Arguments); l < nargs {
  1536. // fill missing arguments with zero values
  1537. n := nargs
  1538. if typ.IsVariadic() {
  1539. n--
  1540. }
  1541. in = make([]reflect.Value, n)
  1542. for i := l; i < n; i++ {
  1543. in[i] = reflect.Zero(typ.In(i))
  1544. }
  1545. } else {
  1546. if l > nargs && !typ.IsVariadic() {
  1547. l = nargs
  1548. }
  1549. in = make([]reflect.Value, l)
  1550. }
  1551. callSlice := false
  1552. for i, a := range call.Arguments {
  1553. var t reflect.Type
  1554. n := i
  1555. if n >= nargs-1 && typ.IsVariadic() {
  1556. if n > nargs-1 {
  1557. n = nargs - 1
  1558. }
  1559. t = typ.In(n).Elem()
  1560. } else if n > nargs-1 { // ignore extra arguments
  1561. break
  1562. } else {
  1563. t = typ.In(n)
  1564. }
  1565. // if this is a variadic Go function, and the caller has supplied
  1566. // exactly the number of JavaScript arguments required, and this
  1567. // is the last JavaScript argument, try treating the it as the
  1568. // actual set of variadic Go arguments. if that succeeds, break
  1569. // out of the loop.
  1570. if typ.IsVariadic() && len(call.Arguments) == nargs && i == nargs-1 {
  1571. v := reflect.New(typ.In(n)).Elem()
  1572. if err := r.toReflectValue(a, v, &objectExportCtx{}); err == nil {
  1573. in[i] = v
  1574. callSlice = true
  1575. break
  1576. }
  1577. }
  1578. v := reflect.New(t).Elem()
  1579. err := r.toReflectValue(a, v, &objectExportCtx{})
  1580. if err != nil {
  1581. panic(r.newError(r.global.TypeError, "could not convert function call parameter %v to %v", a, t))
  1582. }
  1583. in[i] = v
  1584. }
  1585. var out []reflect.Value
  1586. if callSlice {
  1587. out = value.CallSlice(in)
  1588. } else {
  1589. out = value.Call(in)
  1590. }
  1591. if len(out) == 0 {
  1592. return _undefined
  1593. }
  1594. if last := out[len(out)-1]; last.Type().Name() == "error" {
  1595. if !last.IsNil() {
  1596. err := last.Interface()
  1597. if _, ok := err.(*Exception); ok {
  1598. panic(err)
  1599. }
  1600. panic(r.NewGoError(last.Interface().(error)))
  1601. }
  1602. out = out[:len(out)-1]
  1603. }
  1604. switch len(out) {
  1605. case 0:
  1606. return _undefined
  1607. case 1:
  1608. return r.ToValue(out[0].Interface())
  1609. default:
  1610. s := make([]interface{}, len(out))
  1611. for i, v := range out {
  1612. s[i] = v.Interface()
  1613. }
  1614. return r.ToValue(s)
  1615. }
  1616. }
  1617. }
  1618. func (r *Runtime) toReflectValue(v Value, dst reflect.Value, ctx *objectExportCtx) error {
  1619. typ := dst.Type()
  1620. if typ == typeValue {
  1621. dst.Set(reflect.ValueOf(v))
  1622. return nil
  1623. }
  1624. if typ == typeObject {
  1625. if obj, ok := v.(*Object); ok {
  1626. dst.Set(reflect.ValueOf(obj))
  1627. return nil
  1628. }
  1629. }
  1630. if typ == typeCallable {
  1631. if fn, ok := AssertFunction(v); ok {
  1632. dst.Set(reflect.ValueOf(fn))
  1633. return nil
  1634. }
  1635. }
  1636. et := v.ExportType()
  1637. if et == nil || et == reflectTypeNil {
  1638. dst.Set(reflect.Zero(typ))
  1639. return nil
  1640. }
  1641. kind := typ.Kind()
  1642. for i := 0; ; i++ {
  1643. if et.AssignableTo(typ) {
  1644. ev := reflect.ValueOf(exportValue(v, ctx))
  1645. for ; i > 0; i-- {
  1646. ev = ev.Elem()
  1647. }
  1648. dst.Set(ev)
  1649. return nil
  1650. }
  1651. expKind := et.Kind()
  1652. if expKind == kind && et.ConvertibleTo(typ) || expKind == reflect.String && typ == typeBytes {
  1653. ev := reflect.ValueOf(exportValue(v, ctx))
  1654. for ; i > 0; i-- {
  1655. ev = ev.Elem()
  1656. }
  1657. dst.Set(ev.Convert(typ))
  1658. return nil
  1659. }
  1660. if expKind == reflect.Ptr {
  1661. et = et.Elem()
  1662. } else {
  1663. break
  1664. }
  1665. }
  1666. if typ == typeTime {
  1667. if obj, ok := v.(*Object); ok {
  1668. if d, ok := obj.self.(*dateObject); ok {
  1669. dst.Set(reflect.ValueOf(d.time()))
  1670. return nil
  1671. }
  1672. }
  1673. if et.Kind() == reflect.String {
  1674. tme, ok := dateParse(v.String())
  1675. if !ok {
  1676. return fmt.Errorf("could not convert string %v to %v", v, typ)
  1677. }
  1678. dst.Set(reflect.ValueOf(tme))
  1679. return nil
  1680. }
  1681. }
  1682. switch kind {
  1683. case reflect.String:
  1684. dst.Set(reflect.ValueOf(v.String()).Convert(typ))
  1685. return nil
  1686. case reflect.Bool:
  1687. dst.Set(reflect.ValueOf(v.ToBoolean()).Convert(typ))
  1688. return nil
  1689. case reflect.Int:
  1690. dst.Set(reflect.ValueOf(toInt(v)).Convert(typ))
  1691. return nil
  1692. case reflect.Int64:
  1693. dst.Set(reflect.ValueOf(toInt64(v)).Convert(typ))
  1694. return nil
  1695. case reflect.Int32:
  1696. dst.Set(reflect.ValueOf(toInt32(v)).Convert(typ))
  1697. return nil
  1698. case reflect.Int16:
  1699. dst.Set(reflect.ValueOf(toInt16(v)).Convert(typ))
  1700. return nil
  1701. case reflect.Int8:
  1702. dst.Set(reflect.ValueOf(toInt8(v)).Convert(typ))
  1703. return nil
  1704. case reflect.Uint:
  1705. dst.Set(reflect.ValueOf(toUint(v)).Convert(typ))
  1706. return nil
  1707. case reflect.Uint64:
  1708. dst.Set(reflect.ValueOf(toUint64(v)).Convert(typ))
  1709. return nil
  1710. case reflect.Uint32:
  1711. dst.Set(reflect.ValueOf(toUint32(v)).Convert(typ))
  1712. return nil
  1713. case reflect.Uint16:
  1714. dst.Set(reflect.ValueOf(toUint16(v)).Convert(typ))
  1715. return nil
  1716. case reflect.Uint8:
  1717. dst.Set(reflect.ValueOf(toUint8(v)).Convert(typ))
  1718. return nil
  1719. case reflect.Float64:
  1720. dst.Set(reflect.ValueOf(v.ToFloat()).Convert(typ))
  1721. return nil
  1722. case reflect.Float32:
  1723. dst.Set(reflect.ValueOf(toFloat32(v)).Convert(typ))
  1724. return nil
  1725. case reflect.Slice:
  1726. if o, ok := v.(*Object); ok {
  1727. if o.self.className() == classArray {
  1728. if v, exists := ctx.getTyped(o.self, typ); exists {
  1729. dst.Set(reflect.ValueOf(v))
  1730. return nil
  1731. }
  1732. l := int(toLength(o.self.getStr("length", nil)))
  1733. if dst.IsNil() || dst.Len() != l {
  1734. dst.Set(reflect.MakeSlice(typ, l, l))
  1735. }
  1736. s := dst
  1737. ctx.putTyped(o.self, typ, s.Interface())
  1738. for i := 0; i < l; i++ {
  1739. item := o.self.getIdx(valueInt(int64(i)), nil)
  1740. err := r.toReflectValue(item, s.Index(i), ctx)
  1741. if err != nil {
  1742. return fmt.Errorf("could not convert array element %v to %v at %d: %w", v, typ, i, err)
  1743. }
  1744. }
  1745. return nil
  1746. }
  1747. }
  1748. case reflect.Map:
  1749. if o, ok := v.(*Object); ok {
  1750. if v, exists := ctx.getTyped(o.self, typ); exists {
  1751. dst.Set(reflect.ValueOf(v))
  1752. return nil
  1753. }
  1754. if dst.IsNil() {
  1755. dst.Set(reflect.MakeMap(typ))
  1756. }
  1757. m := dst
  1758. ctx.putTyped(o.self, typ, m.Interface())
  1759. keyTyp := typ.Key()
  1760. elemTyp := typ.Elem()
  1761. needConvertKeys := !reflect.ValueOf("").Type().AssignableTo(keyTyp)
  1762. iter := &enumerableIter{
  1763. o: o,
  1764. wrapped: o.self.iterateStringKeys(),
  1765. }
  1766. for item, next := iter.next(); next != nil; item, next = next() {
  1767. var kv reflect.Value
  1768. var err error
  1769. if needConvertKeys {
  1770. kv = reflect.New(keyTyp).Elem()
  1771. err = r.toReflectValue(item.name, kv, ctx)
  1772. if err != nil {
  1773. return fmt.Errorf("could not convert map key %s to %v", item.name.String(), typ)
  1774. }
  1775. } else {
  1776. kv = reflect.ValueOf(item.name.String())
  1777. }
  1778. ival := o.self.getStr(item.name.string(), nil)
  1779. if ival != nil {
  1780. vv := reflect.New(elemTyp).Elem()
  1781. err := r.toReflectValue(ival, vv, ctx)
  1782. if err != nil {
  1783. return fmt.Errorf("could not convert map value %v to %v at key %s", ival, typ, item.name.String())
  1784. }
  1785. m.SetMapIndex(kv, vv)
  1786. } else {
  1787. m.SetMapIndex(kv, reflect.Zero(elemTyp))
  1788. }
  1789. }
  1790. return nil
  1791. }
  1792. case reflect.Struct:
  1793. if o, ok := v.(*Object); ok {
  1794. t := reflect.PtrTo(typ)
  1795. if v, exists := ctx.getTyped(o.self, t); exists {
  1796. dst.Set(reflect.ValueOf(v).Elem())
  1797. return nil
  1798. }
  1799. s := dst
  1800. ctx.putTyped(o.self, t, s.Addr().Interface())
  1801. for i := 0; i < typ.NumField(); i++ {
  1802. field := typ.Field(i)
  1803. if ast.IsExported(field.Name) {
  1804. name := field.Name
  1805. if r.fieldNameMapper != nil {
  1806. name = r.fieldNameMapper.FieldName(typ, field)
  1807. }
  1808. var v Value
  1809. if field.Anonymous {
  1810. v = o
  1811. } else {
  1812. v = o.self.getStr(unistring.NewFromString(name), nil)
  1813. }
  1814. if v != nil {
  1815. err := r.toReflectValue(v, s.Field(i), ctx)
  1816. if err != nil {
  1817. return fmt.Errorf("could not convert struct value %v to %v for field %s: %w", v, field.Type, field.Name, err)
  1818. }
  1819. }
  1820. }
  1821. }
  1822. return nil
  1823. }
  1824. case reflect.Func:
  1825. if fn, ok := AssertFunction(v); ok {
  1826. dst.Set(reflect.MakeFunc(typ, r.wrapJSFunc(fn, typ)))
  1827. return nil
  1828. }
  1829. case reflect.Ptr:
  1830. if o, ok := v.(*Object); ok {
  1831. if v, exists := ctx.getTyped(o.self, typ); exists {
  1832. dst.Set(reflect.ValueOf(v))
  1833. return nil
  1834. }
  1835. }
  1836. if dst.IsNil() {
  1837. dst.Set(reflect.New(typ.Elem()))
  1838. }
  1839. return r.toReflectValue(v, dst.Elem(), ctx)
  1840. }
  1841. return fmt.Errorf("could not convert %v to %v", v, typ)
  1842. }
  1843. func (r *Runtime) wrapJSFunc(fn Callable, typ reflect.Type) func(args []reflect.Value) (results []reflect.Value) {
  1844. return func(args []reflect.Value) (results []reflect.Value) {
  1845. jsArgs := make([]Value, len(args))
  1846. for i, arg := range args {
  1847. jsArgs[i] = r.ToValue(arg.Interface())
  1848. }
  1849. results = make([]reflect.Value, typ.NumOut())
  1850. res, err := fn(_undefined, jsArgs...)
  1851. if err == nil {
  1852. if typ.NumOut() > 0 {
  1853. v := reflect.New(typ.Out(0)).Elem()
  1854. err = r.toReflectValue(res, v, &objectExportCtx{})
  1855. if err == nil {
  1856. results[0] = v
  1857. }
  1858. }
  1859. }
  1860. if err != nil {
  1861. if typ.NumOut() == 2 && typ.Out(1).Name() == "error" {
  1862. results[1] = reflect.ValueOf(err).Convert(typ.Out(1))
  1863. } else {
  1864. panic(err)
  1865. }
  1866. }
  1867. for i, v := range results {
  1868. if !v.IsValid() {
  1869. results[i] = reflect.Zero(typ.Out(i))
  1870. }
  1871. }
  1872. return
  1873. }
  1874. }
  1875. // ExportTo converts a JavaScript value into the specified Go value. The second parameter must be a non-nil pointer.
  1876. // Exporting to an interface{} results in a value of the same type as Export() would produce.
  1877. // Exporting to numeric types uses the standard ECMAScript conversion operations, same as used when assigning
  1878. // values to non-clamped typed array items, e.g. https://262.ecma-international.org/#sec-toint32
  1879. // Returns error if conversion is not possible.
  1880. func (r *Runtime) ExportTo(v Value, target interface{}) error {
  1881. tval := reflect.ValueOf(target)
  1882. if tval.Kind() != reflect.Ptr || tval.IsNil() {
  1883. return errors.New("target must be a non-nil pointer")
  1884. }
  1885. return r.toReflectValue(v, tval.Elem(), &objectExportCtx{})
  1886. }
  1887. // GlobalObject returns the global object.
  1888. func (r *Runtime) GlobalObject() *Object {
  1889. return r.globalObject
  1890. }
  1891. // Set the specified variable in the global context.
  1892. // Equivalent to running "name = value" in non-strict mode.
  1893. // The value is first converted using ToValue().
  1894. // Note, this is not the same as GlobalObject().Set(name, value),
  1895. // because if a global lexical binding (let or const) exists, it is set instead.
  1896. func (r *Runtime) Set(name string, value interface{}) error {
  1897. return r.try(func() {
  1898. name := unistring.NewFromString(name)
  1899. v := r.ToValue(value)
  1900. if ref := r.global.stash.getRefByName(name, false); ref != nil {
  1901. ref.set(v)
  1902. } else {
  1903. r.globalObject.self.setOwnStr(name, v, true)
  1904. }
  1905. })
  1906. }
  1907. // Get the specified variable in the global context.
  1908. // Equivalent to dereferencing a variable by name in non-strict mode. If variable is not defined returns nil.
  1909. // Note, this is not the same as GlobalObject().Get(name),
  1910. // because if a global lexical binding (let or const) exists, it is used instead.
  1911. // This method will panic with an *Exception if a JavaScript exception is thrown in the process.
  1912. func (r *Runtime) Get(name string) (ret Value) {
  1913. r.tryPanic(func() {
  1914. n := unistring.NewFromString(name)
  1915. if v, exists := r.global.stash.getByName(n); exists {
  1916. ret = v
  1917. } else {
  1918. ret = r.globalObject.self.getStr(n, nil)
  1919. }
  1920. })
  1921. return
  1922. }
  1923. // SetRandSource sets random source for this Runtime. If not called, the default math/rand is used.
  1924. func (r *Runtime) SetRandSource(source RandSource) {
  1925. r.rand = source
  1926. }
  1927. // SetTimeSource sets the current time source for this Runtime.
  1928. // If not called, the default time.Now() is used.
  1929. func (r *Runtime) SetTimeSource(now Now) {
  1930. r.now = now
  1931. }
  1932. // SetParserOptions sets parser options to be used by RunString, RunScript and eval() within the code.
  1933. func (r *Runtime) SetParserOptions(opts ...parser.Option) {
  1934. r.parserOptions = opts
  1935. }
  1936. // SetMaxCallStackSize sets the maximum function call depth. When exceeded, a *StackOverflowError is thrown and
  1937. // returned by RunProgram or by a Callable call. This is useful to prevent memory exhaustion caused by an
  1938. // infinite recursion. The default value is math.MaxInt32.
  1939. // This method (as the rest of the Set* methods) is not safe for concurrent use and may only be called
  1940. // from the vm goroutine or when the vm is not running.
  1941. func (r *Runtime) SetMaxCallStackSize(size int) {
  1942. r.vm.maxCallStackSize = size
  1943. }
  1944. // New is an equivalent of the 'new' operator allowing to call it directly from Go.
  1945. func (r *Runtime) New(construct Value, args ...Value) (o *Object, err error) {
  1946. err = r.try(func() {
  1947. o = r.builtin_new(r.toObject(construct), args)
  1948. })
  1949. return
  1950. }
  1951. // Callable represents a JavaScript function that can be called from Go.
  1952. type Callable func(this Value, args ...Value) (Value, error)
  1953. // AssertFunction checks if the Value is a function and returns a Callable.
  1954. func AssertFunction(v Value) (Callable, bool) {
  1955. if obj, ok := v.(*Object); ok {
  1956. if f, ok := obj.self.assertCallable(); ok {
  1957. return func(this Value, args ...Value) (ret Value, err error) {
  1958. defer func() {
  1959. if x := recover(); x != nil {
  1960. if ex, ok := x.(*uncatchableException); ok {
  1961. err = ex.err
  1962. } else {
  1963. panic(x)
  1964. }
  1965. }
  1966. }()
  1967. ex := obj.runtime.vm.try(func() {
  1968. ret = f(FunctionCall{
  1969. This: this,
  1970. Arguments: args,
  1971. })
  1972. })
  1973. if ex != nil {
  1974. err = ex
  1975. }
  1976. vm := obj.runtime.vm
  1977. vm.clearStack()
  1978. if len(vm.callStack) == 0 {
  1979. obj.runtime.leave()
  1980. }
  1981. return
  1982. }, true
  1983. }
  1984. }
  1985. return nil, false
  1986. }
  1987. // IsUndefined returns true if the supplied Value is undefined. Note, it checks against the real undefined, not
  1988. // against the global object's 'undefined' property.
  1989. func IsUndefined(v Value) bool {
  1990. return v == _undefined
  1991. }
  1992. // IsNull returns true if the supplied Value is null.
  1993. func IsNull(v Value) bool {
  1994. return v == _null
  1995. }
  1996. // IsNaN returns true if the supplied value is NaN.
  1997. func IsNaN(v Value) bool {
  1998. f, ok := v.(valueFloat)
  1999. return ok && math.IsNaN(float64(f))
  2000. }
  2001. // IsInfinity returns true if the supplied is (+/-)Infinity
  2002. func IsInfinity(v Value) bool {
  2003. return v == _positiveInf || v == _negativeInf
  2004. }
  2005. // Undefined returns JS undefined value. Note if global 'undefined' property is changed this still returns the original value.
  2006. func Undefined() Value {
  2007. return _undefined
  2008. }
  2009. // Null returns JS null value.
  2010. func Null() Value {
  2011. return _null
  2012. }
  2013. // NaN returns a JS NaN value.
  2014. func NaN() Value {
  2015. return _NaN
  2016. }
  2017. // PositiveInf returns a JS +Inf value.
  2018. func PositiveInf() Value {
  2019. return _positiveInf
  2020. }
  2021. // NegativeInf returns a JS -Inf value.
  2022. func NegativeInf() Value {
  2023. return _negativeInf
  2024. }
  2025. func tryFunc(f func()) (ret interface{}) {
  2026. defer func() {
  2027. ret = recover()
  2028. }()
  2029. f()
  2030. return
  2031. }
  2032. func (r *Runtime) try(f func()) error {
  2033. if ex := r.vm.try(f); ex != nil {
  2034. return ex
  2035. }
  2036. return nil
  2037. }
  2038. func (r *Runtime) tryPanic(f func()) {
  2039. if ex := r.vm.try(f); ex != nil {
  2040. panic(ex)
  2041. }
  2042. }
  2043. func (r *Runtime) toObject(v Value, args ...interface{}) *Object {
  2044. if obj, ok := v.(*Object); ok {
  2045. return obj
  2046. }
  2047. if len(args) > 0 {
  2048. panic(r.NewTypeError(args...))
  2049. } else {
  2050. var s string
  2051. if v == nil {
  2052. s = "undefined"
  2053. } else {
  2054. s = v.String()
  2055. }
  2056. panic(r.NewTypeError("Value is not an object: %s", s))
  2057. }
  2058. }
  2059. func (r *Runtime) toNumber(v Value) Value {
  2060. switch o := v.(type) {
  2061. case valueInt, valueFloat:
  2062. return v
  2063. case *Object:
  2064. if pvo, ok := o.self.(*primitiveValueObject); ok {
  2065. return r.toNumber(pvo.pValue)
  2066. }
  2067. }
  2068. panic(r.NewTypeError("Value is not a number: %s", v))
  2069. }
  2070. func (r *Runtime) speciesConstructor(o, defaultConstructor *Object) func(args []Value, newTarget *Object) *Object {
  2071. c := o.self.getStr("constructor", nil)
  2072. if c != nil && c != _undefined {
  2073. c = r.toObject(c).self.getSym(SymSpecies, nil)
  2074. }
  2075. if c == nil || c == _undefined || c == _null {
  2076. c = defaultConstructor
  2077. }
  2078. return r.toConstructor(c)
  2079. }
  2080. func (r *Runtime) speciesConstructorObj(o, defaultConstructor *Object) *Object {
  2081. c := o.self.getStr("constructor", nil)
  2082. if c != nil && c != _undefined {
  2083. c = r.toObject(c).self.getSym(SymSpecies, nil)
  2084. }
  2085. if c == nil || c == _undefined || c == _null {
  2086. return defaultConstructor
  2087. }
  2088. obj := r.toObject(c)
  2089. if obj.self.assertConstructor() == nil {
  2090. panic(r.NewTypeError("Value is not a constructor"))
  2091. }
  2092. return obj
  2093. }
  2094. func (r *Runtime) returnThis(call FunctionCall) Value {
  2095. return call.This
  2096. }
  2097. func createDataProperty(o *Object, p Value, v Value) {
  2098. o.defineOwnProperty(p, PropertyDescriptor{
  2099. Writable: FLAG_TRUE,
  2100. Enumerable: FLAG_TRUE,
  2101. Configurable: FLAG_TRUE,
  2102. Value: v,
  2103. }, false)
  2104. }
  2105. func createDataPropertyOrThrow(o *Object, p Value, v Value) {
  2106. o.defineOwnProperty(p, PropertyDescriptor{
  2107. Writable: FLAG_TRUE,
  2108. Enumerable: FLAG_TRUE,
  2109. Configurable: FLAG_TRUE,
  2110. Value: v,
  2111. }, true)
  2112. }
  2113. func toPropertyKey(key Value) Value {
  2114. return key.ToString()
  2115. }
  2116. func (r *Runtime) getVStr(v Value, p unistring.String) Value {
  2117. o := v.ToObject(r)
  2118. return o.self.getStr(p, v)
  2119. }
  2120. func (r *Runtime) getV(v Value, p Value) Value {
  2121. o := v.ToObject(r)
  2122. return o.get(p, v)
  2123. }
  2124. type iteratorRecord struct {
  2125. iterator *Object
  2126. next func(FunctionCall) Value
  2127. }
  2128. func (r *Runtime) getIterator(obj Value, method func(FunctionCall) Value) *iteratorRecord {
  2129. if method == nil {
  2130. method = toMethod(r.getV(obj, SymIterator))
  2131. if method == nil {
  2132. panic(r.NewTypeError("object is not iterable"))
  2133. }
  2134. }
  2135. iter := r.toObject(method(FunctionCall{
  2136. This: obj,
  2137. }))
  2138. next := toMethod(iter.self.getStr("next", nil))
  2139. return &iteratorRecord{
  2140. iterator: iter,
  2141. next: next,
  2142. }
  2143. }
  2144. func (ir *iteratorRecord) iterate(step func(Value)) {
  2145. r := ir.iterator.runtime
  2146. for {
  2147. res := r.toObject(ir.next(FunctionCall{This: ir.iterator}))
  2148. if nilSafe(res.self.getStr("done", nil)).ToBoolean() {
  2149. break
  2150. }
  2151. value := nilSafe(res.self.getStr("value", nil))
  2152. ret := tryFunc(func() {
  2153. step(value)
  2154. })
  2155. if ret != nil {
  2156. _ = tryFunc(func() {
  2157. ir.returnIter()
  2158. })
  2159. panic(ret)
  2160. }
  2161. }
  2162. }
  2163. func (ir *iteratorRecord) step() (value Value, ex *Exception) {
  2164. r := ir.iterator.runtime
  2165. ex = r.vm.try(func() {
  2166. res := r.toObject(ir.next(FunctionCall{This: ir.iterator}))
  2167. done := nilSafe(res.self.getStr("done", nil)).ToBoolean()
  2168. if !done {
  2169. value = nilSafe(res.self.getStr("value", nil))
  2170. } else {
  2171. ir.close()
  2172. }
  2173. })
  2174. return
  2175. }
  2176. func (ir *iteratorRecord) returnIter() {
  2177. if ir.iterator == nil {
  2178. return
  2179. }
  2180. retMethod := toMethod(ir.iterator.self.getStr("return", nil))
  2181. if retMethod != nil {
  2182. ir.iterator.runtime.toObject(retMethod(FunctionCall{This: ir.iterator}))
  2183. }
  2184. ir.iterator = nil
  2185. ir.next = nil
  2186. }
  2187. func (ir *iteratorRecord) close() {
  2188. ir.iterator = nil
  2189. ir.next = nil
  2190. }
  2191. func (r *Runtime) createIterResultObject(value Value, done bool) Value {
  2192. o := r.NewObject()
  2193. o.self.setOwnStr("value", value, false)
  2194. o.self.setOwnStr("done", r.toBoolean(done), false)
  2195. return o
  2196. }
  2197. func (r *Runtime) newLazyObject(create func(*Object) objectImpl) *Object {
  2198. val := &Object{runtime: r}
  2199. o := &lazyObject{
  2200. val: val,
  2201. create: create,
  2202. }
  2203. val.self = o
  2204. return val
  2205. }
  2206. func (r *Runtime) getHash() *maphash.Hash {
  2207. if r.hash == nil {
  2208. r.hash = &maphash.Hash{}
  2209. }
  2210. return r.hash
  2211. }
  2212. // called when the top level function returns (i.e. control is passed outside the Runtime).
  2213. func (r *Runtime) leave() {
  2214. for {
  2215. jobs := r.jobQueue
  2216. r.jobQueue = nil
  2217. if len(jobs) == 0 {
  2218. break
  2219. }
  2220. for _, job := range jobs {
  2221. job()
  2222. }
  2223. }
  2224. }
  2225. func nilSafe(v Value) Value {
  2226. if v != nil {
  2227. return v
  2228. }
  2229. return _undefined
  2230. }
  2231. func isArray(object *Object) bool {
  2232. self := object.self
  2233. if proxy, ok := self.(*proxyObject); ok {
  2234. if proxy.target == nil {
  2235. panic(typeError("Cannot perform 'IsArray' on a proxy that has been revoked"))
  2236. }
  2237. return isArray(proxy.target)
  2238. }
  2239. switch self.className() {
  2240. case classArray:
  2241. return true
  2242. default:
  2243. return false
  2244. }
  2245. }
  2246. func isRegexp(v Value) bool {
  2247. if o, ok := v.(*Object); ok {
  2248. matcher := o.self.getSym(SymMatch, nil)
  2249. if matcher != nil && matcher != _undefined {
  2250. return matcher.ToBoolean()
  2251. }
  2252. _, reg := o.self.(*regexpObject)
  2253. return reg
  2254. }
  2255. return false
  2256. }
  2257. func limitCallArgs(call FunctionCall, n int) FunctionCall {
  2258. if len(call.Arguments) > n {
  2259. return FunctionCall{This: call.This, Arguments: call.Arguments[:n]}
  2260. } else {
  2261. return call
  2262. }
  2263. }
  2264. func shrinkCap(newSize, oldCap int) int {
  2265. if oldCap > 8 {
  2266. if cap := oldCap / 2; cap >= newSize {
  2267. return cap
  2268. }
  2269. }
  2270. return oldCap
  2271. }
  2272. func growCap(newSize, oldSize, oldCap int) int {
  2273. // Use the same algorithm as in runtime.growSlice
  2274. doublecap := oldCap + oldCap
  2275. if newSize > doublecap {
  2276. return newSize
  2277. } else {
  2278. if oldSize < 1024 {
  2279. return doublecap
  2280. } else {
  2281. cap := oldCap
  2282. // Check 0 < cap to detect overflow
  2283. // and prevent an infinite loop.
  2284. for 0 < cap && cap < newSize {
  2285. cap += cap / 4
  2286. }
  2287. // Return the requested cap when
  2288. // the calculation overflowed.
  2289. if cap <= 0 {
  2290. return newSize
  2291. }
  2292. return cap
  2293. }
  2294. }
  2295. }
  2296. func (r *Runtime) genId() (ret uint64) {
  2297. if r.hash == nil {
  2298. h := r.getHash()
  2299. r.idSeq = h.Sum64()
  2300. }
  2301. if r.idSeq == 0 {
  2302. r.idSeq = 1
  2303. }
  2304. ret = r.idSeq
  2305. r.idSeq++
  2306. return
  2307. }
  2308. func (r *Runtime) setGlobal(name unistring.String, v Value, strict bool) {
  2309. if ref := r.global.stash.getRefByName(name, strict); ref != nil {
  2310. ref.set(v)
  2311. } else {
  2312. o := r.globalObject.self
  2313. if strict {
  2314. if o.hasOwnPropertyStr(name) {
  2315. o.setOwnStr(name, v, true)
  2316. } else {
  2317. r.throwReferenceError(name)
  2318. }
  2319. } else {
  2320. o.setOwnStr(name, v, false)
  2321. }
  2322. }
  2323. }
  2324. func (r *Runtime) trackPromiseRejection(p *Promise, operation PromiseRejectionOperation) {
  2325. if r.promiseRejectionTracker != nil {
  2326. r.promiseRejectionTracker(p, operation)
  2327. }
  2328. }
  2329. func (r *Runtime) callJobCallback(job *jobCallback, this Value, args ...Value) Value {
  2330. return job.callback(FunctionCall{This: this, Arguments: args})
  2331. }
  2332. func (r *Runtime) invoke(v Value, p unistring.String, args ...Value) Value {
  2333. o := v.ToObject(r)
  2334. return r.toCallable(o.self.getStr(p, nil))(FunctionCall{This: v, Arguments: args})
  2335. }
  2336. func (r *Runtime) iterableToList(items Value, method func(FunctionCall) Value) []Value {
  2337. iter := r.getIterator(items, method)
  2338. var values []Value
  2339. iter.iterate(func(item Value) {
  2340. values = append(values, item)
  2341. })
  2342. return values
  2343. }
  2344. func (r *Runtime) putSpeciesReturnThis(o objectImpl) {
  2345. o._putSym(SymSpecies, &valueProperty{
  2346. getterFunc: r.newNativeFunc(r.returnThis, nil, "get [Symbol.species]", nil, 0),
  2347. accessor: true,
  2348. configurable: true,
  2349. })
  2350. }
  2351. func strToArrayIdx(s unistring.String) uint32 {
  2352. if s == "" {
  2353. return math.MaxUint32
  2354. }
  2355. l := len(s)
  2356. if s[0] == '0' {
  2357. if l == 1 {
  2358. return 0
  2359. }
  2360. return math.MaxUint32
  2361. }
  2362. var n uint32
  2363. if l < 10 {
  2364. // guaranteed not to overflow
  2365. for i := 0; i < len(s); i++ {
  2366. c := s[i]
  2367. if c < '0' || c > '9' {
  2368. return math.MaxUint32
  2369. }
  2370. n = n*10 + uint32(c-'0')
  2371. }
  2372. return n
  2373. }
  2374. if l > 10 {
  2375. // guaranteed to overflow
  2376. return math.MaxUint32
  2377. }
  2378. c9 := s[9]
  2379. if c9 < '0' || c9 > '9' {
  2380. return math.MaxUint32
  2381. }
  2382. for i := 0; i < 9; i++ {
  2383. c := s[i]
  2384. if c < '0' || c > '9' {
  2385. return math.MaxUint32
  2386. }
  2387. n = n*10 + uint32(c-'0')
  2388. }
  2389. if n >= math.MaxUint32/10+1 {
  2390. return math.MaxUint32
  2391. }
  2392. n *= 10
  2393. n1 := n + uint32(c9-'0')
  2394. if n1 < n {
  2395. return math.MaxUint32
  2396. }
  2397. return n1
  2398. }
  2399. func strToInt32(s unistring.String) (int32, bool) {
  2400. if s == "" {
  2401. return -1, false
  2402. }
  2403. neg := s[0] == '-'
  2404. if neg {
  2405. s = s[1:]
  2406. }
  2407. l := len(s)
  2408. if s[0] == '0' {
  2409. if l == 1 {
  2410. return 0, !neg
  2411. }
  2412. return -1, false
  2413. }
  2414. var n uint32
  2415. if l < 10 {
  2416. // guaranteed not to overflow
  2417. for i := 0; i < len(s); i++ {
  2418. c := s[i]
  2419. if c < '0' || c > '9' {
  2420. return -1, false
  2421. }
  2422. n = n*10 + uint32(c-'0')
  2423. }
  2424. } else if l > 10 {
  2425. // guaranteed to overflow
  2426. return -1, false
  2427. } else {
  2428. c9 := s[9]
  2429. if c9 >= '0' {
  2430. if !neg && c9 > '7' || c9 > '8' {
  2431. // guaranteed to overflow
  2432. return -1, false
  2433. }
  2434. for i := 0; i < 9; i++ {
  2435. c := s[i]
  2436. if c < '0' || c > '9' {
  2437. return -1, false
  2438. }
  2439. n = n*10 + uint32(c-'0')
  2440. }
  2441. if n >= math.MaxInt32/10+1 {
  2442. // valid number, but it overflows integer
  2443. return 0, false
  2444. }
  2445. n = n*10 + uint32(c9-'0')
  2446. } else {
  2447. return -1, false
  2448. }
  2449. }
  2450. if neg {
  2451. return int32(-n), true
  2452. }
  2453. return int32(n), true
  2454. }
  2455. func strToInt64(s unistring.String) (int64, bool) {
  2456. if s == "" {
  2457. return -1, false
  2458. }
  2459. neg := s[0] == '-'
  2460. if neg {
  2461. s = s[1:]
  2462. }
  2463. l := len(s)
  2464. if s[0] == '0' {
  2465. if l == 1 {
  2466. return 0, !neg
  2467. }
  2468. return -1, false
  2469. }
  2470. var n uint64
  2471. if l < 19 {
  2472. // guaranteed not to overflow
  2473. for i := 0; i < len(s); i++ {
  2474. c := s[i]
  2475. if c < '0' || c > '9' {
  2476. return -1, false
  2477. }
  2478. n = n*10 + uint64(c-'0')
  2479. }
  2480. } else if l > 19 {
  2481. // guaranteed to overflow
  2482. return -1, false
  2483. } else {
  2484. c18 := s[18]
  2485. if c18 >= '0' {
  2486. if !neg && c18 > '7' || c18 > '8' {
  2487. // guaranteed to overflow
  2488. return -1, false
  2489. }
  2490. for i := 0; i < 18; i++ {
  2491. c := s[i]
  2492. if c < '0' || c > '9' {
  2493. return -1, false
  2494. }
  2495. n = n*10 + uint64(c-'0')
  2496. }
  2497. if n >= math.MaxInt64/10+1 {
  2498. // valid number, but it overflows integer
  2499. return 0, false
  2500. }
  2501. n = n*10 + uint64(c18-'0')
  2502. } else {
  2503. return -1, false
  2504. }
  2505. }
  2506. if neg {
  2507. return int64(-n), true
  2508. }
  2509. return int64(n), true
  2510. }
  2511. func strToInt(s unistring.String) (int, bool) {
  2512. if bits.UintSize == 32 {
  2513. n, ok := strToInt32(s)
  2514. return int(n), ok
  2515. }
  2516. n, ok := strToInt64(s)
  2517. return int(n), ok
  2518. }
  2519. // Attempts to convert a string into a canonical integer.
  2520. // On success returns (number, true).
  2521. // If it was a canonical number, but not an integer returns (0, false). This includes -0 and overflows.
  2522. // In all other cases returns (-1, false).
  2523. // See https://262.ecma-international.org/#sec-canonicalnumericindexstring
  2524. func strToIntNum(s unistring.String) (int, bool) {
  2525. n, ok := strToInt64(s)
  2526. if n == 0 {
  2527. return 0, ok
  2528. }
  2529. if ok && n >= -maxInt && n <= maxInt {
  2530. if bits.UintSize == 32 {
  2531. if n > math.MaxInt32 || n < math.MinInt32 {
  2532. return 0, false
  2533. }
  2534. }
  2535. return int(n), true
  2536. }
  2537. str := stringValueFromRaw(s)
  2538. if str.ToNumber().toString().SameAs(str) {
  2539. return 0, false
  2540. }
  2541. return -1, false
  2542. }
  2543. func strToGoIdx(s unistring.String) int {
  2544. if n, ok := strToInt(s); ok {
  2545. return n
  2546. }
  2547. return -1
  2548. }
  2549. func strToIdx64(s unistring.String) int64 {
  2550. if n, ok := strToInt64(s); ok {
  2551. return n
  2552. }
  2553. return -1
  2554. }
  2555. func assertCallable(v Value) (func(FunctionCall) Value, bool) {
  2556. if obj, ok := v.(*Object); ok {
  2557. return obj.self.assertCallable()
  2558. }
  2559. return nil, false
  2560. }