runtime.go 80 KB

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