state.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  1. package lua
  2. ////////////////////////////////////////////////////////
  3. // This file was generated by go-inline. DO NOT EDIT. //
  4. ////////////////////////////////////////////////////////
  5. import (
  6. "bufio"
  7. "fmt"
  8. "github.com/vmihailenco/msgpack"
  9. "github.com/yuin/gopher-lua/parse"
  10. "golang.org/x/net/context"
  11. "io"
  12. "io/ioutil"
  13. "math"
  14. "os"
  15. "runtime"
  16. "strings"
  17. "sync/atomic"
  18. "time"
  19. )
  20. const MultRet = -1
  21. const RegistryIndex = -10000
  22. const EnvironIndex = -10001
  23. const GlobalsIndex = -10002
  24. /* ApiError {{{ */
  25. type ApiError struct {
  26. Type ApiErrorType
  27. Object LValue
  28. StackTrace string
  29. // Underlying error. This attribute is set only if the Type is ApiErrorFile or ApiErrorSyntax
  30. Cause error
  31. }
  32. func newApiError(code ApiErrorType, object LValue) *ApiError {
  33. return &ApiError{code, object, "", nil}
  34. }
  35. func newApiErrorS(code ApiErrorType, message string) *ApiError {
  36. return newApiError(code, LString(message))
  37. }
  38. func newApiErrorE(code ApiErrorType, err error) *ApiError {
  39. return &ApiError{code, LString(err.Error()), "", err}
  40. }
  41. func (e *ApiError) Error() string {
  42. if len(e.StackTrace) > 0 {
  43. return fmt.Sprintf("%s\n%s", e.Object.String(), e.StackTrace)
  44. }
  45. return e.Object.String()
  46. }
  47. type ApiErrorType int
  48. const (
  49. ApiErrorSyntax ApiErrorType = iota
  50. ApiErrorFile
  51. ApiErrorRun
  52. ApiErrorError
  53. ApiErrorPanic
  54. )
  55. /* }}} */
  56. /* ResumeState {{{ */
  57. type ResumeState int
  58. const (
  59. ResumeOK ResumeState = iota
  60. ResumeYield
  61. ResumeError
  62. )
  63. /* }}} */
  64. /* P {{{ */
  65. type P struct {
  66. Fn LValue
  67. NRet int
  68. Protect bool
  69. Handler *LFunction
  70. }
  71. /* }}} */
  72. /* Options {{{ */
  73. // Options is a configuration that is used to create a new LState.
  74. type Options struct {
  75. // Call stack size. This defaults to `lua.CallStackSize`.
  76. CallStackSize int
  77. // Data stack size. This defaults to `lua.RegistrySize`.
  78. RegistrySize int
  79. // Controls whether or not libraries are opened by default
  80. SkipOpenLibs bool
  81. // Tells whether a Go stacktrace should be included in a Lua stacktrace when panics occur.
  82. IncludeGoStackTrace bool
  83. }
  84. /* }}} */
  85. /* Debug {{{ */
  86. type Debug struct {
  87. frame *callFrame
  88. Name string
  89. What string
  90. Source string
  91. CurrentLine int
  92. NUpvalues int
  93. LineDefined int
  94. LastLineDefined int
  95. }
  96. /* }}} */
  97. /* callFrame {{{ */
  98. type callFrame struct {
  99. Idx int
  100. Fn *LFunction
  101. Parent *callFrame
  102. Pc int
  103. Base int
  104. LocalBase int
  105. ReturnBase int
  106. NArgs int
  107. NRet int
  108. TailCall int
  109. }
  110. type callFrameStack struct {
  111. array []callFrame
  112. sp int
  113. }
  114. func newCallFrameStack(size int) *callFrameStack {
  115. return &callFrameStack{
  116. array: make([]callFrame, size),
  117. sp: 0,
  118. }
  119. }
  120. func (cs *callFrameStack) IsEmpty() bool { return cs.sp == 0 }
  121. func (cs *callFrameStack) Clear() {
  122. cs.sp = 0
  123. }
  124. func (cs *callFrameStack) Push(v callFrame) { // +inline-start
  125. cs.array[cs.sp] = v
  126. cs.array[cs.sp].Idx = cs.sp
  127. cs.sp++
  128. } // +inline-end
  129. func (cs *callFrameStack) Remove(sp int) {
  130. psp := sp - 1
  131. nsp := sp + 1
  132. var pre *callFrame
  133. var next *callFrame
  134. if psp > 0 {
  135. pre = &cs.array[psp]
  136. }
  137. if nsp < cs.sp {
  138. next = &cs.array[nsp]
  139. }
  140. if next != nil {
  141. next.Parent = pre
  142. }
  143. for i := sp; i+1 < cs.sp; i++ {
  144. cs.array[i] = cs.array[i+1]
  145. cs.array[i].Idx = i
  146. cs.sp = i
  147. }
  148. cs.sp++
  149. }
  150. func (cs *callFrameStack) Sp() int {
  151. return cs.sp
  152. }
  153. func (cs *callFrameStack) SetSp(sp int) {
  154. cs.sp = sp
  155. }
  156. func (cs *callFrameStack) Last() *callFrame {
  157. if cs.sp == 0 {
  158. return nil
  159. }
  160. return &cs.array[cs.sp-1]
  161. }
  162. func (cs *callFrameStack) At(sp int) *callFrame {
  163. return &cs.array[sp]
  164. }
  165. func (cs *callFrameStack) Pop() *callFrame {
  166. cs.sp--
  167. return &cs.array[cs.sp]
  168. }
  169. /* }}} */
  170. /* registry {{{ */
  171. type registry struct {
  172. array []LValue
  173. top int
  174. alloc *allocator
  175. }
  176. func newRegistry(size int, alloc *allocator) *registry {
  177. return &registry{make([]LValue, size), 0, alloc}
  178. }
  179. func (rg *registry) SetTop(top int) {
  180. oldtop := rg.top
  181. rg.top = top
  182. for i := oldtop; i < rg.top; i++ {
  183. rg.array[i] = LNil
  184. }
  185. for i := rg.top; i < oldtop; i++ {
  186. rg.array[i] = LNil
  187. }
  188. }
  189. func (rg *registry) Top() int {
  190. return rg.top
  191. }
  192. func (rg *registry) Push(v LValue) {
  193. rg.array[rg.top] = v
  194. rg.top++
  195. }
  196. func (rg *registry) Pop() LValue {
  197. v := rg.array[rg.top-1]
  198. rg.array[rg.top-1] = LNil
  199. rg.top--
  200. return v
  201. }
  202. func (rg *registry) Get(reg int) LValue {
  203. return rg.array[reg]
  204. }
  205. func (rg *registry) CopyRange(regv, start, limit, n int) { // +inline-start
  206. for i := 0; i < n; i++ {
  207. if tidx := start + i; tidx >= rg.top || limit > -1 && tidx >= limit || tidx < 0 {
  208. rg.array[regv+i] = LNil
  209. } else {
  210. rg.array[regv+i] = rg.array[tidx]
  211. }
  212. }
  213. rg.top = regv + n
  214. } // +inline-end
  215. func (rg *registry) FillNil(regm, n int) { // +inline-start
  216. for i := 0; i < n; i++ {
  217. rg.array[regm+i] = LNil
  218. }
  219. rg.top = regm + n
  220. } // +inline-end
  221. func (rg *registry) Insert(value LValue, reg int) {
  222. top := rg.Top()
  223. if reg >= top {
  224. rg.Set(reg, value)
  225. return
  226. }
  227. top--
  228. for ; top >= reg; top-- {
  229. rg.Set(top+1, rg.Get(top))
  230. }
  231. rg.Set(reg, value)
  232. }
  233. func (rg *registry) Set(reg int, val LValue) {
  234. rg.array[reg] = val
  235. if reg >= rg.top {
  236. rg.top = reg + 1
  237. }
  238. }
  239. func (rg *registry) SetNumber(reg int, val LNumber) {
  240. rg.array[reg] = rg.alloc.LNumber2I(val)
  241. if reg >= rg.top {
  242. rg.top = reg + 1
  243. }
  244. } /* }}} */
  245. /* Global {{{ */
  246. func newGlobal() *Global {
  247. return &Global{
  248. MainThread: nil,
  249. Registry: newLTable(0, 32),
  250. Global: newLTable(0, 64),
  251. builtinMts: make(map[int]LValue),
  252. tempFiles: make([]*os.File, 0, 10),
  253. }
  254. }
  255. /* }}} */
  256. /* package local methods {{{ */
  257. func panicWithTraceback(L *LState) {
  258. err := newApiError(ApiErrorRun, L.Get(-1))
  259. err.StackTrace = L.stackTrace(0)
  260. panic(err)
  261. }
  262. func panicWithoutTraceback(L *LState) {
  263. err := newApiError(ApiErrorRun, L.Get(-1))
  264. panic(err)
  265. }
  266. func newLState(options Options) *LState {
  267. al := newAllocator(32)
  268. ls := &LState{
  269. G: newGlobal(),
  270. Parent: nil,
  271. Panic: panicWithTraceback,
  272. Dead: false,
  273. Options: options,
  274. stop: 0,
  275. reg: newRegistry(options.RegistrySize, al),
  276. stack: newCallFrameStack(options.CallStackSize),
  277. alloc: al,
  278. currentFrame: nil,
  279. wrapped: false,
  280. uvcache: nil,
  281. hasErrorFunc: false,
  282. mainLoop: mainLoop,
  283. ctx: nil,
  284. }
  285. ls.Env = ls.G.Global
  286. return ls
  287. }
  288. func (ls *LState) printReg() {
  289. println("-------------------------")
  290. println("thread:", ls)
  291. println("top:", ls.reg.Top())
  292. if ls.currentFrame != nil {
  293. println("function base:", ls.currentFrame.Base)
  294. println("return base:", ls.currentFrame.ReturnBase)
  295. } else {
  296. println("(vm not started)")
  297. }
  298. println("local base:", ls.currentLocalBase())
  299. for i := 0; i < ls.reg.Top(); i++ {
  300. println(i, ls.reg.Get(i).String())
  301. }
  302. println("-------------------------")
  303. }
  304. func (ls *LState) printCallStack() {
  305. println("-------------------------")
  306. for i := 0; i < ls.stack.Sp(); i++ {
  307. print(i)
  308. print(" ")
  309. frame := ls.stack.At(i)
  310. if frame == nil {
  311. break
  312. }
  313. if frame.Fn.IsG {
  314. println("IsG:", true, "Frame:", frame, "Fn:", frame.Fn)
  315. } else {
  316. println("IsG:", false, "Frame:", frame, "Fn:", frame.Fn, "pc:", frame.Pc)
  317. }
  318. }
  319. println("-------------------------")
  320. }
  321. func (ls *LState) closeAllUpvalues() { // +inline-start
  322. for cf := ls.currentFrame; cf != nil; cf = cf.Parent {
  323. if !cf.Fn.IsG {
  324. ls.closeUpvalues(cf.LocalBase)
  325. }
  326. }
  327. } // +inline-end
  328. func (ls *LState) raiseError(level int, format string, args ...interface{}) {
  329. if !ls.hasErrorFunc {
  330. ls.closeAllUpvalues()
  331. }
  332. message := format
  333. if len(args) > 0 {
  334. message = fmt.Sprintf(format, args...)
  335. }
  336. if level > 0 {
  337. message = fmt.Sprintf("%v %v", ls.where(level-1, true), message)
  338. }
  339. ls.reg.Push(LString(message))
  340. ls.Panic(ls)
  341. }
  342. func (ls *LState) findLocal(frame *callFrame, no int) string {
  343. fn := frame.Fn
  344. if !fn.IsG {
  345. if name, ok := fn.LocalName(no, frame.Pc-1); ok {
  346. return name
  347. }
  348. }
  349. var top int
  350. if ls.currentFrame == frame {
  351. top = ls.reg.Top()
  352. } else if frame.Idx+1 < ls.stack.Sp() {
  353. top = ls.stack.At(frame.Idx + 1).Base
  354. } else {
  355. return ""
  356. }
  357. if top-frame.LocalBase >= no {
  358. return "(*temporary)"
  359. }
  360. return ""
  361. }
  362. func (ls *LState) where(level int, skipg bool) string {
  363. dbg, ok := ls.GetStack(level)
  364. if !ok {
  365. return ""
  366. }
  367. cf := dbg.frame
  368. proto := cf.Fn.Proto
  369. sourcename := "[G]"
  370. if proto != nil {
  371. sourcename = proto.SourceName
  372. } else if skipg {
  373. return ls.where(level+1, skipg)
  374. }
  375. line := ""
  376. if proto != nil {
  377. line = fmt.Sprintf("%v:", proto.DbgSourcePositions[cf.Pc-1])
  378. }
  379. return fmt.Sprintf("%v:%v", sourcename, line)
  380. }
  381. func (ls *LState) stackTrace(level int) string {
  382. buf := []string{}
  383. header := "stack traceback:"
  384. if ls.currentFrame != nil {
  385. i := 0
  386. for dbg, ok := ls.GetStack(i); ok; dbg, ok = ls.GetStack(i) {
  387. cf := dbg.frame
  388. buf = append(buf, fmt.Sprintf("\t%v in %v", ls.Where(i), ls.formattedFrameFuncName(cf)))
  389. if !cf.Fn.IsG && cf.TailCall > 0 {
  390. for tc := cf.TailCall; tc > 0; tc-- {
  391. buf = append(buf, "\t(tailcall): ?")
  392. i++
  393. }
  394. }
  395. i++
  396. }
  397. }
  398. buf = append(buf, fmt.Sprintf("\t%v: %v", "[G]", "?"))
  399. buf = buf[intMax(0, intMin(level, len(buf))):len(buf)]
  400. if len(buf) > 20 {
  401. newbuf := make([]string, 0, 20)
  402. newbuf = append(newbuf, buf[0:7]...)
  403. newbuf = append(newbuf, "\t...")
  404. newbuf = append(newbuf, buf[len(buf)-7:len(buf)]...)
  405. buf = newbuf
  406. }
  407. return fmt.Sprintf("%s\n%s", header, strings.Join(buf, "\n"))
  408. }
  409. func (ls *LState) formattedFrameFuncName(fr *callFrame) string {
  410. name, ischunk := ls.frameFuncName(fr)
  411. if ischunk {
  412. return name
  413. }
  414. if name[0] != '(' && name[0] != '<' {
  415. return fmt.Sprintf("function '%s'", name)
  416. }
  417. return fmt.Sprintf("function %s", name)
  418. }
  419. func (ls *LState) rawFrameFuncName(fr *callFrame) string {
  420. name, _ := ls.frameFuncName(fr)
  421. return name
  422. }
  423. func (ls *LState) frameFuncName(fr *callFrame) (string, bool) {
  424. frame := fr.Parent
  425. if frame == nil {
  426. if ls.Parent == nil {
  427. return "main chunk", true
  428. } else {
  429. return "corountine", true
  430. }
  431. }
  432. if !frame.Fn.IsG {
  433. pc := frame.Pc - 1
  434. for _, call := range frame.Fn.Proto.DbgCalls {
  435. if call.Pc == pc {
  436. name := call.Name
  437. if (name == "?" || fr.TailCall > 0) && !fr.Fn.IsG {
  438. name = fmt.Sprintf("<%v:%v>", fr.Fn.Proto.SourceName, fr.Fn.Proto.LineDefined)
  439. }
  440. return name, false
  441. }
  442. }
  443. }
  444. if !fr.Fn.IsG {
  445. return fmt.Sprintf("<%v:%v>", fr.Fn.Proto.SourceName, fr.Fn.Proto.LineDefined), false
  446. }
  447. return "(anonymous)", false
  448. }
  449. func (ls *LState) isStarted() bool {
  450. return ls.currentFrame != nil
  451. }
  452. func (ls *LState) kill() {
  453. ls.Dead = true
  454. }
  455. func (ls *LState) indexToReg(idx int) int {
  456. base := ls.currentLocalBase()
  457. if idx > 0 {
  458. return base + idx - 1
  459. } else if idx == 0 {
  460. return -1
  461. } else {
  462. tidx := ls.reg.Top() + idx
  463. if tidx < base {
  464. return -1
  465. }
  466. return tidx
  467. }
  468. }
  469. func (ls *LState) currentLocalBase() int {
  470. base := 0
  471. if ls.currentFrame != nil {
  472. base = ls.currentFrame.LocalBase
  473. }
  474. return base
  475. }
  476. func (ls *LState) currentEnv() *LTable {
  477. return ls.Env
  478. /*
  479. if ls.currentFrame == nil {
  480. return ls.Env
  481. }
  482. return ls.currentFrame.Fn.Env
  483. */
  484. }
  485. func (ls *LState) rkValue(idx int) LValue {
  486. /*
  487. if OpIsK(idx) {
  488. return ls.currentFrame.Fn.Proto.Constants[opIndexK(idx)]
  489. }
  490. return ls.reg.Get(ls.currentFrame.LocalBase + idx)
  491. */
  492. if (idx & opBitRk) != 0 {
  493. return ls.currentFrame.Fn.Proto.Constants[idx & ^opBitRk]
  494. }
  495. return ls.reg.array[ls.currentFrame.LocalBase+idx]
  496. }
  497. func (ls *LState) rkString(idx int) string {
  498. if (idx & opBitRk) != 0 {
  499. return ls.currentFrame.Fn.Proto.stringConstants[idx & ^opBitRk]
  500. }
  501. return string(ls.reg.array[ls.currentFrame.LocalBase+idx].(LString))
  502. }
  503. func (ls *LState) closeUpvalues(idx int) { // +inline-start
  504. if ls.uvcache != nil {
  505. var prev *Upvalue
  506. for uv := ls.uvcache; uv != nil; uv = uv.next {
  507. if uv.index >= idx {
  508. if prev != nil {
  509. prev.next = nil
  510. } else {
  511. ls.uvcache = nil
  512. }
  513. uv.Close()
  514. }
  515. prev = uv
  516. }
  517. }
  518. } // +inline-end
  519. func (ls *LState) findUpvalue(idx int) *Upvalue {
  520. var prev *Upvalue
  521. var next *Upvalue
  522. if ls.uvcache != nil {
  523. for uv := ls.uvcache; uv != nil; uv = uv.next {
  524. if uv.index == idx {
  525. return uv
  526. }
  527. if uv.index > idx {
  528. next = uv
  529. break
  530. }
  531. prev = uv
  532. }
  533. }
  534. uv := &Upvalue{reg: ls.reg, index: idx, closed: false}
  535. if prev != nil {
  536. prev.next = uv
  537. } else {
  538. ls.uvcache = uv
  539. }
  540. if next != nil {
  541. uv.next = next
  542. }
  543. return uv
  544. }
  545. func (ls *LState) metatable(lvalue LValue, rawget bool) LValue {
  546. var metatable LValue = LNil
  547. switch obj := lvalue.(type) {
  548. case *LTable:
  549. metatable = obj.Metatable
  550. case *LUserData:
  551. metatable = obj.Metatable
  552. default:
  553. if table, ok := ls.G.builtinMts[int(obj.Type())]; ok {
  554. metatable = table
  555. }
  556. }
  557. if !rawget && metatable != LNil {
  558. oldmt := metatable
  559. if tb, ok := metatable.(*LTable); ok {
  560. metatable = tb.RawGetString("__metatable")
  561. if metatable == LNil {
  562. metatable = oldmt
  563. }
  564. }
  565. }
  566. return metatable
  567. }
  568. func (ls *LState) metaOp1(lvalue LValue, event string) LValue {
  569. if mt := ls.metatable(lvalue, true); mt != LNil {
  570. if tb, ok := mt.(*LTable); ok {
  571. return tb.RawGetString(event)
  572. }
  573. }
  574. return LNil
  575. }
  576. func (ls *LState) metaOp2(value1, value2 LValue, event string) LValue {
  577. if mt := ls.metatable(value1, true); mt != LNil {
  578. if tb, ok := mt.(*LTable); ok {
  579. if ret := tb.RawGetString(event); ret != LNil {
  580. return ret
  581. }
  582. }
  583. }
  584. if mt := ls.metatable(value2, true); mt != LNil {
  585. if tb, ok := mt.(*LTable); ok {
  586. return tb.RawGetString(event)
  587. }
  588. }
  589. return LNil
  590. }
  591. func (ls *LState) metaCall(lvalue LValue) (*LFunction, bool) {
  592. if fn, ok := lvalue.(*LFunction); ok {
  593. return fn, false
  594. }
  595. if fn, ok := ls.metaOp1(lvalue, "__call").(*LFunction); ok {
  596. return fn, true
  597. }
  598. return nil, false
  599. }
  600. func (ls *LState) initCallFrame(cf *callFrame) { // +inline-start
  601. if cf.Fn.IsG {
  602. ls.reg.SetTop(cf.LocalBase + cf.NArgs)
  603. } else {
  604. proto := cf.Fn.Proto
  605. nargs := cf.NArgs
  606. np := int(proto.NumParameters)
  607. for i := nargs; i < np; i++ {
  608. ls.reg.array[cf.LocalBase+i] = LNil
  609. nargs = np
  610. }
  611. if (proto.IsVarArg & VarArgIsVarArg) == 0 {
  612. if nargs < int(proto.NumUsedRegisters) {
  613. nargs = int(proto.NumUsedRegisters)
  614. }
  615. for i := np; i < nargs; i++ {
  616. ls.reg.array[cf.LocalBase+i] = LNil
  617. }
  618. ls.reg.top = cf.LocalBase + int(proto.NumUsedRegisters)
  619. } else {
  620. /* swap vararg positions:
  621. closure
  622. namedparam1 <- lbase
  623. namedparam2
  624. vararg1
  625. vararg2
  626. TO
  627. closure
  628. nil
  629. nil
  630. vararg1
  631. vararg2
  632. namedparam1 <- lbase
  633. namedparam2
  634. */
  635. nvarargs := nargs - np
  636. if nvarargs < 0 {
  637. nvarargs = 0
  638. }
  639. ls.reg.SetTop(cf.LocalBase + nargs + np)
  640. for i := 0; i < np; i++ {
  641. //ls.reg.Set(cf.LocalBase+nargs+i, ls.reg.Get(cf.LocalBase+i))
  642. ls.reg.array[cf.LocalBase+nargs+i] = ls.reg.array[cf.LocalBase+i]
  643. //ls.reg.Set(cf.LocalBase+i, LNil)
  644. ls.reg.array[cf.LocalBase+i] = LNil
  645. }
  646. if CompatVarArg {
  647. ls.reg.SetTop(cf.LocalBase + nargs + np + 1)
  648. if (proto.IsVarArg & VarArgNeedsArg) != 0 {
  649. argtb := newLTable(nvarargs, 0)
  650. for i := 0; i < nvarargs; i++ {
  651. argtb.RawSetInt(i+1, ls.reg.Get(cf.LocalBase+np+i))
  652. }
  653. argtb.RawSetString("n", LNumber(nvarargs))
  654. //ls.reg.Set(cf.LocalBase+nargs+np, argtb)
  655. ls.reg.array[cf.LocalBase+nargs+np] = argtb
  656. } else {
  657. ls.reg.array[cf.LocalBase+nargs+np] = LNil
  658. }
  659. }
  660. cf.LocalBase += nargs
  661. maxreg := cf.LocalBase + int(proto.NumUsedRegisters)
  662. ls.reg.SetTop(maxreg)
  663. }
  664. }
  665. } // +inline-end
  666. func (ls *LState) pushCallFrame(cf callFrame, fn LValue, meta bool) { // +inline-start
  667. if meta {
  668. cf.NArgs++
  669. ls.reg.Insert(fn, cf.LocalBase)
  670. }
  671. if cf.Fn == nil {
  672. ls.RaiseError("attempt to call a non-function object")
  673. }
  674. if ls.stack.sp == ls.Options.CallStackSize {
  675. ls.RaiseError("stack overflow")
  676. }
  677. // this section is inlined by go-inline
  678. // source function is 'func (cs *callFrameStack) Push(v callFrame) ' in '_state.go'
  679. {
  680. cs := ls.stack
  681. v := cf
  682. cs.array[cs.sp] = v
  683. cs.array[cs.sp].Idx = cs.sp
  684. cs.sp++
  685. }
  686. newcf := ls.stack.Last()
  687. // this section is inlined by go-inline
  688. // source function is 'func (ls *LState) initCallFrame(cf *callFrame) ' in '_state.go'
  689. {
  690. cf := newcf
  691. if cf.Fn.IsG {
  692. ls.reg.SetTop(cf.LocalBase + cf.NArgs)
  693. } else {
  694. proto := cf.Fn.Proto
  695. nargs := cf.NArgs
  696. np := int(proto.NumParameters)
  697. for i := nargs; i < np; i++ {
  698. ls.reg.array[cf.LocalBase+i] = LNil
  699. nargs = np
  700. }
  701. if (proto.IsVarArg & VarArgIsVarArg) == 0 {
  702. if nargs < int(proto.NumUsedRegisters) {
  703. nargs = int(proto.NumUsedRegisters)
  704. }
  705. for i := np; i < nargs; i++ {
  706. ls.reg.array[cf.LocalBase+i] = LNil
  707. }
  708. ls.reg.top = cf.LocalBase + int(proto.NumUsedRegisters)
  709. } else {
  710. /* swap vararg positions:
  711. closure
  712. namedparam1 <- lbase
  713. namedparam2
  714. vararg1
  715. vararg2
  716. TO
  717. closure
  718. nil
  719. nil
  720. vararg1
  721. vararg2
  722. namedparam1 <- lbase
  723. namedparam2
  724. */
  725. nvarargs := nargs - np
  726. if nvarargs < 0 {
  727. nvarargs = 0
  728. }
  729. ls.reg.SetTop(cf.LocalBase + nargs + np)
  730. for i := 0; i < np; i++ {
  731. //ls.reg.Set(cf.LocalBase+nargs+i, ls.reg.Get(cf.LocalBase+i))
  732. ls.reg.array[cf.LocalBase+nargs+i] = ls.reg.array[cf.LocalBase+i]
  733. //ls.reg.Set(cf.LocalBase+i, LNil)
  734. ls.reg.array[cf.LocalBase+i] = LNil
  735. }
  736. if CompatVarArg {
  737. ls.reg.SetTop(cf.LocalBase + nargs + np + 1)
  738. if (proto.IsVarArg & VarArgNeedsArg) != 0 {
  739. argtb := newLTable(nvarargs, 0)
  740. for i := 0; i < nvarargs; i++ {
  741. argtb.RawSetInt(i+1, ls.reg.Get(cf.LocalBase+np+i))
  742. }
  743. argtb.RawSetString("n", LNumber(nvarargs))
  744. //ls.reg.Set(cf.LocalBase+nargs+np, argtb)
  745. ls.reg.array[cf.LocalBase+nargs+np] = argtb
  746. } else {
  747. ls.reg.array[cf.LocalBase+nargs+np] = LNil
  748. }
  749. }
  750. cf.LocalBase += nargs
  751. maxreg := cf.LocalBase + int(proto.NumUsedRegisters)
  752. ls.reg.SetTop(maxreg)
  753. }
  754. }
  755. }
  756. ls.currentFrame = newcf
  757. } // +inline-end
  758. func (ls *LState) callR(nargs, nret, rbase int) {
  759. base := ls.reg.Top() - nargs - 1
  760. if rbase < 0 {
  761. rbase = base
  762. }
  763. lv := ls.reg.Get(base)
  764. fn, meta := ls.metaCall(lv)
  765. ls.pushCallFrame(callFrame{
  766. Fn: fn,
  767. Pc: 0,
  768. Base: base,
  769. LocalBase: base + 1,
  770. ReturnBase: rbase,
  771. NArgs: nargs,
  772. NRet: nret,
  773. Parent: ls.currentFrame,
  774. TailCall: 0,
  775. }, lv, meta)
  776. if ls.G.MainThread == nil {
  777. ls.G.MainThread = ls
  778. ls.G.CurrentThread = ls
  779. ls.mainLoop(ls, nil)
  780. } else {
  781. ls.mainLoop(ls, ls.currentFrame)
  782. }
  783. if nret != MultRet {
  784. ls.reg.SetTop(rbase + nret)
  785. }
  786. }
  787. func (ls *LState) getField(obj LValue, key LValue) LValue {
  788. curobj := obj
  789. for i := 0; i < MaxTableGetLoop; i++ {
  790. tb, istable := curobj.(*LTable)
  791. if istable {
  792. ret := tb.RawGet(key)
  793. if ret != LNil {
  794. return ret
  795. }
  796. }
  797. metaindex := ls.metaOp1(curobj, "__index")
  798. if metaindex == LNil {
  799. if !istable {
  800. ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
  801. }
  802. return LNil
  803. }
  804. if metaindex.Type() == LTFunction {
  805. ls.reg.Push(metaindex)
  806. ls.reg.Push(curobj)
  807. ls.reg.Push(key)
  808. ls.Call(2, 1)
  809. return ls.reg.Pop()
  810. } else {
  811. curobj = metaindex
  812. }
  813. }
  814. ls.RaiseError("too many recursions in gettable")
  815. return nil
  816. }
  817. func (ls *LState) getFieldString(obj LValue, key string) LValue {
  818. curobj := obj
  819. for i := 0; i < MaxTableGetLoop; i++ {
  820. tb, istable := curobj.(*LTable)
  821. if istable {
  822. ret := tb.RawGetString(key)
  823. if ret != LNil {
  824. return ret
  825. }
  826. }
  827. metaindex := ls.metaOp1(curobj, "__index")
  828. if metaindex == LNil {
  829. if !istable {
  830. ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
  831. }
  832. return LNil
  833. }
  834. if metaindex.Type() == LTFunction {
  835. ls.reg.Push(metaindex)
  836. ls.reg.Push(curobj)
  837. ls.reg.Push(LString(key))
  838. ls.Call(2, 1)
  839. return ls.reg.Pop()
  840. } else {
  841. curobj = metaindex
  842. }
  843. }
  844. ls.RaiseError("too many recursions in gettable")
  845. return nil
  846. }
  847. func (ls *LState) setField(obj LValue, key LValue, value LValue) {
  848. curobj := obj
  849. for i := 0; i < MaxTableGetLoop; i++ {
  850. tb, istable := curobj.(*LTable)
  851. if istable {
  852. if tb.RawGet(key) != LNil {
  853. ls.RawSet(tb, key, value)
  854. return
  855. }
  856. }
  857. metaindex := ls.metaOp1(curobj, "__newindex")
  858. if metaindex == LNil {
  859. if !istable {
  860. ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
  861. }
  862. ls.RawSet(tb, key, value)
  863. return
  864. }
  865. if metaindex.Type() == LTFunction {
  866. ls.reg.Push(metaindex)
  867. ls.reg.Push(curobj)
  868. ls.reg.Push(key)
  869. ls.reg.Push(value)
  870. ls.Call(3, 0)
  871. return
  872. } else {
  873. curobj = metaindex
  874. }
  875. }
  876. ls.RaiseError("too many recursions in settable")
  877. }
  878. func (ls *LState) setFieldString(obj LValue, key string, value LValue) {
  879. curobj := obj
  880. for i := 0; i < MaxTableGetLoop; i++ {
  881. tb, istable := curobj.(*LTable)
  882. if istable {
  883. if tb.RawGetString(key) != LNil {
  884. tb.RawSetString(key, value)
  885. return
  886. }
  887. }
  888. metaindex := ls.metaOp1(curobj, "__newindex")
  889. if metaindex == LNil {
  890. if !istable {
  891. ls.RaiseError("attempt to index a non-table object(%v)", curobj.Type().String())
  892. }
  893. tb.RawSetString(key, value)
  894. return
  895. }
  896. if metaindex.Type() == LTFunction {
  897. ls.reg.Push(metaindex)
  898. ls.reg.Push(curobj)
  899. ls.reg.Push(LString(key))
  900. ls.reg.Push(value)
  901. ls.Call(3, 0)
  902. return
  903. } else {
  904. curobj = metaindex
  905. }
  906. }
  907. ls.RaiseError("too many recursions in settable")
  908. }
  909. /* }}} */
  910. /* api methods {{{ */
  911. func NewState(opts ...Options) *LState {
  912. var ls *LState
  913. if len(opts) == 0 {
  914. ls = newLState(Options{
  915. CallStackSize: CallStackSize,
  916. RegistrySize: RegistrySize,
  917. })
  918. ls.OpenLibs()
  919. } else {
  920. if opts[0].CallStackSize < 1 {
  921. opts[0].CallStackSize = CallStackSize
  922. }
  923. if opts[0].RegistrySize < 128 {
  924. opts[0].RegistrySize = RegistrySize
  925. }
  926. ls = newLState(opts[0])
  927. if !opts[0].SkipOpenLibs {
  928. ls.OpenLibs()
  929. }
  930. }
  931. return ls
  932. }
  933. func (ls *LState) Close() {
  934. atomic.AddInt32(&ls.stop, 1)
  935. for _, file := range ls.G.tempFiles {
  936. // ignore errors in these operations
  937. file.Close()
  938. os.Remove(file.Name())
  939. }
  940. }
  941. /* registry operations {{{ */
  942. func (ls *LState) GetTop() int {
  943. return ls.reg.Top() - ls.currentLocalBase()
  944. }
  945. func (ls *LState) SetTop(idx int) {
  946. base := ls.currentLocalBase()
  947. newtop := ls.indexToReg(idx) + 1
  948. if newtop < base {
  949. ls.reg.SetTop(base)
  950. } else {
  951. ls.reg.SetTop(newtop)
  952. }
  953. }
  954. func (ls *LState) Replace(idx int, value LValue) {
  955. base := ls.currentLocalBase()
  956. if idx > 0 {
  957. reg := base + idx - 1
  958. if reg < ls.reg.Top() {
  959. ls.reg.Set(reg, value)
  960. }
  961. } else if idx == 0 {
  962. } else if idx > RegistryIndex {
  963. if tidx := ls.reg.Top() + idx; tidx >= base {
  964. ls.reg.Set(tidx, value)
  965. }
  966. } else {
  967. switch idx {
  968. case RegistryIndex:
  969. if tb, ok := value.(*LTable); ok {
  970. ls.G.Registry = tb
  971. } else {
  972. ls.RaiseError("registry must be a table(%v)", value.Type().String())
  973. }
  974. case EnvironIndex:
  975. if ls.currentFrame == nil {
  976. ls.RaiseError("no calling environment")
  977. }
  978. if tb, ok := value.(*LTable); ok {
  979. ls.currentFrame.Fn.Env = tb
  980. } else {
  981. ls.RaiseError("environment must be a table(%v)", value.Type().String())
  982. }
  983. case GlobalsIndex:
  984. if tb, ok := value.(*LTable); ok {
  985. ls.G.Global = tb
  986. } else {
  987. ls.RaiseError("_G must be a table(%v)", value.Type().String())
  988. }
  989. default:
  990. fn := ls.currentFrame.Fn
  991. index := GlobalsIndex - idx - 1
  992. if index < len(fn.Upvalues) {
  993. fn.Upvalues[index].SetValue(value)
  994. }
  995. }
  996. }
  997. }
  998. func (ls *LState) Get(idx int) LValue {
  999. base := ls.currentLocalBase()
  1000. if idx > 0 {
  1001. reg := base + idx - 1
  1002. if reg < ls.reg.Top() {
  1003. return ls.reg.Get(reg)
  1004. }
  1005. return LNil
  1006. } else if idx == 0 {
  1007. return LNil
  1008. } else if idx > RegistryIndex {
  1009. tidx := ls.reg.Top() + idx
  1010. if tidx < base {
  1011. return LNil
  1012. }
  1013. return ls.reg.Get(tidx)
  1014. } else {
  1015. switch idx {
  1016. case RegistryIndex:
  1017. return ls.G.Registry
  1018. case EnvironIndex:
  1019. if ls.currentFrame == nil {
  1020. return ls.Env
  1021. }
  1022. return ls.currentFrame.Fn.Env
  1023. case GlobalsIndex:
  1024. return ls.G.Global
  1025. default:
  1026. fn := ls.currentFrame.Fn
  1027. index := GlobalsIndex - idx - 1
  1028. if index < len(fn.Upvalues) {
  1029. return fn.Upvalues[index].Value()
  1030. }
  1031. return LNil
  1032. }
  1033. }
  1034. return LNil
  1035. }
  1036. func (ls *LState) Push(value LValue) {
  1037. ls.reg.Push(value)
  1038. }
  1039. func (ls *LState) Pop(n int) {
  1040. for i := 0; i < n; i++ {
  1041. if ls.GetTop() == 0 {
  1042. ls.RaiseError("register underflow")
  1043. }
  1044. ls.reg.Pop()
  1045. }
  1046. }
  1047. func (ls *LState) Insert(value LValue, index int) {
  1048. reg := ls.indexToReg(index)
  1049. top := ls.reg.Top()
  1050. if reg >= top {
  1051. ls.reg.Set(reg, value)
  1052. return
  1053. }
  1054. if reg <= ls.currentLocalBase() {
  1055. reg = ls.currentLocalBase()
  1056. }
  1057. top--
  1058. for ; top >= reg; top-- {
  1059. ls.reg.Set(top+1, ls.reg.Get(top))
  1060. }
  1061. ls.reg.Set(reg, value)
  1062. }
  1063. func (ls *LState) Remove(index int) {
  1064. reg := ls.indexToReg(index)
  1065. top := ls.reg.Top()
  1066. switch {
  1067. case reg >= top:
  1068. return
  1069. case reg < ls.currentLocalBase():
  1070. return
  1071. case reg == top-1:
  1072. ls.Pop(1)
  1073. return
  1074. }
  1075. for i := reg; i < top-1; i++ {
  1076. ls.reg.Set(i, ls.reg.Get(i+1))
  1077. }
  1078. ls.reg.SetTop(top - 1)
  1079. }
  1080. /* }}} */
  1081. /* object allocation {{{ */
  1082. func (ls *LState) NewTable() *LTable {
  1083. return newLTable(defaultArrayCap, defaultHashCap)
  1084. }
  1085. func (ls *LState) CreateTable(acap, hcap int) *LTable {
  1086. return newLTable(acap, hcap)
  1087. }
  1088. // NewThread returns a new LState that shares with the original state all global objects.
  1089. // If the original state has context.Context, the new state has a new child context of the original state and this function returns its cancel function.
  1090. func (ls *LState) NewThread() (*LState, context.CancelFunc) {
  1091. thread := newLState(ls.Options)
  1092. thread.G = ls.G
  1093. thread.Env = ls.Env
  1094. var f context.CancelFunc = nil
  1095. if ls.ctx != nil {
  1096. thread.mainLoop = mainLoopWithContext
  1097. thread.ctx, f = context.WithCancel(ls.ctx)
  1098. }
  1099. return thread, f
  1100. }
  1101. func (ls *LState) NewUserData() *LUserData {
  1102. return &LUserData{
  1103. Env: ls.currentEnv(),
  1104. Metatable: LNil,
  1105. }
  1106. }
  1107. func (ls *LState) NewFunction(fn LGFunction) *LFunction {
  1108. return newLFunctionG(fn, ls.currentEnv(), 0)
  1109. }
  1110. func (ls *LState) NewClosure(fn LGFunction, upvalues ...LValue) *LFunction {
  1111. cl := newLFunctionG(fn, ls.currentEnv(), len(upvalues))
  1112. for i, lv := range upvalues {
  1113. cl.Upvalues[i] = &Upvalue{}
  1114. cl.Upvalues[i].Close()
  1115. cl.Upvalues[i].SetValue(lv)
  1116. }
  1117. return cl
  1118. }
  1119. /* }}} */
  1120. /* toType {{{ */
  1121. func (ls *LState) ToBool(n int) bool {
  1122. return LVAsBool(ls.Get(n))
  1123. }
  1124. func (ls *LState) ToInt(n int) int {
  1125. if lv, ok := ls.Get(n).(LNumber); ok {
  1126. return int(lv)
  1127. }
  1128. if lv, ok := ls.Get(n).(LString); ok {
  1129. if num, err := parseNumber(string(lv)); err == nil {
  1130. return int(num)
  1131. }
  1132. }
  1133. return 0
  1134. }
  1135. func (ls *LState) ToInt64(n int) int64 {
  1136. if lv, ok := ls.Get(n).(LNumber); ok {
  1137. return int64(lv)
  1138. }
  1139. if lv, ok := ls.Get(n).(LString); ok {
  1140. if num, err := parseNumber(string(lv)); err == nil {
  1141. return int64(num)
  1142. }
  1143. }
  1144. return 0
  1145. }
  1146. func (ls *LState) ToNumber(n int) LNumber {
  1147. return LVAsNumber(ls.Get(n))
  1148. }
  1149. func (ls *LState) ToString(n int) string {
  1150. return LVAsString(ls.Get(n))
  1151. }
  1152. func (ls *LState) ToTable(n int) *LTable {
  1153. if lv, ok := ls.Get(n).(*LTable); ok {
  1154. return lv
  1155. }
  1156. return nil
  1157. }
  1158. func (ls *LState) ToFunction(n int) *LFunction {
  1159. if lv, ok := ls.Get(n).(*LFunction); ok {
  1160. return lv
  1161. }
  1162. return nil
  1163. }
  1164. func (ls *LState) ToUserData(n int) *LUserData {
  1165. if lv, ok := ls.Get(n).(*LUserData); ok {
  1166. return lv
  1167. }
  1168. return nil
  1169. }
  1170. func (ls *LState) ToThread(n int) *LState {
  1171. if lv, ok := ls.Get(n).(*LState); ok {
  1172. return lv
  1173. }
  1174. return nil
  1175. }
  1176. /* }}} */
  1177. /* error & debug operations {{{ */
  1178. // This function is equivalent to luaL_error( http://www.lua.org/manual/5.1/manual.html#luaL_error ).
  1179. func (ls *LState) RaiseError(format string, args ...interface{}) {
  1180. ls.raiseError(1, format, args...)
  1181. }
  1182. // This function is equivalent to lua_error( http://www.lua.org/manual/5.1/manual.html#lua_error ).
  1183. func (ls *LState) Error(lv LValue, level int) {
  1184. if str, ok := lv.(LString); ok {
  1185. ls.raiseError(level, string(str))
  1186. } else {
  1187. if !ls.hasErrorFunc {
  1188. ls.closeAllUpvalues()
  1189. }
  1190. ls.Push(lv)
  1191. ls.Panic(ls)
  1192. }
  1193. }
  1194. func (ls *LState) GetInfo(what string, dbg *Debug, fn LValue) (LValue, error) {
  1195. if !strings.HasPrefix(what, ">") {
  1196. fn = dbg.frame.Fn
  1197. } else {
  1198. what = what[1:]
  1199. }
  1200. f, ok := fn.(*LFunction)
  1201. if !ok {
  1202. return LNil, newApiErrorS(ApiErrorRun, "can not get debug info(an object in not a function)")
  1203. }
  1204. retfn := false
  1205. for _, c := range what {
  1206. switch c {
  1207. case 'f':
  1208. retfn = true
  1209. case 'S':
  1210. if dbg.frame != nil && dbg.frame.Parent == nil {
  1211. dbg.What = "main"
  1212. } else if f.IsG {
  1213. dbg.What = "G"
  1214. } else if dbg.frame != nil && dbg.frame.TailCall > 0 {
  1215. dbg.What = "tail"
  1216. } else {
  1217. dbg.What = "Lua"
  1218. }
  1219. if !f.IsG {
  1220. dbg.Source = f.Proto.SourceName
  1221. dbg.LineDefined = f.Proto.LineDefined
  1222. dbg.LastLineDefined = f.Proto.LastLineDefined
  1223. }
  1224. case 'l':
  1225. if !f.IsG && dbg.frame != nil {
  1226. if dbg.frame.Pc > 0 {
  1227. dbg.CurrentLine = f.Proto.DbgSourcePositions[dbg.frame.Pc-1]
  1228. }
  1229. } else {
  1230. dbg.CurrentLine = -1
  1231. }
  1232. case 'u':
  1233. dbg.NUpvalues = len(f.Upvalues)
  1234. case 'n':
  1235. if dbg.frame != nil {
  1236. dbg.Name = ls.rawFrameFuncName(dbg.frame)
  1237. }
  1238. default:
  1239. return LNil, newApiErrorS(ApiErrorRun, "invalid what: "+string(c))
  1240. }
  1241. }
  1242. if retfn {
  1243. return f, nil
  1244. }
  1245. return LNil, nil
  1246. }
  1247. func (ls *LState) GetStack(level int) (*Debug, bool) {
  1248. frame := ls.currentFrame
  1249. for ; level > 0 && frame != nil; frame = frame.Parent {
  1250. level--
  1251. if !frame.Fn.IsG {
  1252. level -= frame.TailCall
  1253. }
  1254. }
  1255. if level == 0 && frame != nil {
  1256. return &Debug{frame: frame}, true
  1257. } else if level < 0 && ls.stack.Sp() > 0 {
  1258. return &Debug{frame: ls.stack.At(0)}, true
  1259. }
  1260. return &Debug{}, false
  1261. }
  1262. func (ls *LState) GetLocal(dbg *Debug, no int) (string, LValue) {
  1263. frame := dbg.frame
  1264. if name := ls.findLocal(frame, no); len(name) > 0 {
  1265. return name, ls.reg.Get(frame.LocalBase + no - 1)
  1266. }
  1267. return "", LNil
  1268. }
  1269. func (ls *LState) SetLocal(dbg *Debug, no int, lv LValue) string {
  1270. frame := dbg.frame
  1271. if name := ls.findLocal(frame, no); len(name) > 0 {
  1272. ls.reg.Set(frame.LocalBase+no-1, lv)
  1273. return name
  1274. }
  1275. return ""
  1276. }
  1277. func (ls *LState) GetUpvalue(fn *LFunction, no int) (string, LValue) {
  1278. if fn.IsG {
  1279. return "", LNil
  1280. }
  1281. no--
  1282. if no >= 0 && no < len(fn.Upvalues) {
  1283. return fn.Proto.DbgUpvalues[no], fn.Upvalues[no].Value()
  1284. }
  1285. return "", LNil
  1286. }
  1287. func (ls *LState) SetUpvalue(fn *LFunction, no int, lv LValue) string {
  1288. if fn.IsG {
  1289. return ""
  1290. }
  1291. no--
  1292. if no >= 0 && no < len(fn.Upvalues) {
  1293. fn.Upvalues[no].SetValue(lv)
  1294. return fn.Proto.DbgUpvalues[no]
  1295. }
  1296. return ""
  1297. }
  1298. /* }}} */
  1299. /* env operations {{{ */
  1300. func (ls *LState) GetFEnv(obj LValue) LValue {
  1301. switch lv := obj.(type) {
  1302. case *LFunction:
  1303. return lv.Env
  1304. case *LUserData:
  1305. return lv.Env
  1306. case *LState:
  1307. return lv.Env
  1308. }
  1309. return LNil
  1310. }
  1311. func (ls *LState) SetFEnv(obj LValue, env LValue) {
  1312. tb, ok := env.(*LTable)
  1313. if !ok {
  1314. ls.RaiseError("cannot use %v as an environment", env.Type().String())
  1315. }
  1316. switch lv := obj.(type) {
  1317. case *LFunction:
  1318. lv.Env = tb
  1319. case *LUserData:
  1320. lv.Env = tb
  1321. case *LState:
  1322. lv.Env = tb
  1323. }
  1324. /* do nothing */
  1325. }
  1326. /* }}} */
  1327. /* table operations {{{ */
  1328. func (ls *LState) RawGet(tb *LTable, key LValue) LValue {
  1329. return tb.RawGet(key)
  1330. }
  1331. func (ls *LState) RawGetInt(tb *LTable, key int) LValue {
  1332. return tb.RawGetInt(key)
  1333. }
  1334. func (ls *LState) GetField(obj LValue, skey string) LValue {
  1335. return ls.getFieldString(obj, skey)
  1336. }
  1337. func (ls *LState) GetTable(obj LValue, key LValue) LValue {
  1338. return ls.getField(obj, key)
  1339. }
  1340. func (ls *LState) RawSet(tb *LTable, key LValue, value LValue) {
  1341. if n, ok := key.(LNumber); ok && math.IsNaN(float64(n)) {
  1342. ls.RaiseError("table index is NaN")
  1343. } else if key == LNil {
  1344. ls.RaiseError("table index is nil")
  1345. }
  1346. tb.RawSet(key, value)
  1347. }
  1348. func (ls *LState) RawSetInt(tb *LTable, key int, value LValue) {
  1349. tb.RawSetInt(key, value)
  1350. }
  1351. func (ls *LState) SetField(obj LValue, key string, value LValue) {
  1352. ls.setFieldString(obj, key, value)
  1353. }
  1354. func (ls *LState) SetTable(obj LValue, key LValue, value LValue) {
  1355. ls.setField(obj, key, value)
  1356. }
  1357. func (ls *LState) ForEach(tb *LTable, cb func(LValue, LValue)) {
  1358. tb.ForEach(cb)
  1359. }
  1360. func (ls *LState) GetGlobal(name string) LValue {
  1361. return ls.GetField(ls.Get(GlobalsIndex), name)
  1362. }
  1363. func (ls *LState) SetGlobal(name string, value LValue) {
  1364. ls.SetField(ls.Get(GlobalsIndex), name, value)
  1365. }
  1366. func (ls *LState) Next(tb *LTable, key LValue) (LValue, LValue) {
  1367. return tb.Next(key)
  1368. }
  1369. /* }}} */
  1370. /* unary operations {{{ */
  1371. func (ls *LState) ObjLen(v1 LValue) int {
  1372. if v1.Type() == LTString {
  1373. return len(string(v1.(LString)))
  1374. }
  1375. op := ls.metaOp1(v1, "__len")
  1376. if op.Type() == LTFunction {
  1377. ls.Push(op)
  1378. ls.Push(v1)
  1379. ls.Call(1, 1)
  1380. ret := ls.reg.Pop()
  1381. if ret.Type() == LTNumber {
  1382. return int(ret.(LNumber))
  1383. }
  1384. } else if v1.Type() == LTTable {
  1385. return v1.(*LTable).Len()
  1386. }
  1387. return 0
  1388. }
  1389. /* }}} */
  1390. /* binary operations {{{ */
  1391. func (ls *LState) Concat(values ...LValue) string {
  1392. top := ls.reg.Top()
  1393. for _, value := range values {
  1394. ls.reg.Push(value)
  1395. }
  1396. ret := stringConcat(ls, len(values), ls.reg.Top()-1)
  1397. ls.reg.SetTop(top)
  1398. return LVAsString(ret)
  1399. }
  1400. func (ls *LState) LessThan(lhs, rhs LValue) bool {
  1401. return lessThan(ls, lhs, rhs)
  1402. }
  1403. func (ls *LState) Equal(lhs, rhs LValue) bool {
  1404. return equals(ls, lhs, rhs, false)
  1405. }
  1406. func (ls *LState) RawEqual(lhs, rhs LValue) bool {
  1407. return equals(ls, lhs, rhs, true)
  1408. }
  1409. /* }}} */
  1410. /* register operations {{{ */
  1411. func (ls *LState) Register(name string, fn LGFunction) {
  1412. ls.SetGlobal(name, ls.NewFunction(fn))
  1413. }
  1414. /* }}} */
  1415. /* load and function call operations {{{ */
  1416. func container2proto(container *functionProtoContainer) *FunctionProto {
  1417. protos := []*FunctionProto{}
  1418. for _, c := range container.FunctionPrototypes {
  1419. protos = append(protos, container2proto(c))
  1420. }
  1421. constants := []LValue{}
  1422. stringConstants := []string{}
  1423. for _, c := range container.Constants {
  1424. if s, ok := c.(string); ok {
  1425. constants = append(constants, LString(s))
  1426. stringConstants = append(stringConstants, s)
  1427. } else {
  1428. constants = append(constants, LNumber(c.(float64)))
  1429. }
  1430. }
  1431. return &FunctionProto{
  1432. SourceName: container.SourceName,
  1433. LineDefined: container.LineDefined,
  1434. LastLineDefined: container.LastLineDefined,
  1435. NumUpvalues: container.NumUpvalues,
  1436. NumParameters: container.NumParameters,
  1437. IsVarArg: container.IsVarArg,
  1438. NumUsedRegisters: container.NumUsedRegisters,
  1439. Code: container.Code,
  1440. Constants: constants,
  1441. FunctionPrototypes: protos,
  1442. DbgSourcePositions: container.DbgSourcePositions,
  1443. DbgLocals: container.DbgLocals,
  1444. DbgCalls: container.DbgCalls,
  1445. DbgUpvalues: container.DbgUpvalues,
  1446. stringConstants: stringConstants,
  1447. }
  1448. }
  1449. func (ls *LState) Load(reader io.Reader, name string) (*LFunction, error) {
  1450. b := bufio.NewReader(reader)
  1451. if sbuf, err := b.Peek(4); err == nil {
  1452. if string(sbuf) == dumpSignature {
  1453. b.Discard(4)
  1454. buf, err := ioutil.ReadAll(b)
  1455. if err != nil {
  1456. ls.RaiseError(err.Error())
  1457. }
  1458. var container functionProtoContainer
  1459. if err := msgpack.Unmarshal(buf, &container); err != nil {
  1460. ls.RaiseError(err.Error())
  1461. }
  1462. return newLFunctionL(container2proto(&container), ls.currentEnv(), 0), nil
  1463. }
  1464. }
  1465. chunk, err := parse.Parse(b, name)
  1466. if err != nil {
  1467. return nil, newApiErrorE(ApiErrorSyntax, err)
  1468. }
  1469. proto, err := Compile(chunk, name)
  1470. if err != nil {
  1471. return nil, newApiErrorE(ApiErrorSyntax, err)
  1472. }
  1473. return newLFunctionL(proto, ls.currentEnv(), 0), nil
  1474. }
  1475. func (ls *LState) Call(nargs, nret int) {
  1476. ls.callR(nargs, nret, -1)
  1477. }
  1478. func (ls *LState) PCall(nargs, nret int, errfunc *LFunction) (err error) {
  1479. err = nil
  1480. sp := ls.stack.Sp()
  1481. base := ls.reg.Top() - nargs - 1
  1482. oldpanic := ls.Panic
  1483. ls.Panic = panicWithoutTraceback
  1484. if errfunc != nil {
  1485. ls.hasErrorFunc = true
  1486. }
  1487. defer func() {
  1488. ls.Panic = oldpanic
  1489. ls.hasErrorFunc = false
  1490. rcv := recover()
  1491. if rcv != nil {
  1492. if _, ok := rcv.(*ApiError); !ok {
  1493. err = newApiErrorS(ApiErrorPanic, fmt.Sprint(rcv))
  1494. if ls.Options.IncludeGoStackTrace {
  1495. buf := make([]byte, 4096)
  1496. runtime.Stack(buf, false)
  1497. err.(*ApiError).StackTrace = strings.Trim(string(buf), "\000") + "\n" + ls.stackTrace(0)
  1498. }
  1499. } else {
  1500. err = rcv.(*ApiError)
  1501. }
  1502. if errfunc != nil {
  1503. ls.Push(errfunc)
  1504. ls.Push(err.(*ApiError).Object)
  1505. ls.Panic = panicWithoutTraceback
  1506. defer func() {
  1507. ls.Panic = oldpanic
  1508. rcv := recover()
  1509. if rcv != nil {
  1510. if _, ok := rcv.(*ApiError); !ok {
  1511. err = newApiErrorS(ApiErrorPanic, fmt.Sprint(rcv))
  1512. if ls.Options.IncludeGoStackTrace {
  1513. buf := make([]byte, 4096)
  1514. runtime.Stack(buf, false)
  1515. err.(*ApiError).StackTrace = strings.Trim(string(buf), "\000") + ls.stackTrace(0)
  1516. }
  1517. } else {
  1518. err = rcv.(*ApiError)
  1519. err.(*ApiError).StackTrace = ls.stackTrace(0)
  1520. }
  1521. }
  1522. }()
  1523. ls.Call(1, 1)
  1524. err = newApiError(ApiErrorError, ls.Get(-1))
  1525. } else if len(err.(*ApiError).StackTrace) == 0 {
  1526. err.(*ApiError).StackTrace = ls.stackTrace(0)
  1527. }
  1528. ls.reg.SetTop(base)
  1529. }
  1530. ls.stack.SetSp(sp)
  1531. if sp == 0 {
  1532. ls.currentFrame = nil
  1533. }
  1534. }()
  1535. ls.Call(nargs, nret)
  1536. return
  1537. }
  1538. func (ls *LState) GPCall(fn LGFunction, data LValue) error {
  1539. ls.Push(newLFunctionG(fn, ls.currentEnv(), 0))
  1540. ls.Push(data)
  1541. return ls.PCall(1, MultRet, nil)
  1542. }
  1543. func (ls *LState) CallByParam(cp P, args ...LValue) error {
  1544. ls.Push(cp.Fn)
  1545. for _, arg := range args {
  1546. ls.Push(arg)
  1547. }
  1548. if cp.Protect {
  1549. return ls.PCall(len(args), cp.NRet, cp.Handler)
  1550. }
  1551. ls.Call(len(args), cp.NRet)
  1552. return nil
  1553. }
  1554. /* }}} */
  1555. /* metatable operations {{{ */
  1556. func (ls *LState) GetMetatable(obj LValue) LValue {
  1557. return ls.metatable(obj, false)
  1558. }
  1559. func (ls *LState) SetMetatable(obj LValue, mt LValue) {
  1560. switch mt.(type) {
  1561. case *LNilType, *LTable:
  1562. default:
  1563. ls.RaiseError("metatable must be a table or nil, but got %v", mt.Type().String())
  1564. }
  1565. switch v := obj.(type) {
  1566. case *LTable:
  1567. v.Metatable = mt
  1568. case *LUserData:
  1569. v.Metatable = mt
  1570. default:
  1571. ls.G.builtinMts[int(obj.Type())] = mt
  1572. }
  1573. }
  1574. /* }}} */
  1575. /* coroutine operations {{{ */
  1576. func (ls *LState) Status(th *LState) string {
  1577. status := "suspended"
  1578. if th.Dead {
  1579. status = "dead"
  1580. } else if ls.G.CurrentThread == th {
  1581. status = "running"
  1582. } else if ls.Parent == th {
  1583. status = "normal"
  1584. }
  1585. return status
  1586. }
  1587. func (ls *LState) Resume(th *LState, fn *LFunction, args ...LValue) (ResumeState, error, []LValue) {
  1588. isstarted := th.isStarted()
  1589. if !isstarted {
  1590. base := 0
  1591. th.stack.Push(callFrame{
  1592. Fn: fn,
  1593. Pc: 0,
  1594. Base: base,
  1595. LocalBase: base + 1,
  1596. ReturnBase: base,
  1597. NArgs: 0,
  1598. NRet: MultRet,
  1599. Parent: nil,
  1600. TailCall: 0,
  1601. })
  1602. }
  1603. if ls.G.CurrentThread == th {
  1604. return ResumeError, newApiErrorS(ApiErrorRun, "can not resume a running thread"), nil
  1605. }
  1606. if th.Dead {
  1607. return ResumeError, newApiErrorS(ApiErrorRun, "can not resume a dead thread"), nil
  1608. }
  1609. th.Parent = ls
  1610. ls.G.CurrentThread = th
  1611. if !isstarted {
  1612. cf := th.stack.Last()
  1613. th.currentFrame = cf
  1614. th.SetTop(0)
  1615. for _, arg := range args {
  1616. th.Push(arg)
  1617. }
  1618. cf.NArgs = len(args)
  1619. th.initCallFrame(cf)
  1620. th.Panic = panicWithoutTraceback
  1621. } else {
  1622. for _, arg := range args {
  1623. th.Push(arg)
  1624. }
  1625. }
  1626. top := ls.GetTop()
  1627. threadRun(th)
  1628. haserror := LVIsFalse(ls.Get(top + 1))
  1629. ret := make([]LValue, 0, ls.GetTop())
  1630. for idx := top + 2; idx <= ls.GetTop(); idx++ {
  1631. ret = append(ret, ls.Get(idx))
  1632. }
  1633. if len(ret) == 0 {
  1634. ret = append(ret, LNil)
  1635. }
  1636. ls.SetTop(top)
  1637. if haserror {
  1638. return ResumeError, newApiError(ApiErrorRun, ret[0]), nil
  1639. } else if th.stack.IsEmpty() {
  1640. return ResumeOK, nil, ret
  1641. }
  1642. return ResumeYield, nil, ret
  1643. }
  1644. func (ls *LState) Yield(values ...LValue) int {
  1645. ls.SetTop(0)
  1646. for _, lv := range values {
  1647. ls.Push(lv)
  1648. }
  1649. return -1
  1650. }
  1651. func (ls *LState) XMoveTo(other *LState, n int) {
  1652. if ls == other {
  1653. return
  1654. }
  1655. top := ls.GetTop()
  1656. n = intMin(n, top)
  1657. for i := n; i > 0; i-- {
  1658. other.Push(ls.Get(top - i + 1))
  1659. }
  1660. ls.SetTop(top - n)
  1661. }
  1662. /* }}} */
  1663. /* GopherLua original APIs {{{ */
  1664. // Set maximum memory size. This function can only be called from the main thread.
  1665. func (ls *LState) SetMx(mx int) {
  1666. if ls.Parent != nil {
  1667. ls.RaiseError("sub threads are not allowed to set a memory limit")
  1668. }
  1669. go func() {
  1670. limit := uint64(mx * 1024 * 1024) //MB
  1671. var s runtime.MemStats
  1672. for ls.stop == 0 {
  1673. runtime.ReadMemStats(&s)
  1674. if s.Alloc >= limit {
  1675. fmt.Println("out of memory")
  1676. os.Exit(3)
  1677. }
  1678. time.Sleep(100 * time.Millisecond)
  1679. }
  1680. }()
  1681. }
  1682. // SetContext set a context ctx to this LState. The provided ctx must be non-nil.
  1683. func (ls *LState) SetContext(ctx context.Context) {
  1684. ls.mainLoop = mainLoopWithContext
  1685. ls.ctx = ctx
  1686. }
  1687. // Context returns the LState's context. To change the context, use WithContext.
  1688. func (ls *LState) Context() context.Context {
  1689. return ls.ctx
  1690. }
  1691. // RemoveContext removes the context associated with this LState and returns this context.
  1692. func (ls *LState) RemoveContext() context.Context {
  1693. oldctx := ls.ctx
  1694. ls.mainLoop = mainLoop
  1695. ls.ctx = nil
  1696. return oldctx
  1697. }
  1698. // Converts the Lua value at the given acceptable index to the chan LValue.
  1699. func (ls *LState) ToChannel(n int) chan LValue {
  1700. if lv, ok := ls.Get(n).(LChannel); ok {
  1701. return (chan LValue)(lv)
  1702. }
  1703. return nil
  1704. }
  1705. /* }}} */
  1706. /* }}} */
  1707. //