runtime.go 68 KB

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