runtime.go 78 KB

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