vm_test.go 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998
  1. package tengo_test
  2. import (
  3. "errors"
  4. "fmt"
  5. "math"
  6. "math/rand"
  7. "reflect"
  8. _runtime "runtime"
  9. "strings"
  10. "testing"
  11. "github.com/d5/tengo/v2"
  12. "github.com/d5/tengo/v2/parser"
  13. "github.com/d5/tengo/v2/require"
  14. "github.com/d5/tengo/v2/stdlib"
  15. "github.com/d5/tengo/v2/token"
  16. )
  17. const testOut = "out"
  18. type IARR []interface{}
  19. type IMAP map[string]interface{}
  20. type MAP = map[string]interface{}
  21. type ARR = []interface{}
  22. type testopts struct {
  23. modules *tengo.ModuleMap
  24. symbols map[string]tengo.Object
  25. maxAllocs int64
  26. skip2ndPass bool
  27. }
  28. func Opts() *testopts {
  29. return &testopts{
  30. modules: tengo.NewModuleMap(),
  31. symbols: make(map[string]tengo.Object),
  32. maxAllocs: -1,
  33. skip2ndPass: false,
  34. }
  35. }
  36. func (o *testopts) copy() *testopts {
  37. c := &testopts{
  38. modules: o.modules.Copy(),
  39. symbols: make(map[string]tengo.Object),
  40. maxAllocs: o.maxAllocs,
  41. skip2ndPass: o.skip2ndPass,
  42. }
  43. for k, v := range o.symbols {
  44. c.symbols[k] = v
  45. }
  46. return c
  47. }
  48. func (o *testopts) Stdlib() *testopts {
  49. o.modules.AddMap(stdlib.GetModuleMap(stdlib.AllModuleNames()...))
  50. return o
  51. }
  52. func (o *testopts) Module(name string, mod interface{}) *testopts {
  53. c := o.copy()
  54. switch mod := mod.(type) {
  55. case tengo.Importable:
  56. c.modules.Add(name, mod)
  57. case string:
  58. c.modules.AddSourceModule(name, []byte(mod))
  59. case []byte:
  60. c.modules.AddSourceModule(name, mod)
  61. default:
  62. panic(fmt.Errorf("invalid module type: %T", mod))
  63. }
  64. return c
  65. }
  66. func (o *testopts) Symbol(name string, value tengo.Object) *testopts {
  67. c := o.copy()
  68. c.symbols[name] = value
  69. return c
  70. }
  71. func (o *testopts) MaxAllocs(limit int64) *testopts {
  72. c := o.copy()
  73. c.maxAllocs = limit
  74. return c
  75. }
  76. func (o *testopts) Skip2ndPass() *testopts {
  77. c := o.copy()
  78. c.skip2ndPass = true
  79. return c
  80. }
  81. type customError struct {
  82. err error
  83. str string
  84. }
  85. func (c *customError) Error() string {
  86. return c.str
  87. }
  88. func (c *customError) Unwrap() error {
  89. return c.err
  90. }
  91. func TestArray(t *testing.T) {
  92. expectRun(t, `out = [1, 2 * 2, 3 + 3]`, nil, ARR{1, 4, 6})
  93. // array copy-by-reference
  94. expectRun(t, `a1 := [1, 2, 3]; a2 := a1; a1[0] = 5; out = a2`,
  95. nil, ARR{5, 2, 3})
  96. expectRun(t, `func () { a1 := [1, 2, 3]; a2 := a1; a1[0] = 5; out = a2 }()`,
  97. nil, ARR{5, 2, 3})
  98. // array index set
  99. expectError(t, `a1 := [1, 2, 3]; a1[3] = 5`,
  100. nil, "index out of bounds")
  101. // index operator
  102. arr := ARR{1, 2, 3, 4, 5, 6}
  103. arrStr := `[1, 2, 3, 4, 5, 6]`
  104. arrLen := 6
  105. for idx := 0; idx < arrLen; idx++ {
  106. expectRun(t, fmt.Sprintf("out = %s[%d]", arrStr, idx),
  107. nil, arr[idx])
  108. expectRun(t, fmt.Sprintf("out = %s[0 + %d]", arrStr, idx),
  109. nil, arr[idx])
  110. expectRun(t, fmt.Sprintf("out = %s[1 + %d - 1]", arrStr, idx),
  111. nil, arr[idx])
  112. expectRun(t, fmt.Sprintf("idx := %d; out = %s[idx]", idx, arrStr),
  113. nil, arr[idx])
  114. }
  115. expectRun(t, fmt.Sprintf("%s[%d]", arrStr, -1),
  116. nil, tengo.UndefinedValue)
  117. expectRun(t, fmt.Sprintf("%s[%d]", arrStr, arrLen),
  118. nil, tengo.UndefinedValue)
  119. // slice operator
  120. for low := 0; low < arrLen; low++ {
  121. expectRun(t, fmt.Sprintf("out = %s[%d:%d]", arrStr, low, low),
  122. nil, ARR{})
  123. for high := low; high <= arrLen; high++ {
  124. expectRun(t, fmt.Sprintf("out = %s[%d:%d]", arrStr, low, high),
  125. nil, arr[low:high])
  126. expectRun(t, fmt.Sprintf("out = %s[0 + %d : 0 + %d]",
  127. arrStr, low, high), nil, arr[low:high])
  128. expectRun(t, fmt.Sprintf("out = %s[1 + %d - 1 : 1 + %d - 1]",
  129. arrStr, low, high), nil, arr[low:high])
  130. expectRun(t, fmt.Sprintf("out = %s[:%d]", arrStr, high),
  131. nil, arr[:high])
  132. expectRun(t, fmt.Sprintf("out = %s[%d:]", arrStr, low),
  133. nil, arr[low:])
  134. }
  135. }
  136. expectRun(t, fmt.Sprintf("out = %s[:]", arrStr),
  137. nil, arr)
  138. expectRun(t, fmt.Sprintf("out = %s[%d:]", arrStr, -1),
  139. nil, arr)
  140. expectRun(t, fmt.Sprintf("out = %s[:%d]", arrStr, arrLen+1),
  141. nil, arr)
  142. expectRun(t, fmt.Sprintf("out = %s[%d:%d]", arrStr, 2, 2),
  143. nil, ARR{})
  144. expectError(t, fmt.Sprintf("%s[:%d]", arrStr, -1),
  145. nil, "invalid slice index")
  146. expectError(t, fmt.Sprintf("%s[%d:]", arrStr, arrLen+1),
  147. nil, "invalid slice index")
  148. expectError(t, fmt.Sprintf("%s[%d:%d]", arrStr, 0, -1),
  149. nil, "invalid slice index")
  150. expectError(t, fmt.Sprintf("%s[%d:%d]", arrStr, 2, 1),
  151. nil, "invalid slice index")
  152. }
  153. func TestAssignment(t *testing.T) {
  154. expectRun(t, `a := 1; a = 2; out = a`, nil, 2)
  155. expectRun(t, `a := 1; a = 2; out = a`, nil, 2)
  156. expectRun(t, `a := 1; a = a + 4; out = a`, nil, 5)
  157. expectRun(t, `a := 1; f1 := func() { a = 2; return a }; out = f1()`,
  158. nil, 2)
  159. expectRun(t, `a := 1; f1 := func() { a := 3; a = 2; return a }; out = f1()`,
  160. nil, 2)
  161. expectRun(t, `a := 1; out = a`, nil, 1)
  162. expectRun(t, `a := 1; a = 2; out = a`, nil, 2)
  163. expectRun(t, `a := 1; func() { a = 2 }(); out = a`, nil, 2)
  164. expectRun(t, `a := 1; func() { a := 2 }(); out = a`, nil, 1) // "a := 2" defines a new local variable 'a'
  165. expectRun(t, `a := 1; func() { b := 2; out = b }()`, nil, 2)
  166. expectRun(t, `
  167. out = func() {
  168. a := 2
  169. func() {
  170. a = 3 // captured from outer scope
  171. }()
  172. return a
  173. }()
  174. `, nil, 3)
  175. expectRun(t, `
  176. func() {
  177. a := 5
  178. out = func() {
  179. a := 4
  180. return a
  181. }()
  182. }()`, nil, 4)
  183. expectError(t, `a := 1; a := 2`, nil, "redeclared") // redeclared in the same scope
  184. expectError(t, `func() { a := 1; a := 2 }()`, nil, "redeclared") // redeclared in the same scope
  185. expectRun(t, `a := 1; a += 2; out = a`, nil, 3)
  186. expectRun(t, `a := 1; a += 4 - 2;; out = a`, nil, 3)
  187. expectRun(t, `a := 3; a -= 1;; out = a`, nil, 2)
  188. expectRun(t, `a := 3; a -= 5 - 4;; out = a`, nil, 2)
  189. expectRun(t, `a := 2; a *= 4;; out = a`, nil, 8)
  190. expectRun(t, `a := 2; a *= 1 + 3;; out = a`, nil, 8)
  191. expectRun(t, `a := 10; a /= 2;; out = a`, nil, 5)
  192. expectRun(t, `a := 10; a /= 5 - 3;; out = a`, nil, 5)
  193. // compound assignment operator does not define new variable
  194. expectError(t, `a += 4`, nil, "unresolved reference")
  195. expectError(t, `a -= 4`, nil, "unresolved reference")
  196. expectError(t, `a *= 4`, nil, "unresolved reference")
  197. expectError(t, `a /= 4`, nil, "unresolved reference")
  198. expectRun(t, `
  199. f1 := func() {
  200. f2 := func() {
  201. a := 1
  202. a += 2 // it's a statement, not an expression
  203. return a
  204. };
  205. return f2();
  206. };
  207. out = f1();`, nil, 3)
  208. expectRun(t, `f1 := func() { f2 := func() { a := 1; a += 4 - 2; return a }; return f2(); }; out = f1()`,
  209. nil, 3)
  210. expectRun(t, `f1 := func() { f2 := func() { a := 3; a -= 1; return a }; return f2(); }; out = f1()`,
  211. nil, 2)
  212. expectRun(t, `f1 := func() { f2 := func() { a := 3; a -= 5 - 4; return a }; return f2(); }; out = f1()`,
  213. nil, 2)
  214. expectRun(t, `f1 := func() { f2 := func() { a := 2; a *= 4; return a }; return f2(); }; out = f1()`,
  215. nil, 8)
  216. expectRun(t, `f1 := func() { f2 := func() { a := 2; a *= 1 + 3; return a }; return f2(); }; out = f1()`,
  217. nil, 8)
  218. expectRun(t, `f1 := func() { f2 := func() { a := 10; a /= 2; return a }; return f2(); }; out = f1()`,
  219. nil, 5)
  220. expectRun(t, `f1 := func() { f2 := func() { a := 10; a /= 5 - 3; return a }; return f2(); }; out = f1()`,
  221. nil, 5)
  222. expectRun(t, `a := 1; f1 := func() { f2 := func() { a += 2; return a }; return f2(); }; out = f1()`,
  223. nil, 3)
  224. expectRun(t, `
  225. f1 := func(a) {
  226. return func(b) {
  227. c := a
  228. c += b * 2
  229. return c
  230. }
  231. }
  232. out = f1(3)(4)
  233. `, nil, 11)
  234. expectRun(t, `
  235. out = func() {
  236. a := 1
  237. func() {
  238. a = 2
  239. func() {
  240. a = 3
  241. func() {
  242. a := 4 // declared new
  243. }()
  244. }()
  245. }()
  246. return a
  247. }()
  248. `, nil, 3)
  249. // write on free variables
  250. expectRun(t, `
  251. f1 := func() {
  252. a := 5
  253. return func() {
  254. a += 3
  255. return a
  256. }()
  257. }
  258. out = f1()
  259. `, nil, 8)
  260. expectRun(t, `
  261. out = func() {
  262. f1 := func() {
  263. a := 5
  264. add1 := func() { a += 1 }
  265. add2 := func() { a += 2 }
  266. a += 3
  267. return func() { a += 4; add1(); add2(); a += 5; return a }
  268. }
  269. return f1()
  270. }()()
  271. `, nil, 20)
  272. expectRun(t, `
  273. it := func(seq, fn) {
  274. fn(seq[0])
  275. fn(seq[1])
  276. fn(seq[2])
  277. }
  278. foo := func(a) {
  279. b := 0
  280. it([1, 2, 3], func(x) {
  281. b = x + a
  282. })
  283. return b
  284. }
  285. out = foo(2)
  286. `, nil, 5)
  287. expectRun(t, `
  288. it := func(seq, fn) {
  289. fn(seq[0])
  290. fn(seq[1])
  291. fn(seq[2])
  292. }
  293. foo := func(a) {
  294. b := 0
  295. it([1, 2, 3], func(x) {
  296. b += x + a
  297. })
  298. return b
  299. }
  300. out = foo(2)
  301. `, nil, 12)
  302. expectRun(t, `
  303. out = func() {
  304. a := 1
  305. func() {
  306. a = 2
  307. }()
  308. return a
  309. }()
  310. `, nil, 2)
  311. expectRun(t, `
  312. f := func() {
  313. a := 1
  314. return {
  315. b: func() { a += 3 },
  316. c: func() { a += 2 },
  317. d: func() { return a }
  318. }
  319. }
  320. m := f()
  321. m.b()
  322. m.c()
  323. out = m.d()
  324. `, nil, 6)
  325. expectRun(t, `
  326. each := func(s, x) { for i:=0; i<len(s); i++ { x(s[i]) } }
  327. out = func() {
  328. a := 100
  329. each([1, 2, 3], func(x) {
  330. a += x
  331. })
  332. a += 10
  333. return func(b) {
  334. return a + b
  335. }
  336. }()(20)
  337. `, nil, 136)
  338. // assigning different type value
  339. expectRun(t, `a := 1; a = "foo"; out = a`, nil, "foo") // global
  340. expectRun(t, `func() { a := 1; a = "foo"; out = a }()`, nil, "foo") // local
  341. expectRun(t, `
  342. out = func() {
  343. a := 5
  344. return func() {
  345. a = "foo"
  346. return a
  347. }()
  348. }()`, nil, "foo") // free
  349. // variables declared in if/for blocks
  350. expectRun(t, `for a:=0; a<5; a++ {}; a := "foo"; out = a`,
  351. nil, "foo")
  352. expectRun(t, `func() { for a:=0; a<5; a++ {}; a := "foo"; out = a }()`,
  353. nil, "foo")
  354. // selectors
  355. expectRun(t, `a:=[1,2,3]; a[1] = 5; out = a[1]`, nil, 5)
  356. expectRun(t, `a:=[1,2,3]; a[1] += 5; out = a[1]`, nil, 7)
  357. expectRun(t, `a:={b:1,c:2}; a.b = 5; out = a.b`, nil, 5)
  358. expectRun(t, `a:={b:1,c:2}; a.b += 5; out = a.b`, nil, 6)
  359. expectRun(t, `a:={b:1,c:2}; a.b += a.c; out = a.b`, nil, 3)
  360. expectRun(t, `a:={b:1,c:2}; a.b += a.c; out = a.c`, nil, 2)
  361. expectRun(t, `
  362. a := {
  363. b: [1, 2, 3],
  364. c: {
  365. d: 8,
  366. e: "foo",
  367. f: [9, 8]
  368. }
  369. }
  370. a.c.f[1] += 2
  371. out = a["c"]["f"][1]
  372. `, nil, 10)
  373. expectRun(t, `
  374. a := {
  375. b: [1, 2, 3],
  376. c: {
  377. d: 8,
  378. e: "foo",
  379. f: [9, 8]
  380. }
  381. }
  382. a.c.h = "bar"
  383. out = a.c.h
  384. `, nil, "bar")
  385. expectError(t, `
  386. a := {
  387. b: [1, 2, 3],
  388. c: {
  389. d: 8,
  390. e: "foo",
  391. f: [9, 8]
  392. }
  393. }
  394. a.x.e = "bar"`, nil, "not index-assignable")
  395. }
  396. func TestBitwise(t *testing.T) {
  397. expectRun(t, `out = 1 & 1`, nil, 1)
  398. expectRun(t, `out = 1 & 0`, nil, 0)
  399. expectRun(t, `out = 0 & 1`, nil, 0)
  400. expectRun(t, `out = 0 & 0`, nil, 0)
  401. expectRun(t, `out = 1 | 1`, nil, 1)
  402. expectRun(t, `out = 1 | 0`, nil, 1)
  403. expectRun(t, `out = 0 | 1`, nil, 1)
  404. expectRun(t, `out = 0 | 0`, nil, 0)
  405. expectRun(t, `out = 1 ^ 1`, nil, 0)
  406. expectRun(t, `out = 1 ^ 0`, nil, 1)
  407. expectRun(t, `out = 0 ^ 1`, nil, 1)
  408. expectRun(t, `out = 0 ^ 0`, nil, 0)
  409. expectRun(t, `out = 1 &^ 1`, nil, 0)
  410. expectRun(t, `out = 1 &^ 0`, nil, 1)
  411. expectRun(t, `out = 0 &^ 1`, nil, 0)
  412. expectRun(t, `out = 0 &^ 0`, nil, 0)
  413. expectRun(t, `out = 1 << 2`, nil, 4)
  414. expectRun(t, `out = 16 >> 2`, nil, 4)
  415. expectRun(t, `out = 1; out &= 1`, nil, 1)
  416. expectRun(t, `out = 1; out |= 0`, nil, 1)
  417. expectRun(t, `out = 1; out ^= 0`, nil, 1)
  418. expectRun(t, `out = 1; out &^= 0`, nil, 1)
  419. expectRun(t, `out = 1; out <<= 2`, nil, 4)
  420. expectRun(t, `out = 16; out >>= 2`, nil, 4)
  421. expectRun(t, `out = ^0`, nil, ^0)
  422. expectRun(t, `out = ^1`, nil, ^1)
  423. expectRun(t, `out = ^55`, nil, ^55)
  424. expectRun(t, `out = ^-55`, nil, ^-55)
  425. }
  426. func TestBoolean(t *testing.T) {
  427. expectRun(t, `out = true`, nil, true)
  428. expectRun(t, `out = false`, nil, false)
  429. expectRun(t, `out = 1 < 2`, nil, true)
  430. expectRun(t, `out = 1 > 2`, nil, false)
  431. expectRun(t, `out = 1 < 1`, nil, false)
  432. expectRun(t, `out = 1 > 2`, nil, false)
  433. expectRun(t, `out = 1 == 1`, nil, true)
  434. expectRun(t, `out = 1 != 1`, nil, false)
  435. expectRun(t, `out = 1 == 2`, nil, false)
  436. expectRun(t, `out = 1 != 2`, nil, true)
  437. expectRun(t, `out = 1 <= 2`, nil, true)
  438. expectRun(t, `out = 1 >= 2`, nil, false)
  439. expectRun(t, `out = 1 <= 1`, nil, true)
  440. expectRun(t, `out = 1 >= 2`, nil, false)
  441. expectRun(t, `out = true == true`, nil, true)
  442. expectRun(t, `out = false == false`, nil, true)
  443. expectRun(t, `out = true == false`, nil, false)
  444. expectRun(t, `out = true != false`, nil, true)
  445. expectRun(t, `out = false != true`, nil, true)
  446. expectRun(t, `out = (1 < 2) == true`, nil, true)
  447. expectRun(t, `out = (1 < 2) == false`, nil, false)
  448. expectRun(t, `out = (1 > 2) == true`, nil, false)
  449. expectRun(t, `out = (1 > 2) == false`, nil, true)
  450. expectError(t, `5 + true`, nil, "invalid operation")
  451. expectError(t, `5 + true; 5`, nil, "invalid operation")
  452. expectError(t, `-true`, nil, "invalid operation")
  453. expectError(t, `true + false`, nil, "invalid operation")
  454. expectError(t, `5; true + false; 5`, nil, "invalid operation")
  455. expectError(t, `if (10 > 1) { true + false; }`, nil, "invalid operation")
  456. expectError(t, `
  457. func() {
  458. if (10 > 1) {
  459. if (10 > 1) {
  460. return true + false;
  461. }
  462. return 1;
  463. }
  464. }()
  465. `, nil, "invalid operation")
  466. expectError(t, `if (true + false) { 10 }`, nil, "invalid operation")
  467. expectError(t, `10 + (true + false)`, nil, "invalid operation")
  468. expectError(t, `(true + false) + 20`, nil, "invalid operation")
  469. expectError(t, `!(true + false)`, nil, "invalid operation")
  470. }
  471. func TestUndefined(t *testing.T) {
  472. expectRun(t, `out = undefined`, nil, tengo.UndefinedValue)
  473. expectRun(t, `out = undefined.a`, nil, tengo.UndefinedValue)
  474. expectRun(t, `out = undefined[1]`, nil, tengo.UndefinedValue)
  475. expectRun(t, `out = undefined.a.b`, nil, tengo.UndefinedValue)
  476. expectRun(t, `out = undefined[1][2]`, nil, tengo.UndefinedValue)
  477. expectRun(t, `out = undefined ? 1 : 2`, nil, 2)
  478. expectRun(t, `out = undefined == undefined`, nil, true)
  479. expectRun(t, `out = undefined == 1`, nil, false)
  480. expectRun(t, `out = 1 == undefined`, nil, false)
  481. expectRun(t, `out = undefined == float([])`, nil, true)
  482. expectRun(t, `out = float([]) == undefined`, nil, true)
  483. }
  484. func TestBuiltinFunction(t *testing.T) {
  485. expectRun(t, `out = len("")`, nil, 0)
  486. expectRun(t, `out = len("four")`, nil, 4)
  487. expectRun(t, `out = len("hello world")`, nil, 11)
  488. expectRun(t, `out = len([])`, nil, 0)
  489. expectRun(t, `out = len([1, 2, 3])`, nil, 3)
  490. expectRun(t, `out = len({})`, nil, 0)
  491. expectRun(t, `out = len({a:1, b:2})`, nil, 2)
  492. expectRun(t, `out = len(immutable([]))`, nil, 0)
  493. expectRun(t, `out = len(immutable([1, 2, 3]))`, nil, 3)
  494. expectRun(t, `out = len(immutable({}))`, nil, 0)
  495. expectRun(t, `out = len(immutable({a:1, b:2}))`, nil, 2)
  496. expectError(t, `len(1)`, nil, "invalid type for argument")
  497. expectError(t, `len("one", "two")`, nil, "wrong number of arguments")
  498. expectRun(t, `out = copy(1)`, nil, 1)
  499. expectError(t, `copy(1, 2)`, nil, "wrong number of arguments")
  500. expectRun(t, `out = append([1, 2, 3], 4)`, nil, ARR{1, 2, 3, 4})
  501. expectRun(t, `out = append([1, 2, 3], 4, 5, 6)`, nil, ARR{1, 2, 3, 4, 5, 6})
  502. expectRun(t, `out = append([1, 2, 3], "foo", false)`,
  503. nil, ARR{1, 2, 3, "foo", false})
  504. expectRun(t, `out = int(1)`, nil, 1)
  505. expectRun(t, `out = int(1.8)`, nil, 1)
  506. expectRun(t, `out = int("-522")`, nil, -522)
  507. expectRun(t, `out = int(true)`, nil, 1)
  508. expectRun(t, `out = int(false)`, nil, 0)
  509. expectRun(t, `out = int('8')`, nil, 56)
  510. expectRun(t, `out = int([1])`, nil, tengo.UndefinedValue)
  511. expectRun(t, `out = int({a: 1})`, nil, tengo.UndefinedValue)
  512. expectRun(t, `out = int(undefined)`, nil, tengo.UndefinedValue)
  513. expectRun(t, `out = int("-522", 1)`, nil, -522)
  514. expectRun(t, `out = int(undefined, 1)`, nil, 1)
  515. expectRun(t, `out = int(undefined, 1.8)`, nil, 1.8)
  516. expectRun(t, `out = int(undefined, string(1))`, nil, "1")
  517. expectRun(t, `out = int(undefined, undefined)`, nil, tengo.UndefinedValue)
  518. expectRun(t, `out = string(1)`, nil, "1")
  519. expectRun(t, `out = string(1.8)`, nil, "1.8")
  520. expectRun(t, `out = string("-522")`, nil, "-522")
  521. expectRun(t, `out = string(true)`, nil, "true")
  522. expectRun(t, `out = string(false)`, nil, "false")
  523. expectRun(t, `out = string('8')`, nil, "8")
  524. expectRun(t, `out = string([1,8.1,true,3])`, nil, "[1, 8.1, true, 3]")
  525. expectRun(t, `out = string({b: "foo"})`, nil, `{b: "foo"}`)
  526. expectRun(t, `out = string(undefined)`, nil, tengo.UndefinedValue) // not "undefined"
  527. expectRun(t, `out = string(1, "-522")`, nil, "1")
  528. expectRun(t, `out = string(undefined, "-522")`, nil, "-522") // not "undefined"
  529. expectRun(t, `out = float(1)`, nil, 1.0)
  530. expectRun(t, `out = float(1.8)`, nil, 1.8)
  531. expectRun(t, `out = float("-52.2")`, nil, -52.2)
  532. expectRun(t, `out = float(true)`, nil, tengo.UndefinedValue)
  533. expectRun(t, `out = float(false)`, nil, tengo.UndefinedValue)
  534. expectRun(t, `out = float('8')`, nil, tengo.UndefinedValue)
  535. expectRun(t, `out = float([1,8.1,true,3])`, nil, tengo.UndefinedValue)
  536. expectRun(t, `out = float({a: 1, b: "foo"})`, nil, tengo.UndefinedValue)
  537. expectRun(t, `out = float(undefined)`, nil, tengo.UndefinedValue)
  538. expectRun(t, `out = float("-52.2", 1.8)`, nil, -52.2)
  539. expectRun(t, `out = float(undefined, 1)`, nil, 1)
  540. expectRun(t, `out = float(undefined, 1.8)`, nil, 1.8)
  541. expectRun(t, `out = float(undefined, "-52.2")`, nil, "-52.2")
  542. expectRun(t, `out = float(undefined, char(56))`, nil, '8')
  543. expectRun(t, `out = float(undefined, undefined)`, nil, tengo.UndefinedValue)
  544. expectRun(t, `out = char(56)`, nil, '8')
  545. expectRun(t, `out = char(1.8)`, nil, tengo.UndefinedValue)
  546. expectRun(t, `out = char("-52.2")`, nil, tengo.UndefinedValue)
  547. expectRun(t, `out = char(true)`, nil, tengo.UndefinedValue)
  548. expectRun(t, `out = char(false)`, nil, tengo.UndefinedValue)
  549. expectRun(t, `out = char('8')`, nil, '8')
  550. expectRun(t, `out = char([1,8.1,true,3])`, nil, tengo.UndefinedValue)
  551. expectRun(t, `out = char({a: 1, b: "foo"})`, nil, tengo.UndefinedValue)
  552. expectRun(t, `out = char(undefined)`, nil, tengo.UndefinedValue)
  553. expectRun(t, `out = char(56, 'a')`, nil, '8')
  554. expectRun(t, `out = char(undefined, '8')`, nil, '8')
  555. expectRun(t, `out = char(undefined, 56)`, nil, 56)
  556. expectRun(t, `out = char(undefined, "-52.2")`, nil, "-52.2")
  557. expectRun(t, `out = char(undefined, undefined)`, nil, tengo.UndefinedValue)
  558. expectRun(t, `out = bool(1)`, nil, true) // non-zero integer: true
  559. expectRun(t, `out = bool(0)`, nil, false) // zero: true
  560. expectRun(t, `out = bool(1.8)`, nil, true) // all floats (except for NaN): true
  561. expectRun(t, `out = bool(0.0)`, nil, true) // all floats (except for NaN): true
  562. expectRun(t, `out = bool("false")`, nil, true) // non-empty string: true
  563. expectRun(t, `out = bool("")`, nil, false) // empty string: false
  564. expectRun(t, `out = bool(true)`, nil, true) // true: true
  565. expectRun(t, `out = bool(false)`, nil, false) // false: false
  566. expectRun(t, `out = bool('8')`, nil, true) // non-zero chars: true
  567. expectRun(t, `out = bool(char(0))`, nil, false) // zero char: false
  568. expectRun(t, `out = bool([1])`, nil, true) // non-empty arrays: true
  569. expectRun(t, `out = bool([])`, nil, false) // empty array: false
  570. expectRun(t, `out = bool({a: 1})`, nil, true) // non-empty maps: true
  571. expectRun(t, `out = bool({})`, nil, false) // empty maps: false
  572. expectRun(t, `out = bool(undefined)`, nil, false) // undefined: false
  573. expectRun(t, `out = bytes(1)`, nil, []byte{0})
  574. expectRun(t, `out = bytes(1.8)`, nil, tengo.UndefinedValue)
  575. expectRun(t, `out = bytes("-522")`, nil, []byte{'-', '5', '2', '2'})
  576. expectRun(t, `out = bytes(true)`, nil, tengo.UndefinedValue)
  577. expectRun(t, `out = bytes(false)`, nil, tengo.UndefinedValue)
  578. expectRun(t, `out = bytes('8')`, nil, tengo.UndefinedValue)
  579. expectRun(t, `out = bytes([1])`, nil, tengo.UndefinedValue)
  580. expectRun(t, `out = bytes({a: 1})`, nil, tengo.UndefinedValue)
  581. expectRun(t, `out = bytes(undefined)`, nil, tengo.UndefinedValue)
  582. expectRun(t, `out = bytes("-522", ['8'])`, nil, []byte{'-', '5', '2', '2'})
  583. expectRun(t, `out = bytes(undefined, "-522")`, nil, "-522")
  584. expectRun(t, `out = bytes(undefined, 1)`, nil, 1)
  585. expectRun(t, `out = bytes(undefined, 1.8)`, nil, 1.8)
  586. expectRun(t, `out = bytes(undefined, int("-522"))`, nil, -522)
  587. expectRun(t, `out = bytes(undefined, undefined)`, nil, tengo.UndefinedValue)
  588. expectRun(t, `out = is_error(error(1))`, nil, true)
  589. expectRun(t, `out = is_error(1)`, nil, false)
  590. expectRun(t, `out = is_undefined(undefined)`, nil, true)
  591. expectRun(t, `out = is_undefined(error(1))`, nil, false)
  592. // type_name
  593. expectRun(t, `out = type_name(1)`, nil, "int")
  594. expectRun(t, `out = type_name(1.1)`, nil, "float")
  595. expectRun(t, `out = type_name("a")`, nil, "string")
  596. expectRun(t, `out = type_name([1,2,3])`, nil, "array")
  597. expectRun(t, `out = type_name({k:1})`, nil, "map")
  598. expectRun(t, `out = type_name('a')`, nil, "char")
  599. expectRun(t, `out = type_name(true)`, nil, "bool")
  600. expectRun(t, `out = type_name(false)`, nil, "bool")
  601. expectRun(t, `out = type_name(bytes( 1))`, nil, "bytes")
  602. expectRun(t, `out = type_name(undefined)`, nil, "undefined")
  603. expectRun(t, `out = type_name(error("err"))`, nil, "error")
  604. expectRun(t, `out = type_name(func() {})`, nil, "compiled-function")
  605. expectRun(t, `a := func(x) { return func() { return x } }; out = type_name(a(5))`,
  606. nil, "compiled-function") // closure
  607. // is_function
  608. expectRun(t, `out = is_function(1)`, nil, false)
  609. expectRun(t, `out = is_function(func() {})`, nil, true)
  610. expectRun(t, `out = is_function(func(x) { return x })`, nil, true)
  611. expectRun(t, `out = is_function(len)`, nil, false) // builtin function
  612. expectRun(t, `a := func(x) { return func() { return x } }; out = is_function(a)`,
  613. nil, true) // function
  614. expectRun(t, `a := func(x) { return func() { return x } }; out = is_function(a(5))`,
  615. nil, true) // closure
  616. expectRun(t, `out = is_function(x)`,
  617. Opts().Symbol("x", &StringArray{
  618. Value: []string{"foo", "bar"},
  619. }).Skip2ndPass(),
  620. false) // user object
  621. // is_callable
  622. expectRun(t, `out = is_callable(1)`, nil, false)
  623. expectRun(t, `out = is_callable(func() {})`, nil, true)
  624. expectRun(t, `out = is_callable(func(x) { return x })`, nil, true)
  625. expectRun(t, `out = is_callable(len)`, nil, true) // builtin function
  626. expectRun(t, `a := func(x) { return func() { return x } }; out = is_callable(a)`,
  627. nil, true) // function
  628. expectRun(t, `a := func(x) { return func() { return x } }; out = is_callable(a(5))`,
  629. nil, true) // closure
  630. expectRun(t, `out = is_callable(x)`,
  631. Opts().Symbol("x", &StringArray{
  632. Value: []string{"foo", "bar"},
  633. }).Skip2ndPass(), true) // user object
  634. expectRun(t, `out = format("")`, nil, "")
  635. expectRun(t, `out = format("foo")`, nil, "foo")
  636. expectRun(t, `out = format("foo %d %v %s", 1, 2, "bar")`,
  637. nil, "foo 1 2 bar")
  638. expectRun(t, `out = format("foo %v", [1, "bar", true])`,
  639. nil, `foo [1, "bar", true]`)
  640. expectRun(t, `out = format("foo %v %d", [1, "bar", true], 19)`,
  641. nil, `foo [1, "bar", true] 19`)
  642. expectRun(t, `out = format("foo %v", {"a": {"b": {"c": [1, 2, 3]}}})`,
  643. nil, `foo {a: {b: {c: [1, 2, 3]}}}`)
  644. expectRun(t, `out = format("%v", [1, [2, [3, 4]]])`,
  645. nil, `[1, [2, [3, 4]]]`)
  646. tengo.MaxStringLen = 9
  647. expectError(t, `format("%s", "1234567890")`,
  648. nil, "exceeding string size limit")
  649. tengo.MaxStringLen = 2147483647
  650. // delete
  651. expectError(t, `delete()`, nil, tengo.ErrWrongNumArguments.Error())
  652. expectError(t, `delete(1)`, nil, tengo.ErrWrongNumArguments.Error())
  653. expectError(t, `delete(1, 2, 3)`, nil, tengo.ErrWrongNumArguments.Error())
  654. expectError(t, `delete({}, "", 3)`, nil, tengo.ErrWrongNumArguments.Error())
  655. expectError(t, `delete(1, 1)`, nil, `invalid type for argument 'first'`)
  656. expectError(t, `delete(1.0, 1)`, nil, `invalid type for argument 'first'`)
  657. expectError(t, `delete("str", 1)`, nil, `invalid type for argument 'first'`)
  658. expectError(t, `delete(bytes("str"), 1)`, nil,
  659. `invalid type for argument 'first'`)
  660. expectError(t, `delete(error("err"), 1)`, nil,
  661. `invalid type for argument 'first'`)
  662. expectError(t, `delete(true, 1)`, nil, `invalid type for argument 'first'`)
  663. expectError(t, `delete(char('c'), 1)`, nil,
  664. `invalid type for argument 'first'`)
  665. expectError(t, `delete(undefined, 1)`, nil,
  666. `invalid type for argument 'first'`)
  667. expectError(t, `delete(time(1257894000), 1)`, nil,
  668. `invalid type for argument 'first'`)
  669. expectError(t, `delete(immutable({}), "key")`, nil,
  670. `invalid type for argument 'first'`)
  671. expectError(t, `delete(immutable([]), "")`, nil,
  672. `invalid type for argument 'first'`)
  673. expectError(t, `delete([], "")`, nil, `invalid type for argument 'first'`)
  674. expectError(t, `delete({}, 1)`, nil, `invalid type for argument 'second'`)
  675. expectError(t, `delete({}, 1.0)`, nil, `invalid type for argument 'second'`)
  676. expectError(t, `delete({}, undefined)`, nil,
  677. `invalid type for argument 'second'`)
  678. expectError(t, `delete({}, [])`, nil, `invalid type for argument 'second'`)
  679. expectError(t, `delete({}, {})`, nil, `invalid type for argument 'second'`)
  680. expectError(t, `delete({}, error("err"))`, nil,
  681. `invalid type for argument 'second'`)
  682. expectError(t, `delete({}, bytes("str"))`, nil,
  683. `invalid type for argument 'second'`)
  684. expectError(t, `delete({}, char(35))`, nil,
  685. `invalid type for argument 'second'`)
  686. expectError(t, `delete({}, time(1257894000))`, nil,
  687. `invalid type for argument 'second'`)
  688. expectError(t, `delete({}, immutable({}))`, nil,
  689. `invalid type for argument 'second'`)
  690. expectError(t, `delete({}, immutable([]))`, nil,
  691. `invalid type for argument 'second'`)
  692. expectRun(t, `out = delete({}, "")`, nil, tengo.UndefinedValue)
  693. expectRun(t, `out = {key1: 1}; delete(out, "key1")`, nil, MAP{})
  694. expectRun(t, `out = {key1: 1, key2: "2"}; delete(out, "key1")`, nil,
  695. MAP{"key2": "2"})
  696. expectRun(t, `out = [1, "2", {a: "b", c: 10}]; delete(out[2], "c")`, nil,
  697. ARR{1, "2", MAP{"a": "b"}})
  698. // splice
  699. expectError(t, `splice()`, nil, tengo.ErrWrongNumArguments.Error())
  700. expectError(t, `splice(1)`, nil, `invalid type for argument 'first'`)
  701. expectError(t, `splice(1.0)`, nil, `invalid type for argument 'first'`)
  702. expectError(t, `splice("str")`, nil, `invalid type for argument 'first'`)
  703. expectError(t, `splice(bytes("str"))`, nil,
  704. `invalid type for argument 'first'`)
  705. expectError(t, `splice(error("err"))`, nil,
  706. `invalid type for argument 'first'`)
  707. expectError(t, `splice(true)`, nil, `invalid type for argument 'first'`)
  708. expectError(t, `splice(char('c'))`, nil,
  709. `invalid type for argument 'first'`)
  710. expectError(t, `splice(undefined)`, nil,
  711. `invalid type for argument 'first'`)
  712. expectError(t, `splice(time(1257894000))`, nil,
  713. `invalid type for argument 'first'`)
  714. expectError(t, `splice(immutable({}))`, nil,
  715. `invalid type for argument 'first'`)
  716. expectError(t, `splice(immutable([]))`, nil,
  717. `invalid type for argument 'first'`)
  718. expectError(t, `splice({})`, nil, `invalid type for argument 'first'`)
  719. expectError(t, `splice([], 1.0)`, nil,
  720. `invalid type for argument 'second'`)
  721. expectError(t, `splice([], "str")`, nil,
  722. `invalid type for argument 'second'`)
  723. expectError(t, `splice([], bytes("str"))`, nil,
  724. `invalid type for argument 'second'`)
  725. expectError(t, `splice([], error("error"))`, nil,
  726. `invalid type for argument 'second'`)
  727. expectError(t, `splice([], false)`, nil,
  728. `invalid type for argument 'second'`)
  729. expectError(t, `splice([], char('d'))`, nil,
  730. `invalid type for argument 'second'`)
  731. expectError(t, `splice([], undefined)`, nil,
  732. `invalid type for argument 'second'`)
  733. expectError(t, `splice([], time(0))`, nil,
  734. `invalid type for argument 'second'`)
  735. expectError(t, `splice([], [])`, nil,
  736. `invalid type for argument 'second'`)
  737. expectError(t, `splice([], {})`, nil,
  738. `invalid type for argument 'second'`)
  739. expectError(t, `splice([], immutable([]))`, nil,
  740. `invalid type for argument 'second'`)
  741. expectError(t, `splice([], immutable({}))`, nil,
  742. `invalid type for argument 'second'`)
  743. expectError(t, `splice([], 0, 1.0)`, nil,
  744. `invalid type for argument 'third'`)
  745. expectError(t, `splice([], 0, "string")`, nil,
  746. `invalid type for argument 'third'`)
  747. expectError(t, `splice([], 0, bytes("string"))`, nil,
  748. `invalid type for argument 'third'`)
  749. expectError(t, `splice([], 0, error("string"))`, nil,
  750. `invalid type for argument 'third'`)
  751. expectError(t, `splice([], 0, true)`, nil,
  752. `invalid type for argument 'third'`)
  753. expectError(t, `splice([], 0, char('f'))`, nil,
  754. `invalid type for argument 'third'`)
  755. expectError(t, `splice([], 0, undefined)`, nil,
  756. `invalid type for argument 'third'`)
  757. expectError(t, `splice([], 0, time(0))`, nil,
  758. `invalid type for argument 'third'`)
  759. expectError(t, `splice([], 0, [])`, nil,
  760. `invalid type for argument 'third'`)
  761. expectError(t, `splice([], 0, {})`, nil,
  762. `invalid type for argument 'third'`)
  763. expectError(t, `splice([], 0, immutable([]))`, nil,
  764. `invalid type for argument 'third'`)
  765. expectError(t, `splice([], 0, immutable({}))`, nil,
  766. `invalid type for argument 'third'`)
  767. expectError(t, `splice([], 1)`, nil, tengo.ErrIndexOutOfBounds.Error())
  768. expectError(t, `splice([1, 2, 3], 0, -1)`, nil,
  769. tengo.ErrIndexOutOfBounds.Error())
  770. expectError(t, `splice([1, 2, 3], 99, 0, "a", "b")`, nil,
  771. tengo.ErrIndexOutOfBounds.Error())
  772. expectRun(t, `out = []; splice(out)`, nil, ARR{})
  773. expectRun(t, `out = ["a"]; splice(out, 1)`, nil, ARR{"a"})
  774. expectRun(t, `out = ["a"]; out = splice(out, 1)`, nil, ARR{})
  775. expectRun(t, `out = [1, 2, 3]; splice(out, 0, 1)`, nil, ARR{2, 3})
  776. expectRun(t, `out = [1, 2, 3]; out = splice(out, 0, 1)`, nil, ARR{1})
  777. expectRun(t, `out = [1, 2, 3]; splice(out, 0, 0, "a", "b")`, nil,
  778. ARR{"a", "b", 1, 2, 3})
  779. expectRun(t, `out = [1, 2, 3]; out = splice(out, 0, 0, "a", "b")`, nil,
  780. ARR{})
  781. expectRun(t, `out = [1, 2, 3]; splice(out, 1, 0, "a", "b")`, nil,
  782. ARR{1, "a", "b", 2, 3})
  783. expectRun(t, `out = [1, 2, 3]; out = splice(out, 1, 0, "a", "b")`, nil,
  784. ARR{})
  785. expectRun(t, `out = [1, 2, 3]; splice(out, 1, 0, "a", "b")`, nil,
  786. ARR{1, "a", "b", 2, 3})
  787. expectRun(t, `out = [1, 2, 3]; splice(out, 2, 0, "a", "b")`, nil,
  788. ARR{1, 2, "a", "b", 3})
  789. expectRun(t, `out = [1, 2, 3]; splice(out, 3, 0, "a", "b")`, nil,
  790. ARR{1, 2, 3, "a", "b"})
  791. expectRun(t, `array := [1, 2, 3]; deleted := splice(array, 1, 1, "a", "b");
  792. out = [deleted, array]`, nil, ARR{ARR{2}, ARR{1, "a", "b", 3}})
  793. expectRun(t, `array := [1, 2, 3]; deleted := splice(array, 1);
  794. out = [deleted, array]`, nil, ARR{ARR{2, 3}, ARR{1}})
  795. expectRun(t, `out = []; splice(out, 0, 0, "a", "b")`, nil, ARR{"a", "b"})
  796. expectRun(t, `out = []; splice(out, 0, 1, "a", "b")`, nil, ARR{"a", "b"})
  797. expectRun(t, `out = []; out = splice(out, 0, 0, "a", "b")`, nil, ARR{})
  798. expectRun(t, `out = splice(splice([1, 2, 3], 0, 3), 1, 3)`, nil, ARR{2, 3})
  799. // splice doc examples
  800. expectRun(t, `v := [1, 2, 3]; deleted := splice(v, 0);
  801. out = [deleted, v]`, nil, ARR{ARR{1, 2, 3}, ARR{}})
  802. expectRun(t, `v := [1, 2, 3]; deleted := splice(v, 1);
  803. out = [deleted, v]`, nil, ARR{ARR{2, 3}, ARR{1}})
  804. expectRun(t, `v := [1, 2, 3]; deleted := splice(v, 0, 1);
  805. out = [deleted, v]`, nil, ARR{ARR{1}, ARR{2, 3}})
  806. expectRun(t, `v := ["a", "b", "c"]; deleted := splice(v, 1, 2);
  807. out = [deleted, v]`, nil, ARR{ARR{"b", "c"}, ARR{"a"}})
  808. expectRun(t, `v := ["a", "b", "c"]; deleted := splice(v, 2, 1, "d");
  809. out = [deleted, v]`, nil, ARR{ARR{"c"}, ARR{"a", "b", "d"}})
  810. expectRun(t, `v := ["a", "b", "c"]; deleted := splice(v, 0, 0, "d", "e");
  811. out = [deleted, v]`, nil, ARR{ARR{}, ARR{"d", "e", "a", "b", "c"}})
  812. expectRun(t, `v := ["a", "b", "c"]; deleted := splice(v, 1, 1, "d", "e");
  813. out = [deleted, v]`, nil, ARR{ARR{"b"}, ARR{"a", "d", "e", "c"}})
  814. }
  815. func TestBytesN(t *testing.T) {
  816. curMaxBytesLen := tengo.MaxBytesLen
  817. defer func() { tengo.MaxBytesLen = curMaxBytesLen }()
  818. tengo.MaxBytesLen = 10
  819. expectRun(t, `out = bytes(0)`, nil, make([]byte, 0))
  820. expectRun(t, `out = bytes(10)`, nil, make([]byte, 10))
  821. expectError(t, `bytes(11)`, nil, "bytes size limit")
  822. tengo.MaxBytesLen = 1000
  823. expectRun(t, `out = bytes(1000)`, nil, make([]byte, 1000))
  824. expectError(t, `bytes(1001)`, nil, "bytes size limit")
  825. }
  826. func TestBytes(t *testing.T) {
  827. expectRun(t, `out = bytes("Hello World!")`, nil, []byte("Hello World!"))
  828. expectRun(t, `out = bytes("Hello") + bytes(" ") + bytes("World!")`,
  829. nil, []byte("Hello World!"))
  830. // bytes[] -> int
  831. expectRun(t, `out = bytes("abcde")[0]`, nil, 97)
  832. expectRun(t, `out = bytes("abcde")[1]`, nil, 98)
  833. expectRun(t, `out = bytes("abcde")[4]`, nil, 101)
  834. expectRun(t, `out = bytes("abcde")[10]`, nil, tengo.UndefinedValue)
  835. }
  836. func TestCall(t *testing.T) {
  837. expectRun(t, `a := { b: func(x) { return x + 2 } }; out = a.b(5)`,
  838. nil, 7)
  839. expectRun(t, `a := { b: { c: func(x) { return x + 2 } } }; out = a.b.c(5)`,
  840. nil, 7)
  841. expectRun(t, `a := { b: { c: func(x) { return x + 2 } } }; out = a["b"].c(5)`,
  842. nil, 7)
  843. expectError(t, `a := 1
  844. b := func(a, c) {
  845. c(a)
  846. }
  847. c := func(a) {
  848. a()
  849. }
  850. b(a, c)
  851. `, nil, "Runtime Error: not callable: int\n\tat test:7:4\n\tat test:3:4\n\tat test:9:1")
  852. }
  853. func TestChar(t *testing.T) {
  854. expectRun(t, `out = 'a'`, nil, 'a')
  855. expectRun(t, `out = '九'`, nil, rune(20061))
  856. expectRun(t, `out = 'Æ'`, nil, rune(198))
  857. expectRun(t, `out = '0' + '9'`, nil, rune(105))
  858. expectRun(t, `out = '0' + 9`, nil, '9')
  859. expectRun(t, `out = '9' - 4`, nil, '5')
  860. expectRun(t, `out = '0' == '0'`, nil, true)
  861. expectRun(t, `out = '0' != '0'`, nil, false)
  862. expectRun(t, `out = '2' < '4'`, nil, true)
  863. expectRun(t, `out = '2' > '4'`, nil, false)
  864. expectRun(t, `out = '2' <= '4'`, nil, true)
  865. expectRun(t, `out = '2' >= '4'`, nil, false)
  866. expectRun(t, `out = '4' < '4'`, nil, false)
  867. expectRun(t, `out = '4' > '4'`, nil, false)
  868. expectRun(t, `out = '4' <= '4'`, nil, true)
  869. expectRun(t, `out = '4' >= '4'`, nil, true)
  870. }
  871. func TestCondExpr(t *testing.T) {
  872. expectRun(t, `out = true ? 5 : 10`, nil, 5)
  873. expectRun(t, `out = false ? 5 : 10`, nil, 10)
  874. expectRun(t, `out = (1 == 1) ? 2 + 3 : 12 - 2`, nil, 5)
  875. expectRun(t, `out = (1 != 1) ? 2 + 3 : 12 - 2`, nil, 10)
  876. expectRun(t, `out = (1 == 1) ? true ? 10 - 8 : 1 + 3 : 12 - 2`, nil, 2)
  877. expectRun(t, `out = (1 == 1) ? false ? 10 - 8 : 1 + 3 : 12 - 2`, nil, 4)
  878. expectRun(t, `
  879. out = 0
  880. f1 := func() { out += 10 }
  881. f2 := func() { out = -out }
  882. true ? f1() : f2()
  883. `, nil, 10)
  884. expectRun(t, `
  885. out = 5
  886. f1 := func() { out += 10 }
  887. f2 := func() { out = -out }
  888. false ? f1() : f2()
  889. `, nil, -5)
  890. expectRun(t, `
  891. f1 := func(a) { return a + 2 }
  892. f2 := func(a) { return a - 2 }
  893. f3 := func(a) { return a + 10 }
  894. f4 := func(a) { return -a }
  895. f := func(c) {
  896. return c == 0 ? f1(c) : f2(c) ? f3(c) : f4(c)
  897. }
  898. out = [f(0), f(1), f(2)]
  899. `, nil, ARR{2, 11, -2})
  900. expectRun(t, `f := func(a) { return -a }; out = f(true ? 5 : 3)`, nil, -5)
  901. expectRun(t, `out = [false?5:10, true?1:2]`, nil, ARR{10, 1})
  902. expectRun(t, `
  903. out = 1 > 2 ?
  904. 1 + 2 + 3 :
  905. 10 - 5`, nil, 5)
  906. }
  907. func TestEquality(t *testing.T) {
  908. testEquality(t, `1`, `1`, true)
  909. testEquality(t, `1`, `2`, false)
  910. testEquality(t, `1.0`, `1.0`, true)
  911. testEquality(t, `1.0`, `1.1`, false)
  912. testEquality(t, `true`, `true`, true)
  913. testEquality(t, `true`, `false`, false)
  914. testEquality(t, `"foo"`, `"foo"`, true)
  915. testEquality(t, `"foo"`, `"bar"`, false)
  916. testEquality(t, `'f'`, `'f'`, true)
  917. testEquality(t, `'f'`, `'b'`, false)
  918. testEquality(t, `[]`, `[]`, true)
  919. testEquality(t, `[1]`, `[1]`, true)
  920. testEquality(t, `[1]`, `[1, 2]`, false)
  921. testEquality(t, `["foo", "bar"]`, `["foo", "bar"]`, true)
  922. testEquality(t, `["foo", "bar"]`, `["bar", "foo"]`, false)
  923. testEquality(t, `{}`, `{}`, true)
  924. testEquality(t, `{a: 1, b: 2}`, `{b: 2, a: 1}`, true)
  925. testEquality(t, `{a: 1, b: 2}`, `{b: 2}`, false)
  926. testEquality(t, `{a: 1, b: {}}`, `{b: {}, a: 1}`, true)
  927. testEquality(t, `1`, `"foo"`, false)
  928. testEquality(t, `1`, `true`, false)
  929. testEquality(t, `[1]`, `["1"]`, false)
  930. testEquality(t, `[1, [2]]`, `[1, ["2"]]`, false)
  931. testEquality(t, `{a: 1}`, `{a: "1"}`, false)
  932. testEquality(t, `{a: 1, b: {c: 2}}`, `{a: 1, b: {c: "2"}}`, false)
  933. }
  934. func testEquality(t *testing.T, lhs, rhs string, expected bool) {
  935. // 1. equality is commutative
  936. // 2. equality and inequality must be always opposite
  937. expectRun(t, fmt.Sprintf("out = %s == %s", lhs, rhs), nil, expected)
  938. expectRun(t, fmt.Sprintf("out = %s == %s", rhs, lhs), nil, expected)
  939. expectRun(t, fmt.Sprintf("out = %s != %s", lhs, rhs), nil, !expected)
  940. expectRun(t, fmt.Sprintf("out = %s != %s", rhs, lhs), nil, !expected)
  941. }
  942. func TestVMErrorInfo(t *testing.T) {
  943. expectError(t, `a := 5
  944. a + "boo"`,
  945. nil, "Runtime Error: invalid operation: int + string\n\tat test:2:1")
  946. expectError(t, `a := 5
  947. b := a(5)`,
  948. nil, "Runtime Error: not callable: int\n\tat test:2:6")
  949. expectError(t, `a := 5
  950. b := {}
  951. b.x.y = 10`,
  952. nil, "Runtime Error: not index-assignable: undefined\n\tat test:3:1")
  953. expectError(t, `
  954. a := func() {
  955. b := 5
  956. b += "foo"
  957. }
  958. a()`,
  959. nil, "Runtime Error: invalid operation: int + string\n\tat test:4:2")
  960. expectError(t, `a := 5
  961. a + import("mod1")`, Opts().Module(
  962. "mod1", `export "foo"`,
  963. ), ": invalid operation: int + string\n\tat test:2:1")
  964. expectError(t, `a := import("mod1")()`,
  965. Opts().Module(
  966. "mod1", `
  967. export func() {
  968. b := 5
  969. return b + "foo"
  970. }`), "Runtime Error: invalid operation: int + string\n\tat mod1:4:9")
  971. expectError(t, `a := import("mod1")()`,
  972. Opts().Module(
  973. "mod1", `export import("mod2")()`).
  974. Module(
  975. "mod2", `
  976. export func() {
  977. b := 5
  978. return b + "foo"
  979. }`), "Runtime Error: invalid operation: int + string\n\tat mod2:4:9")
  980. expectError(t, `a := [1, 2, 3]; b := a[:"invalid"];`, nil,
  981. "Runtime Error: invalid slice index type: string")
  982. expectError(t, `a := immutable([4, 5, 6]); b := a[:false];`, nil,
  983. "Runtime Error: invalid slice index type: bool")
  984. expectError(t, `a := "hello"; b := a[:1.23];`, nil,
  985. "Runtime Error: invalid slice index type: float")
  986. expectError(t, `a := bytes("world"); b := a[:time(1)];`, nil,
  987. "Runtime Error: invalid slice index type: time")
  988. }
  989. func TestVMErrorUnwrap(t *testing.T) {
  990. userErr := errors.New("user runtime error")
  991. userFunc := func(err error) *tengo.UserFunction {
  992. return &tengo.UserFunction{Name: "user_func", Value: func(args ...tengo.Object) (tengo.Object, error) {
  993. return nil, err
  994. }}
  995. }
  996. userModule := func(err error) *tengo.BuiltinModule {
  997. return &tengo.BuiltinModule{
  998. Attrs: map[string]tengo.Object{
  999. "afunction": &tengo.UserFunction{
  1000. Name: "afunction",
  1001. Value: func(a ...tengo.Object) (tengo.Object, error) {
  1002. return nil, err
  1003. },
  1004. },
  1005. },
  1006. }
  1007. }
  1008. expectError(t, `user_func()`,
  1009. Opts().Symbol("user_func", userFunc(userErr)),
  1010. "Runtime Error: "+userErr.Error(),
  1011. )
  1012. expectErrorIs(t, `user_func()`,
  1013. Opts().Symbol("user_func", userFunc(userErr)),
  1014. userErr,
  1015. )
  1016. wrapUserErr := &customError{err: userErr, str: "custom error"}
  1017. expectErrorIs(t, `user_func()`,
  1018. Opts().Symbol("user_func", userFunc(wrapUserErr)),
  1019. wrapUserErr,
  1020. )
  1021. expectErrorIs(t, `user_func()`,
  1022. Opts().Symbol("user_func", userFunc(wrapUserErr)),
  1023. userErr,
  1024. )
  1025. var asErr1 *customError
  1026. expectErrorAs(t, `user_func()`,
  1027. Opts().Symbol("user_func", userFunc(wrapUserErr)),
  1028. &asErr1,
  1029. )
  1030. require.True(t, asErr1.Error() == wrapUserErr.Error(),
  1031. "expected error as:%v, got:%v", wrapUserErr, asErr1)
  1032. expectError(t, `import("mod1").afunction()`,
  1033. Opts().Module("mod1", userModule(userErr)),
  1034. "Runtime Error: "+userErr.Error(),
  1035. )
  1036. expectErrorIs(t, `import("mod1").afunction()`,
  1037. Opts().Module("mod1", userModule(userErr)),
  1038. userErr,
  1039. )
  1040. expectError(t, `import("mod1").afunction()`,
  1041. Opts().Module("mod1", userModule(wrapUserErr)),
  1042. "Runtime Error: "+wrapUserErr.Error(),
  1043. )
  1044. expectErrorIs(t, `import("mod1").afunction()`,
  1045. Opts().Module("mod1", userModule(wrapUserErr)),
  1046. wrapUserErr,
  1047. )
  1048. expectErrorIs(t, `import("mod1").afunction()`,
  1049. Opts().Module("mod1", userModule(wrapUserErr)),
  1050. userErr,
  1051. )
  1052. var asErr2 *customError
  1053. expectErrorAs(t, `import("mod1").afunction()`,
  1054. Opts().Module("mod1", userModule(wrapUserErr)),
  1055. &asErr2,
  1056. )
  1057. require.True(t, asErr2.Error() == wrapUserErr.Error(),
  1058. "expected error as:%v, got:%v", wrapUserErr, asErr2)
  1059. }
  1060. func TestError(t *testing.T) {
  1061. expectRun(t, `out = error(1)`, nil, errorObject(1))
  1062. expectRun(t, `out = error(1).value`, nil, 1)
  1063. expectRun(t, `out = error("some error")`, nil, errorObject("some error"))
  1064. expectRun(t, `out = error("some" + " error")`, nil, errorObject("some error"))
  1065. expectRun(t, `out = func() { return error(5) }()`, nil, errorObject(5))
  1066. expectRun(t, `out = error(error("foo"))`, nil, errorObject(errorObject("foo")))
  1067. expectRun(t, `out = error("some error")`, nil, errorObject("some error"))
  1068. expectRun(t, `out = error("some error").value`, nil, "some error")
  1069. expectRun(t, `out = error("some error")["value"]`, nil, "some error")
  1070. expectError(t, `error("error").err`, nil, "invalid index on error")
  1071. expectError(t, `error("error").value_`, nil, "invalid index on error")
  1072. expectError(t, `error([1,2,3])[1]`, nil, "invalid index on error")
  1073. }
  1074. func TestFloat(t *testing.T) {
  1075. expectRun(t, `out = 0.0`, nil, 0.0)
  1076. expectRun(t, `out = -10.3`, nil, -10.3)
  1077. expectRun(t, `out = 3.2 + 2.0 * -4.0`, nil, -4.8)
  1078. expectRun(t, `out = 4 + 2.3`, nil, 6.3)
  1079. expectRun(t, `out = 2.3 + 4`, nil, 6.3)
  1080. expectRun(t, `out = +5.0`, nil, 5.0)
  1081. expectRun(t, `out = -5.0 + +5.0`, nil, 0.0)
  1082. }
  1083. func TestForIn(t *testing.T) {
  1084. // array
  1085. expectRun(t, `out = 0; for x in [1, 2, 3] { out += x }`,
  1086. nil, 6) // value
  1087. expectRun(t, `out = 0; for i, x in [1, 2, 3] { out += i + x }`,
  1088. nil, 9) // index, value
  1089. expectRun(t, `out = 0; func() { for i, x in [1, 2, 3] { out += i + x } }()`,
  1090. nil, 9) // index, value
  1091. expectRun(t, `out = 0; for i, _ in [1, 2, 3] { out += i }`,
  1092. nil, 3) // index, _
  1093. expectRun(t, `out = 0; func() { for i, _ in [1, 2, 3] { out += i } }()`,
  1094. nil, 3) // index, _
  1095. // map
  1096. expectRun(t, `out = 0; for v in {a:2,b:3,c:4} { out += v }`,
  1097. nil, 9) // value
  1098. expectRun(t, `out = ""; for k, v in {a:2,b:3,c:4} { out = k; if v==3 { break } }`,
  1099. nil, "b") // key, value
  1100. expectRun(t, `out = ""; for k, _ in {a:2} { out += k }`,
  1101. nil, "a") // key, _
  1102. expectRun(t, `out = 0; for _, v in {a:2,b:3,c:4} { out += v }`,
  1103. nil, 9) // _, value
  1104. expectRun(t, `out = ""; func() { for k, v in {a:2,b:3,c:4} { out = k; if v==3 { break } } }()`,
  1105. nil, "b") // key, value
  1106. // string
  1107. expectRun(t, `out = ""; for c in "abcde" { out += c }`,
  1108. nil, "abcde")
  1109. expectRun(t, `out = ""; for i, c in "abcde" { if i == 2 { continue }; out += c }`,
  1110. nil, "abde")
  1111. }
  1112. func TestFor(t *testing.T) {
  1113. expectRun(t, `
  1114. out = 0
  1115. for {
  1116. out++
  1117. if out == 5 {
  1118. break
  1119. }
  1120. }`, nil, 5)
  1121. expectRun(t, `
  1122. out = 0
  1123. for {
  1124. out++
  1125. if out == 5 {
  1126. break
  1127. }
  1128. }`, nil, 5)
  1129. expectRun(t, `
  1130. out = 0
  1131. a := 0
  1132. for {
  1133. a++
  1134. if a == 3 { continue }
  1135. if a == 5 { break }
  1136. out += a
  1137. }`, nil, 7) // 1 + 2 + 4
  1138. expectRun(t, `
  1139. out = 0
  1140. a := 0
  1141. for {
  1142. a++
  1143. if a == 3 { continue }
  1144. out += a
  1145. if a == 5 { break }
  1146. }`, nil, 12) // 1 + 2 + 4 + 5
  1147. expectRun(t, `
  1148. out = 0
  1149. for true {
  1150. out++
  1151. if out == 5 {
  1152. break
  1153. }
  1154. }`, nil, 5)
  1155. expectRun(t, `
  1156. a := 0
  1157. for true {
  1158. a++
  1159. if a == 5 {
  1160. break
  1161. }
  1162. }
  1163. out = a`, nil, 5)
  1164. expectRun(t, `
  1165. out = 0
  1166. a := 0
  1167. for true {
  1168. a++
  1169. if a == 3 { continue }
  1170. if a == 5 { break }
  1171. out += a
  1172. }`, nil, 7) // 1 + 2 + 4
  1173. expectRun(t, `
  1174. out = 0
  1175. a := 0
  1176. for true {
  1177. a++
  1178. if a == 3 { continue }
  1179. out += a
  1180. if a == 5 { break }
  1181. }`, nil, 12) // 1 + 2 + 4 + 5
  1182. expectRun(t, `
  1183. out = 0
  1184. func() {
  1185. for true {
  1186. out++
  1187. if out == 5 {
  1188. return
  1189. }
  1190. }
  1191. }()`, nil, 5)
  1192. expectRun(t, `
  1193. out = 0
  1194. for a:=1; a<=10; a++ {
  1195. out += a
  1196. }`, nil, 55)
  1197. expectRun(t, `
  1198. out = 0
  1199. for a:=1; a<=3; a++ {
  1200. for b:=3; b<=6; b++ {
  1201. out += b
  1202. }
  1203. }`, nil, 54)
  1204. expectRun(t, `
  1205. out = 0
  1206. func() {
  1207. for {
  1208. out++
  1209. if out == 5 {
  1210. break
  1211. }
  1212. }
  1213. }()`, nil, 5)
  1214. expectRun(t, `
  1215. out = 0
  1216. func() {
  1217. for true {
  1218. out++
  1219. if out == 5 {
  1220. break
  1221. }
  1222. }
  1223. }()`, nil, 5)
  1224. expectRun(t, `
  1225. out = func() {
  1226. a := 0
  1227. for {
  1228. a++
  1229. if a == 5 {
  1230. break
  1231. }
  1232. }
  1233. return a
  1234. }()`, nil, 5)
  1235. expectRun(t, `
  1236. out = func() {
  1237. a := 0
  1238. for true {
  1239. a++
  1240. if a== 5 {
  1241. break
  1242. }
  1243. }
  1244. return a
  1245. }()`, nil, 5)
  1246. expectRun(t, `
  1247. out = func() {
  1248. a := 0
  1249. func() {
  1250. for {
  1251. a++
  1252. if a == 5 {
  1253. break
  1254. }
  1255. }
  1256. }()
  1257. return a
  1258. }()`, nil, 5)
  1259. expectRun(t, `
  1260. out = func() {
  1261. a := 0
  1262. func() {
  1263. for true {
  1264. a++
  1265. if a == 5 {
  1266. break
  1267. }
  1268. }
  1269. }()
  1270. return a
  1271. }()`, nil, 5)
  1272. expectRun(t, `
  1273. out = func() {
  1274. sum := 0
  1275. for a:=1; a<=10; a++ {
  1276. sum += a
  1277. }
  1278. return sum
  1279. }()`, nil, 55)
  1280. expectRun(t, `
  1281. out = func() {
  1282. sum := 0
  1283. for a:=1; a<=4; a++ {
  1284. for b:=3; b<=5; b++ {
  1285. sum += b
  1286. }
  1287. }
  1288. return sum
  1289. }()`, nil, 48) // (3+4+5) * 4
  1290. expectRun(t, `
  1291. a := 1
  1292. for ; a<=10; a++ {
  1293. if a == 5 {
  1294. break
  1295. }
  1296. }
  1297. out = a`, nil, 5)
  1298. expectRun(t, `
  1299. out = 0
  1300. for a:=1; a<=10; a++ {
  1301. if a == 3 {
  1302. continue
  1303. }
  1304. out += a
  1305. if a == 5 {
  1306. break
  1307. }
  1308. }`, nil, 12) // 1 + 2 + 4 + 5
  1309. expectRun(t, `
  1310. out = 0
  1311. for a:=1; a<=10; {
  1312. if a == 3 {
  1313. a++
  1314. continue
  1315. }
  1316. out += a
  1317. if a == 5 {
  1318. break
  1319. }
  1320. a++
  1321. }`, nil, 12) // 1 + 2 + 4 + 5
  1322. }
  1323. func TestFunction(t *testing.T) {
  1324. // function with no "return" statement returns "invalid" value.
  1325. expectRun(t, `f1 := func() {}; out = f1();`,
  1326. nil, tengo.UndefinedValue)
  1327. expectRun(t, `f1 := func() {}; f2 := func() { return f1(); }; f1(); out = f2();`,
  1328. nil, tengo.UndefinedValue)
  1329. expectRun(t, `f := func(x) { x; }; out = f(5);`,
  1330. nil, tengo.UndefinedValue)
  1331. expectRun(t, `f := func(...x) { return x; }; out = f(1,2,3);`,
  1332. nil, ARR{1, 2, 3})
  1333. expectRun(t, `f := func(a, b, ...x) { return [a, b, x]; }; out = f(8,9,1,2,3);`,
  1334. nil, ARR{8, 9, ARR{1, 2, 3}})
  1335. expectRun(t, `f := func(v) { x := 2; return func(a, ...b){ return [a, b, v+x]}; }; out = f(5)("a", "b");`,
  1336. nil, ARR{"a", ARR{"b"}, 7})
  1337. expectRun(t, `f := func(...x) { return x; }; out = f();`,
  1338. nil, &tengo.Array{Value: []tengo.Object{}})
  1339. expectRun(t, `f := func(a, b, ...x) { return [a, b, x]; }; out = f(8, 9);`,
  1340. nil, ARR{8, 9, ARR{}})
  1341. expectRun(t, `f := func(v) { x := 2; return func(a, ...b){ return [a, b, v+x]}; }; out = f(5)("a");`,
  1342. nil, ARR{"a", ARR{}, 7})
  1343. expectError(t, `f := func(a, b, ...x) { return [a, b, x]; }; f();`, nil,
  1344. "Runtime Error: wrong number of arguments: want>=2, got=0\n\tat test:1:46")
  1345. expectError(t, `f := func(a, b, ...x) { return [a, b, x]; }; f(1);`, nil,
  1346. "Runtime Error: wrong number of arguments: want>=2, got=1\n\tat test:1:46")
  1347. expectRun(t, `f := func(x) { return x; }; out = f(5);`, nil, 5)
  1348. expectRun(t, `f := func(x) { return x * 2; }; out = f(5);`, nil, 10)
  1349. expectRun(t, `f := func(x, y) { return x + y; }; out = f(5, 5);`, nil, 10)
  1350. expectRun(t, `f := func(x, y) { return x + y; }; out = f(5 + 5, f(5, 5));`,
  1351. nil, 20)
  1352. expectRun(t, `out = func(x) { return x; }(5)`, nil, 5)
  1353. expectRun(t, `x := 10; f := func(x) { return x; }; f(5); out = x;`, nil, 10)
  1354. expectRun(t, `
  1355. f2 := func(a) {
  1356. f1 := func(a) {
  1357. return a * 2;
  1358. };
  1359. return f1(a) * 3;
  1360. };
  1361. out = f2(10);
  1362. `, nil, 60)
  1363. expectRun(t, `
  1364. f1 := func(f) {
  1365. a := [undefined]
  1366. a[0] = func() { return f(a) }
  1367. return a[0]()
  1368. }
  1369. out = f1(func(a) { return 2 })
  1370. `, nil, 2)
  1371. // closures
  1372. expectRun(t, `
  1373. newAdder := func(x) {
  1374. return func(y) { return x + y };
  1375. };
  1376. add2 := newAdder(2);
  1377. out = add2(5);
  1378. `, nil, 7)
  1379. expectRun(t, `
  1380. m := {a: 1}
  1381. for k,v in m {
  1382. func(){
  1383. out = k
  1384. }()
  1385. }
  1386. `, nil, "a")
  1387. expectRun(t, `
  1388. m := {a: 1}
  1389. for k,v in m {
  1390. func(){
  1391. out = v
  1392. }()
  1393. }
  1394. `, nil, 1)
  1395. // function as a argument
  1396. expectRun(t, `
  1397. add := func(a, b) { return a + b };
  1398. sub := func(a, b) { return a - b };
  1399. applyFunc := func(a, b, f) { return f(a, b) };
  1400. out = applyFunc(applyFunc(2, 2, add), 3, sub);
  1401. `, nil, 1)
  1402. expectRun(t, `f1 := func() { return 5 + 10; }; out = f1();`,
  1403. nil, 15)
  1404. expectRun(t, `f1 := func() { return 1 }; f2 := func() { return 2 }; out = f1() + f2()`,
  1405. nil, 3)
  1406. expectRun(t, `f1 := func() { return 1 }; f2 := func() { return f1() + 2 }; f3 := func() { return f2() + 3 }; out = f3()`,
  1407. nil, 6)
  1408. expectRun(t, `f1 := func() { return 99; 100 }; out = f1();`,
  1409. nil, 99)
  1410. expectRun(t, `f1 := func() { return 99; return 100 }; out = f1();`,
  1411. nil, 99)
  1412. expectRun(t, `f1 := func() { return 33; }; f2 := func() { return f1 }; out = f2()();`,
  1413. nil, 33)
  1414. expectRun(t, `one := func() { one = 1; return one }; out = one()`,
  1415. nil, 1)
  1416. expectRun(t, `three := func() { one := 1; two := 2; return one + two }; out = three()`,
  1417. nil, 3)
  1418. expectRun(t, `three := func() { one := 1; two := 2; return one + two }; seven := func() { three := 3; four := 4; return three + four }; out = three() + seven()`,
  1419. nil, 10)
  1420. expectRun(t, `
  1421. foo1 := func() {
  1422. foo := 50
  1423. return foo
  1424. }
  1425. foo2 := func() {
  1426. foo := 100
  1427. return foo
  1428. }
  1429. out = foo1() + foo2()`, nil, 150)
  1430. expectRun(t, `
  1431. g := 50;
  1432. minusOne := func() {
  1433. n := 1;
  1434. return g - n;
  1435. };
  1436. minusTwo := func() {
  1437. n := 2;
  1438. return g - n;
  1439. };
  1440. out = minusOne() + minusTwo()
  1441. `, nil, 97)
  1442. expectRun(t, `
  1443. f1 := func() {
  1444. f2 := func() { return 1; }
  1445. return f2
  1446. };
  1447. out = f1()()
  1448. `, nil, 1)
  1449. expectRun(t, `
  1450. f1 := func(a) { return a; };
  1451. out = f1(4)`, nil, 4)
  1452. expectRun(t, `
  1453. f1 := func(a, b) { return a + b; };
  1454. out = f1(1, 2)`, nil, 3)
  1455. expectRun(t, `
  1456. sum := func(a, b) {
  1457. c := a + b;
  1458. return c;
  1459. };
  1460. out = sum(1, 2);`, nil, 3)
  1461. expectRun(t, `
  1462. sum := func(a, b) {
  1463. c := a + b;
  1464. return c;
  1465. };
  1466. out = sum(1, 2) + sum(3, 4);`, nil, 10)
  1467. expectRun(t, `
  1468. sum := func(a, b) {
  1469. c := a + b
  1470. return c
  1471. };
  1472. outer := func() {
  1473. return sum(1, 2) + sum(3, 4)
  1474. };
  1475. out = outer();`, nil, 10)
  1476. expectRun(t, `
  1477. g := 10;
  1478. sum := func(a, b) {
  1479. c := a + b;
  1480. return c + g;
  1481. }
  1482. outer := func() {
  1483. return sum(1, 2) + sum(3, 4) + g;
  1484. }
  1485. out = outer() + g
  1486. `, nil, 50)
  1487. expectError(t, `func() { return 1; }(1)`,
  1488. nil, "wrong number of arguments")
  1489. expectError(t, `func(a) { return a; }()`,
  1490. nil, "wrong number of arguments")
  1491. expectError(t, `func(a, b) { return a + b; }(1)`,
  1492. nil, "wrong number of arguments")
  1493. expectRun(t, `
  1494. f1 := func(a) {
  1495. return func() { return a; };
  1496. };
  1497. f2 := f1(99);
  1498. out = f2()
  1499. `, nil, 99)
  1500. expectRun(t, `
  1501. f1 := func(a, b) {
  1502. return func(c) { return a + b + c };
  1503. };
  1504. f2 := f1(1, 2);
  1505. out = f2(8);
  1506. `, nil, 11)
  1507. expectRun(t, `
  1508. f1 := func(a, b) {
  1509. c := a + b;
  1510. return func(d) { return c + d };
  1511. };
  1512. f2 := f1(1, 2);
  1513. out = f2(8);
  1514. `, nil, 11)
  1515. expectRun(t, `
  1516. f1 := func(a, b) {
  1517. c := a + b;
  1518. return func(d) {
  1519. e := d + c;
  1520. return func(f) { return e + f };
  1521. }
  1522. };
  1523. f2 := f1(1, 2);
  1524. f3 := f2(3);
  1525. out = f3(8);
  1526. `, nil, 14)
  1527. expectRun(t, `
  1528. a := 1;
  1529. f1 := func(b) {
  1530. return func(c) {
  1531. return func(d) { return a + b + c + d }
  1532. };
  1533. };
  1534. f2 := f1(2);
  1535. f3 := f2(3);
  1536. out = f3(8);
  1537. `, nil, 14)
  1538. expectRun(t, `
  1539. f1 := func(a, b) {
  1540. one := func() { return a; };
  1541. two := func() { return b; };
  1542. return func() { return one() + two(); }
  1543. };
  1544. f2 := f1(9, 90);
  1545. out = f2();
  1546. `, nil, 99)
  1547. // global function recursion
  1548. expectRun(t, `
  1549. fib := func(x) {
  1550. if x == 0 {
  1551. return 0
  1552. } else if x == 1 {
  1553. return 1
  1554. } else {
  1555. return fib(x-1) + fib(x-2)
  1556. }
  1557. }
  1558. out = fib(15)`, nil, 610)
  1559. // local function recursion
  1560. expectRun(t, `
  1561. out = func() {
  1562. sum := func(x) {
  1563. return x == 0 ? 0 : x + sum(x-1)
  1564. }
  1565. return sum(5)
  1566. }()`, nil, 15)
  1567. expectError(t, `return 5`, nil, "return not allowed outside function")
  1568. // closure and block scopes
  1569. expectRun(t, `
  1570. func() {
  1571. a := 10
  1572. func() {
  1573. b := 5
  1574. if true {
  1575. out = a + 5
  1576. }
  1577. }()
  1578. }()`, nil, 15)
  1579. expectRun(t, `
  1580. func() {
  1581. a := 10
  1582. b := func() { return 5 }
  1583. func() {
  1584. if b() {
  1585. out = a + b()
  1586. }
  1587. }()
  1588. }()`, nil, 15)
  1589. expectRun(t, `
  1590. func() {
  1591. a := 10
  1592. func() {
  1593. b := func() { return 5 }
  1594. func() {
  1595. if true {
  1596. out = a + b()
  1597. }
  1598. }()
  1599. }()
  1600. }()`, nil, 15)
  1601. // function skipping return
  1602. expectRun(t, `out = func() {}()`,
  1603. nil, tengo.UndefinedValue)
  1604. expectRun(t, `out = func(v) { if v { return true } }(1)`,
  1605. nil, true)
  1606. expectRun(t, `out = func(v) { if v { return true } }(0)`,
  1607. nil, tengo.UndefinedValue)
  1608. expectRun(t, `out = func(v) { if v { } else { return true } }(1)`,
  1609. nil, tengo.UndefinedValue)
  1610. expectRun(t, `out = func(v) { if v { return } }(1)`,
  1611. nil, tengo.UndefinedValue)
  1612. expectRun(t, `out = func(v) { if v { return } }(0)`,
  1613. nil, tengo.UndefinedValue)
  1614. expectRun(t, `out = func(v) { if v { } else { return } }(1)`,
  1615. nil, tengo.UndefinedValue)
  1616. expectRun(t, `out = func(v) { for ;;v++ { if v == 3 { return true } } }(1)`,
  1617. nil, true)
  1618. expectRun(t, `out = func(v) { for ;;v++ { if v == 3 { break } } }(1)`,
  1619. nil, tengo.UndefinedValue)
  1620. // 'f' in RHS at line 4 must reference global variable 'f'
  1621. // See https://github.com/d5/tengo/issues/314
  1622. expectRun(t, `
  1623. f := func() { return 2 }
  1624. out = (func() {
  1625. f := f()
  1626. return f
  1627. })()
  1628. `, nil, 2)
  1629. }
  1630. func TestBlocksInGlobalScope(t *testing.T) {
  1631. expectRun(t, `
  1632. f := undefined
  1633. if true {
  1634. a := 1
  1635. f = func() {
  1636. a = 2
  1637. }
  1638. }
  1639. b := 3
  1640. f()
  1641. out = b`,
  1642. nil, 3)
  1643. expectRun(t, `
  1644. func() {
  1645. f := undefined
  1646. if true {
  1647. a := 10
  1648. f = func() {
  1649. a = 20
  1650. }
  1651. }
  1652. b := 5
  1653. f()
  1654. out = b
  1655. }()
  1656. `,
  1657. nil, 5)
  1658. expectRun(t, `
  1659. f := undefined
  1660. if true {
  1661. a := 1
  1662. b := 2
  1663. f = func() {
  1664. a = 3
  1665. b = 4
  1666. }
  1667. }
  1668. c := 5
  1669. d := 6
  1670. f()
  1671. out = c + d`,
  1672. nil, 11)
  1673. expectRun(t, `
  1674. fn := undefined
  1675. if true {
  1676. a := 1
  1677. b := 2
  1678. if true {
  1679. c := 3
  1680. d := 4
  1681. fn = func() {
  1682. a = 5
  1683. b = 6
  1684. c = 7
  1685. d = 8
  1686. }
  1687. }
  1688. }
  1689. e := 9
  1690. f := 10
  1691. fn()
  1692. out = e + f`,
  1693. nil, 19)
  1694. expectRun(t, `
  1695. out = 0
  1696. func() {
  1697. for x in [1, 2, 3] {
  1698. out += x
  1699. }
  1700. }()`,
  1701. nil, 6)
  1702. expectRun(t, `
  1703. out = 0
  1704. for x in [1, 2, 3] {
  1705. out += x
  1706. }`,
  1707. nil, 6)
  1708. }
  1709. func TestIf(t *testing.T) {
  1710. expectRun(t, `if (true) { out = 10 }`, nil, 10)
  1711. expectRun(t, `if (false) { out = 10 }`, nil, tengo.UndefinedValue)
  1712. expectRun(t, `if (false) { out = 10 } else { out = 20 }`, nil, 20)
  1713. expectRun(t, `if (1) { out = 10 }`, nil, 10)
  1714. expectRun(t, `if (0) { out = 10 } else { out = 20 }`, nil, 20)
  1715. expectRun(t, `if (1 < 2) { out = 10 }`, nil, 10)
  1716. expectRun(t, `if (1 > 2) { out = 10 }`, nil, tengo.UndefinedValue)
  1717. expectRun(t, `if (1 < 2) { out = 10 } else { out = 20 }`, nil, 10)
  1718. expectRun(t, `if (1 > 2) { out = 10 } else { out = 20 }`, nil, 20)
  1719. expectRun(t, `if (1 < 2) { out = 10 } else if (1 > 2) { out = 20 } else { out = 30 }`,
  1720. nil, 10)
  1721. expectRun(t, `if (1 > 2) { out = 10 } else if (1 < 2) { out = 20 } else { out = 30 }`,
  1722. nil, 20)
  1723. expectRun(t, `if (1 > 2) { out = 10 } else if (1 == 2) { out = 20 } else { out = 30 }`,
  1724. nil, 30)
  1725. expectRun(t, `if (1 > 2) { out = 10 } else if (1 == 2) { out = 20 } else if (1 < 2) { out = 30 } else { out = 40 }`,
  1726. nil, 30)
  1727. expectRun(t, `if (1 > 2) { out = 10 } else if (1 < 2) { out = 20; out = 21; out = 22 } else { out = 30 }`,
  1728. nil, 22)
  1729. expectRun(t, `if (1 > 2) { out = 10 } else if (1 == 2) { out = 20 } else { out = 30; out = 31; out = 32}`,
  1730. nil, 32)
  1731. expectRun(t, `if (1 > 2) { out = 10 } else if (1 < 2) { if (1 == 2) { out = 21 } else { out = 22 } } else { out = 30 }`,
  1732. nil, 22)
  1733. expectRun(t, `if (1 > 2) { out = 10 } else if (1 < 2) { if (1 == 2) { out = 21 } else if (2 == 3) { out = 22 } else { out = 23 } } else { out = 30 }`,
  1734. nil, 23)
  1735. expectRun(t, `if (1 > 2) { out = 10 } else if (1 == 2) { if (1 == 2) { out = 21 } else if (2 == 3) { out = 22 } else { out = 23 } } else { out = 30 }`,
  1736. nil, 30)
  1737. expectRun(t, `if (1 > 2) { out = 10 } else if (1 == 2) { out = 20 } else { if (1 == 2) { out = 31 } else if (2 == 3) { out = 32 } else { out = 33 } }`,
  1738. nil, 33)
  1739. expectRun(t, `if a:=0; a<1 { out = 10 }`, nil, 10)
  1740. expectRun(t, `a:=0; if a++; a==1 { out = 10 }`, nil, 10)
  1741. expectRun(t, `
  1742. func() {
  1743. a := 1
  1744. if a++; a > 1 {
  1745. out = a
  1746. }
  1747. }()
  1748. `, nil, 2)
  1749. expectRun(t, `
  1750. func() {
  1751. a := 1
  1752. if a++; a == 1 {
  1753. out = 10
  1754. } else {
  1755. out = 20
  1756. }
  1757. }()
  1758. `, nil, 20)
  1759. expectRun(t, `
  1760. func() {
  1761. a := 1
  1762. func() {
  1763. if a++; a > 1 {
  1764. a++
  1765. }
  1766. }()
  1767. out = a
  1768. }()
  1769. `, nil, 3)
  1770. // expression statement in init (should not leave objects on stack)
  1771. expectRun(t, `a := 1; if a; a { out = a }`, nil, 1)
  1772. expectRun(t, `a := 1; if a + 4; a { out = a }`, nil, 1)
  1773. // dead code elimination
  1774. expectRun(t, `
  1775. out = func() {
  1776. if false { return 1 }
  1777. a := undefined
  1778. a = 2
  1779. if !a {
  1780. b := func() {
  1781. return is_callable(a) ? a(8) : a
  1782. }()
  1783. if is_error(b) {
  1784. return b
  1785. } else if !is_undefined(b) {
  1786. return immutable(b)
  1787. }
  1788. }
  1789. a = 3
  1790. if a {
  1791. b := func() {
  1792. return is_callable(a) ? a(9) : a
  1793. }()
  1794. if is_error(b) {
  1795. return b
  1796. } else if !is_undefined(b) {
  1797. return immutable(b)
  1798. }
  1799. }
  1800. return a
  1801. }()
  1802. `, nil, 3)
  1803. }
  1804. func TestImmutable(t *testing.T) {
  1805. // primitive types are already immutable values
  1806. // immutable expression has no effects.
  1807. expectRun(t, `a := immutable(1); out = a`, nil, 1)
  1808. expectRun(t, `a := 5; b := immutable(a); out = b`, nil, 5)
  1809. expectRun(t, `a := immutable(1); a = 5; out = a`, nil, 5)
  1810. // array
  1811. expectError(t, `a := immutable([1, 2, 3]); a[1] = 5`,
  1812. nil, "not index-assignable")
  1813. expectError(t, `a := immutable(["foo", [1,2,3]]); a[1] = "bar"`,
  1814. nil, "not index-assignable")
  1815. expectRun(t, `a := immutable(["foo", [1,2,3]]); a[1][1] = "bar"; out = a`,
  1816. nil, IARR{"foo", ARR{1, "bar", 3}})
  1817. expectError(t, `a := immutable(["foo", immutable([1,2,3])]); a[1][1] = "bar"`,
  1818. nil, "not index-assignable")
  1819. expectError(t, `a := ["foo", immutable([1,2,3])]; a[1][1] = "bar"`,
  1820. nil, "not index-assignable")
  1821. expectRun(t, `a := immutable([1,2,3]); b := copy(a); b[1] = 5; out = b`,
  1822. nil, ARR{1, 5, 3})
  1823. expectRun(t, `a := immutable([1,2,3]); b := copy(a); b[1] = 5; out = a`,
  1824. nil, IARR{1, 2, 3})
  1825. expectRun(t, `out = immutable([1,2,3]) == [1,2,3]`,
  1826. nil, true)
  1827. expectRun(t, `out = immutable([1,2,3]) == immutable([1,2,3])`,
  1828. nil, true)
  1829. expectRun(t, `out = [1,2,3] == immutable([1,2,3])`,
  1830. nil, true)
  1831. expectRun(t, `out = immutable([1,2,3]) == [1,2]`,
  1832. nil, false)
  1833. expectRun(t, `out = immutable([1,2,3]) == immutable([1,2])`,
  1834. nil, false)
  1835. expectRun(t, `out = [1,2,3] == immutable([1,2])`,
  1836. nil, false)
  1837. expectRun(t, `out = immutable([1, 2, 3, 4])[1]`,
  1838. nil, 2)
  1839. expectRun(t, `out = immutable([1, 2, 3, 4])[1:3]`,
  1840. nil, ARR{2, 3})
  1841. expectRun(t, `a := immutable([1,2,3]); a = 5; out = a`,
  1842. nil, 5)
  1843. expectRun(t, `a := immutable([1, 2, 3]); out = a[5]`,
  1844. nil, tengo.UndefinedValue)
  1845. // map
  1846. expectError(t, `a := immutable({b: 1, c: 2}); a.b = 5`,
  1847. nil, "not index-assignable")
  1848. expectError(t, `a := immutable({b: 1, c: 2}); a["b"] = "bar"`,
  1849. nil, "not index-assignable")
  1850. expectRun(t, `a := immutable({b: 1, c: [1,2,3]}); a.c[1] = "bar"; out = a`,
  1851. nil, IMAP{"b": 1, "c": ARR{1, "bar", 3}})
  1852. expectError(t, `a := immutable({b: 1, c: immutable([1,2,3])}); a.c[1] = "bar"`,
  1853. nil, "not index-assignable")
  1854. expectError(t, `a := {b: 1, c: immutable([1,2,3])}; a.c[1] = "bar"`,
  1855. nil, "not index-assignable")
  1856. expectRun(t, `out = immutable({a:1,b:2}) == {a:1,b:2}`,
  1857. nil, true)
  1858. expectRun(t, `out = immutable({a:1,b:2}) == immutable({a:1,b:2})`,
  1859. nil, true)
  1860. expectRun(t, `out = {a:1,b:2} == immutable({a:1,b:2})`,
  1861. nil, true)
  1862. expectRun(t, `out = immutable({a:1,b:2}) == {a:1,b:3}`,
  1863. nil, false)
  1864. expectRun(t, `out = immutable({a:1,b:2}) == immutable({a:1,b:3})`,
  1865. nil, false)
  1866. expectRun(t, `out = {a:1,b:2} == immutable({a:1,b:3})`,
  1867. nil, false)
  1868. expectRun(t, `out = immutable({a:1,b:2}).b`,
  1869. nil, 2)
  1870. expectRun(t, `out = immutable({a:1,b:2})["b"]`,
  1871. nil, 2)
  1872. expectRun(t, `a := immutable({a:1,b:2}); a = 5; out = 5`,
  1873. nil, 5)
  1874. expectRun(t, `a := immutable({a:1,b:2}); out = a.c`,
  1875. nil, tengo.UndefinedValue)
  1876. expectRun(t, `a := immutable({b: 5, c: "foo"}); out = a.b`,
  1877. nil, 5)
  1878. expectError(t, `a := immutable({b: 5, c: "foo"}); a.b = 10`,
  1879. nil, "not index-assignable")
  1880. }
  1881. func TestIncDec(t *testing.T) {
  1882. expectRun(t, `out = 0; out++`, nil, 1)
  1883. expectRun(t, `out = 0; out--`, nil, -1)
  1884. expectRun(t, `a := 0; a++; out = a`, nil, 1)
  1885. expectRun(t, `a := 0; a++; a--; out = a`, nil, 0)
  1886. // this seems strange but it works because 'a += b' is
  1887. // translated into 'a = a + b' and string type takes other types for + operator.
  1888. expectRun(t, `a := "foo"; a++; out = a`, nil, "foo1")
  1889. expectError(t, `a := "foo"; a--`, nil, "invalid operation")
  1890. expectError(t, `a++`, nil, "unresolved reference") // not declared
  1891. expectError(t, `a--`, nil, "unresolved reference") // not declared
  1892. expectError(t, `4++`, nil, "unresolved reference")
  1893. }
  1894. type StringDict struct {
  1895. tengo.ObjectImpl
  1896. Value map[string]string
  1897. }
  1898. func (o *StringDict) String() string { return "" }
  1899. func (o *StringDict) TypeName() string {
  1900. return "string-dict"
  1901. }
  1902. func (o *StringDict) IndexGet(index tengo.Object) (tengo.Object, error) {
  1903. strIdx, ok := index.(*tengo.String)
  1904. if !ok {
  1905. return nil, tengo.ErrInvalidIndexType
  1906. }
  1907. for k, v := range o.Value {
  1908. if strings.EqualFold(strIdx.Value, k) {
  1909. return &tengo.String{Value: v}, nil
  1910. }
  1911. }
  1912. return tengo.UndefinedValue, nil
  1913. }
  1914. func (o *StringDict) IndexSet(index, value tengo.Object) error {
  1915. strIdx, ok := index.(*tengo.String)
  1916. if !ok {
  1917. return tengo.ErrInvalidIndexType
  1918. }
  1919. strVal, ok := tengo.ToString(value)
  1920. if !ok {
  1921. return tengo.ErrInvalidIndexValueType
  1922. }
  1923. o.Value[strings.ToLower(strIdx.Value)] = strVal
  1924. return nil
  1925. }
  1926. type StringCircle struct {
  1927. tengo.ObjectImpl
  1928. Value []string
  1929. }
  1930. func (o *StringCircle) TypeName() string {
  1931. return "string-circle"
  1932. }
  1933. func (o *StringCircle) String() string {
  1934. return ""
  1935. }
  1936. func (o *StringCircle) IndexGet(index tengo.Object) (tengo.Object, error) {
  1937. intIdx, ok := index.(*tengo.Int)
  1938. if !ok {
  1939. return nil, tengo.ErrInvalidIndexType
  1940. }
  1941. r := int(intIdx.Value) % len(o.Value)
  1942. if r < 0 {
  1943. r = len(o.Value) + r
  1944. }
  1945. return &tengo.String{Value: o.Value[r]}, nil
  1946. }
  1947. func (o *StringCircle) IndexSet(index, value tengo.Object) error {
  1948. intIdx, ok := index.(*tengo.Int)
  1949. if !ok {
  1950. return tengo.ErrInvalidIndexType
  1951. }
  1952. r := int(intIdx.Value) % len(o.Value)
  1953. if r < 0 {
  1954. r = len(o.Value) + r
  1955. }
  1956. strVal, ok := tengo.ToString(value)
  1957. if !ok {
  1958. return tengo.ErrInvalidIndexValueType
  1959. }
  1960. o.Value[r] = strVal
  1961. return nil
  1962. }
  1963. type StringArray struct {
  1964. tengo.ObjectImpl
  1965. Value []string
  1966. }
  1967. func (o *StringArray) String() string {
  1968. return strings.Join(o.Value, ", ")
  1969. }
  1970. func (o *StringArray) BinaryOp(
  1971. op token.Token,
  1972. rhs tengo.Object,
  1973. ) (tengo.Object, error) {
  1974. if rhs, ok := rhs.(*StringArray); ok {
  1975. switch op {
  1976. case token.Add:
  1977. if len(rhs.Value) == 0 {
  1978. return o, nil
  1979. }
  1980. return &StringArray{Value: append(o.Value, rhs.Value...)}, nil
  1981. }
  1982. }
  1983. return nil, tengo.ErrInvalidOperator
  1984. }
  1985. func (o *StringArray) IsFalsy() bool {
  1986. return len(o.Value) == 0
  1987. }
  1988. func (o *StringArray) Equals(x tengo.Object) bool {
  1989. if x, ok := x.(*StringArray); ok {
  1990. if len(o.Value) != len(x.Value) {
  1991. return false
  1992. }
  1993. for i, v := range o.Value {
  1994. if v != x.Value[i] {
  1995. return false
  1996. }
  1997. }
  1998. return true
  1999. }
  2000. return false
  2001. }
  2002. func (o *StringArray) Copy() tengo.Object {
  2003. return &StringArray{
  2004. Value: append([]string{}, o.Value...),
  2005. }
  2006. }
  2007. func (o *StringArray) TypeName() string {
  2008. return "string-array"
  2009. }
  2010. func (o *StringArray) IndexGet(index tengo.Object) (tengo.Object, error) {
  2011. intIdx, ok := index.(*tengo.Int)
  2012. if ok {
  2013. if intIdx.Value >= 0 && intIdx.Value < int64(len(o.Value)) {
  2014. return &tengo.String{Value: o.Value[intIdx.Value]}, nil
  2015. }
  2016. return nil, tengo.ErrIndexOutOfBounds
  2017. }
  2018. strIdx, ok := index.(*tengo.String)
  2019. if ok {
  2020. for vidx, str := range o.Value {
  2021. if strIdx.Value == str {
  2022. return &tengo.Int{Value: int64(vidx)}, nil
  2023. }
  2024. }
  2025. return tengo.UndefinedValue, nil
  2026. }
  2027. return nil, tengo.ErrInvalidIndexType
  2028. }
  2029. func (o *StringArray) IndexSet(index, value tengo.Object) error {
  2030. strVal, ok := tengo.ToString(value)
  2031. if !ok {
  2032. return tengo.ErrInvalidIndexValueType
  2033. }
  2034. intIdx, ok := index.(*tengo.Int)
  2035. if ok {
  2036. if intIdx.Value >= 0 && intIdx.Value < int64(len(o.Value)) {
  2037. o.Value[intIdx.Value] = strVal
  2038. return nil
  2039. }
  2040. return tengo.ErrIndexOutOfBounds
  2041. }
  2042. return tengo.ErrInvalidIndexType
  2043. }
  2044. func (o *StringArray) Call(
  2045. args ...tengo.Object,
  2046. ) (ret tengo.Object, err error) {
  2047. if len(args) != 1 {
  2048. return nil, tengo.ErrWrongNumArguments
  2049. }
  2050. s1, ok := tengo.ToString(args[0])
  2051. if !ok {
  2052. return nil, tengo.ErrInvalidArgumentType{
  2053. Name: "first",
  2054. Expected: "string(compatible)",
  2055. Found: args[0].TypeName(),
  2056. }
  2057. }
  2058. for i, v := range o.Value {
  2059. if v == s1 {
  2060. return &tengo.Int{Value: int64(i)}, nil
  2061. }
  2062. }
  2063. return tengo.UndefinedValue, nil
  2064. }
  2065. func (o *StringArray) CanCall() bool {
  2066. return true
  2067. }
  2068. func TestIndexable(t *testing.T) {
  2069. dict := func() *StringDict {
  2070. return &StringDict{Value: map[string]string{"a": "foo", "b": "bar"}}
  2071. }
  2072. expectRun(t, `out = dict["a"]`,
  2073. Opts().Symbol("dict", dict()).Skip2ndPass(), "foo")
  2074. expectRun(t, `out = dict["B"]`,
  2075. Opts().Symbol("dict", dict()).Skip2ndPass(), "bar")
  2076. expectRun(t, `out = dict["x"]`,
  2077. Opts().Symbol("dict", dict()).Skip2ndPass(), tengo.UndefinedValue)
  2078. expectError(t, `dict[0]`,
  2079. Opts().Symbol("dict", dict()).Skip2ndPass(), "invalid index type")
  2080. strCir := func() *StringCircle {
  2081. return &StringCircle{Value: []string{"one", "two", "three"}}
  2082. }
  2083. expectRun(t, `out = cir[0]`,
  2084. Opts().Symbol("cir", strCir()).Skip2ndPass(), "one")
  2085. expectRun(t, `out = cir[1]`,
  2086. Opts().Symbol("cir", strCir()).Skip2ndPass(), "two")
  2087. expectRun(t, `out = cir[-1]`,
  2088. Opts().Symbol("cir", strCir()).Skip2ndPass(), "three")
  2089. expectRun(t, `out = cir[-2]`,
  2090. Opts().Symbol("cir", strCir()).Skip2ndPass(), "two")
  2091. expectRun(t, `out = cir[3]`,
  2092. Opts().Symbol("cir", strCir()).Skip2ndPass(), "one")
  2093. expectError(t, `cir["a"]`,
  2094. Opts().Symbol("cir", strCir()).Skip2ndPass(), "invalid index type")
  2095. strArr := func() *StringArray {
  2096. return &StringArray{Value: []string{"one", "two", "three"}}
  2097. }
  2098. expectRun(t, `out = arr["one"]`,
  2099. Opts().Symbol("arr", strArr()).Skip2ndPass(), 0)
  2100. expectRun(t, `out = arr["three"]`,
  2101. Opts().Symbol("arr", strArr()).Skip2ndPass(), 2)
  2102. expectRun(t, `out = arr["four"]`,
  2103. Opts().Symbol("arr", strArr()).Skip2ndPass(), tengo.UndefinedValue)
  2104. expectRun(t, `out = arr[0]`,
  2105. Opts().Symbol("arr", strArr()).Skip2ndPass(), "one")
  2106. expectRun(t, `out = arr[1]`,
  2107. Opts().Symbol("arr", strArr()).Skip2ndPass(), "two")
  2108. expectError(t, `arr[-1]`,
  2109. Opts().Symbol("arr", strArr()).Skip2ndPass(), "index out of bounds")
  2110. }
  2111. func TestIndexAssignable(t *testing.T) {
  2112. dict := func() *StringDict {
  2113. return &StringDict{Value: map[string]string{"a": "foo", "b": "bar"}}
  2114. }
  2115. expectRun(t, `dict["a"] = "1984"; out = dict["a"]`,
  2116. Opts().Symbol("dict", dict()).Skip2ndPass(), "1984")
  2117. expectRun(t, `dict["c"] = "1984"; out = dict["c"]`,
  2118. Opts().Symbol("dict", dict()).Skip2ndPass(), "1984")
  2119. expectRun(t, `dict["c"] = 1984; out = dict["C"]`,
  2120. Opts().Symbol("dict", dict()).Skip2ndPass(), "1984")
  2121. expectError(t, `dict[0] = "1984"`,
  2122. Opts().Symbol("dict", dict()).Skip2ndPass(), "invalid index type")
  2123. strCir := func() *StringCircle {
  2124. return &StringCircle{Value: []string{"one", "two", "three"}}
  2125. }
  2126. expectRun(t, `cir[0] = "ONE"; out = cir[0]`,
  2127. Opts().Symbol("cir", strCir()).Skip2ndPass(), "ONE")
  2128. expectRun(t, `cir[1] = "TWO"; out = cir[1]`,
  2129. Opts().Symbol("cir", strCir()).Skip2ndPass(), "TWO")
  2130. expectRun(t, `cir[-1] = "THREE"; out = cir[2]`,
  2131. Opts().Symbol("cir", strCir()).Skip2ndPass(), "THREE")
  2132. expectRun(t, `cir[0] = "ONE"; out = cir[3]`,
  2133. Opts().Symbol("cir", strCir()).Skip2ndPass(), "ONE")
  2134. expectError(t, `cir["a"] = "ONE"`,
  2135. Opts().Symbol("cir", strCir()).Skip2ndPass(), "invalid index type")
  2136. strArr := func() *StringArray {
  2137. return &StringArray{Value: []string{"one", "two", "three"}}
  2138. }
  2139. expectRun(t, `arr[0] = "ONE"; out = arr[0]`,
  2140. Opts().Symbol("arr", strArr()).Skip2ndPass(), "ONE")
  2141. expectRun(t, `arr[1] = "TWO"; out = arr[1]`,
  2142. Opts().Symbol("arr", strArr()).Skip2ndPass(), "TWO")
  2143. expectError(t, `arr["one"] = "ONE"`,
  2144. Opts().Symbol("arr", strArr()).Skip2ndPass(), "invalid index type")
  2145. }
  2146. func TestInteger(t *testing.T) {
  2147. expectRun(t, `out = 5`, nil, 5)
  2148. expectRun(t, `out = 10`, nil, 10)
  2149. expectRun(t, `out = -5`, nil, -5)
  2150. expectRun(t, `out = -10`, nil, -10)
  2151. expectRun(t, `out = 5 + 5 + 5 + 5 - 10`, nil, 10)
  2152. expectRun(t, `out = 2 * 2 * 2 * 2 * 2`, nil, 32)
  2153. expectRun(t, `out = -50 + 100 + -50`, nil, 0)
  2154. expectRun(t, `out = 5 * 2 + 10`, nil, 20)
  2155. expectRun(t, `out = 5 + 2 * 10`, nil, 25)
  2156. expectRun(t, `out = 20 + 2 * -10`, nil, 0)
  2157. expectRun(t, `out = 50 / 2 * 2 + 10`, nil, 60)
  2158. expectRun(t, `out = 2 * (5 + 10)`, nil, 30)
  2159. expectRun(t, `out = 3 * 3 * 3 + 10`, nil, 37)
  2160. expectRun(t, `out = 3 * (3 * 3) + 10`, nil, 37)
  2161. expectRun(t, `out = (5 + 10 * 2 + 15 /3) * 2 + -10`, nil, 50)
  2162. expectRun(t, `out = 5 % 3`, nil, 2)
  2163. expectRun(t, `out = 5 % 3 + 4`, nil, 6)
  2164. expectRun(t, `out = +5`, nil, 5)
  2165. expectRun(t, `out = +5 + -5`, nil, 0)
  2166. expectRun(t, `out = 9 + '0'`, nil, '9')
  2167. expectRun(t, `out = '9' - 5`, nil, '4')
  2168. }
  2169. type StringArrayIterator struct {
  2170. tengo.ObjectImpl
  2171. strArr *StringArray
  2172. idx int
  2173. }
  2174. func (i *StringArrayIterator) TypeName() string {
  2175. return "string-array-iterator"
  2176. }
  2177. func (i *StringArrayIterator) String() string {
  2178. return ""
  2179. }
  2180. func (i *StringArrayIterator) Next() bool {
  2181. i.idx++
  2182. return i.idx <= len(i.strArr.Value)
  2183. }
  2184. func (i *StringArrayIterator) Key() tengo.Object {
  2185. return &tengo.Int{Value: int64(i.idx - 1)}
  2186. }
  2187. func (i *StringArrayIterator) Value() tengo.Object {
  2188. return &tengo.String{Value: i.strArr.Value[i.idx-1]}
  2189. }
  2190. func (o *StringArray) Iterate() tengo.Iterator {
  2191. return &StringArrayIterator{
  2192. strArr: o,
  2193. }
  2194. }
  2195. func (o *StringArray) CanIterate() bool {
  2196. return true
  2197. }
  2198. func TestIterable(t *testing.T) {
  2199. strArr := func() *StringArray {
  2200. return &StringArray{Value: []string{"one", "two", "three"}}
  2201. }
  2202. expectRun(t, `for i, s in arr { out += i }`,
  2203. Opts().Symbol("arr", strArr()).Skip2ndPass(), 3)
  2204. expectRun(t, `for i, s in arr { out += s }`,
  2205. Opts().Symbol("arr", strArr()).Skip2ndPass(), "onetwothree")
  2206. expectRun(t, `for i, s in arr { out += s + i }`,
  2207. Opts().Symbol("arr", strArr()).Skip2ndPass(), "one0two1three2")
  2208. }
  2209. func TestLogical(t *testing.T) {
  2210. expectRun(t, `out = true && true`, nil, true)
  2211. expectRun(t, `out = true && false`, nil, false)
  2212. expectRun(t, `out = false && true`, nil, false)
  2213. expectRun(t, `out = false && false`, nil, false)
  2214. expectRun(t, `out = !true && true`, nil, false)
  2215. expectRun(t, `out = !true && false`, nil, false)
  2216. expectRun(t, `out = !false && true`, nil, true)
  2217. expectRun(t, `out = !false && false`, nil, false)
  2218. expectRun(t, `out = true || true`, nil, true)
  2219. expectRun(t, `out = true || false`, nil, true)
  2220. expectRun(t, `out = false || true`, nil, true)
  2221. expectRun(t, `out = false || false`, nil, false)
  2222. expectRun(t, `out = !true || true`, nil, true)
  2223. expectRun(t, `out = !true || false`, nil, false)
  2224. expectRun(t, `out = !false || true`, nil, true)
  2225. expectRun(t, `out = !false || false`, nil, true)
  2226. expectRun(t, `out = 1 && 2`, nil, 2)
  2227. expectRun(t, `out = 1 || 2`, nil, 1)
  2228. expectRun(t, `out = 1 && 0`, nil, 0)
  2229. expectRun(t, `out = 1 || 0`, nil, 1)
  2230. expectRun(t, `out = 1 && (0 || 2)`, nil, 2)
  2231. expectRun(t, `out = 0 || (0 || 2)`, nil, 2)
  2232. expectRun(t, `out = 0 || (0 && 2)`, nil, 0)
  2233. expectRun(t, `out = 0 || (2 && 0)`, nil, 0)
  2234. expectRun(t, `t:=func() {out = 3; return true}; f:=func() {out = 7; return false}; t() && f()`,
  2235. nil, 7)
  2236. expectRun(t, `t:=func() {out = 3; return true}; f:=func() {out = 7; return false}; f() && t()`,
  2237. nil, 7)
  2238. expectRun(t, `t:=func() {out = 3; return true}; f:=func() {out = 7; return false}; f() || t()`,
  2239. nil, 3)
  2240. expectRun(t, `t:=func() {out = 3; return true}; f:=func() {out = 7; return false}; t() || f()`,
  2241. nil, 3)
  2242. expectRun(t, `t:=func() {out = 3; return true}; f:=func() {out = 7; return false}; !t() && f()`,
  2243. nil, 3)
  2244. expectRun(t, `t:=func() {out = 3; return true}; f:=func() {out = 7; return false}; !f() && t()`,
  2245. nil, 3)
  2246. expectRun(t, `t:=func() {out = 3; return true}; f:=func() {out = 7; return false}; !f() || t()`,
  2247. nil, 7)
  2248. expectRun(t, `t:=func() {out = 3; return true}; f:=func() {out = 7; return false}; !t() || f()`,
  2249. nil, 7)
  2250. }
  2251. func TestMap(t *testing.T) {
  2252. expectRun(t, `
  2253. out = {
  2254. one: 10 - 9,
  2255. two: 1 + 1,
  2256. three: 6 / 2
  2257. }`, nil, MAP{
  2258. "one": 1,
  2259. "two": 2,
  2260. "three": 3,
  2261. })
  2262. expectRun(t, `
  2263. out = {
  2264. "one": 10 - 9,
  2265. "two": 1 + 1,
  2266. "three": 6 / 2
  2267. }`, nil, MAP{
  2268. "one": 1,
  2269. "two": 2,
  2270. "three": 3,
  2271. })
  2272. expectRun(t, `out = {foo: 5}["foo"]`, nil, 5)
  2273. expectRun(t, `out = {foo: 5}["bar"]`, nil, tengo.UndefinedValue)
  2274. expectRun(t, `key := "foo"; out = {foo: 5}[key]`, nil, 5)
  2275. expectRun(t, `out = {}["foo"]`, nil, tengo.UndefinedValue)
  2276. expectRun(t, `
  2277. m := {
  2278. foo: func(x) {
  2279. return x * 2
  2280. }
  2281. }
  2282. out = m["foo"](2) + m["foo"](3)
  2283. `, nil, 10)
  2284. // map assignment is copy-by-reference
  2285. expectRun(t, `m1 := {k1: 1, k2: "foo"}; m2 := m1; m1.k1 = 5; out = m2.k1`,
  2286. nil, 5)
  2287. expectRun(t, `m1 := {k1: 1, k2: "foo"}; m2 := m1; m2.k1 = 3; out = m1.k1`,
  2288. nil, 3)
  2289. expectRun(t, `func() { m1 := {k1: 1, k2: "foo"}; m2 := m1; m1.k1 = 5; out = m2.k1 }()`,
  2290. nil, 5)
  2291. expectRun(t, `func() { m1 := {k1: 1, k2: "foo"}; m2 := m1; m2.k1 = 3; out = m1.k1 }()`,
  2292. nil, 3)
  2293. }
  2294. func TestBuiltin(t *testing.T) {
  2295. m := Opts().Module("math",
  2296. &tengo.BuiltinModule{
  2297. Attrs: map[string]tengo.Object{
  2298. "abs": &tengo.UserFunction{
  2299. Name: "abs",
  2300. Value: func(a ...tengo.Object) (tengo.Object, error) {
  2301. v, _ := tengo.ToFloat64(a[0])
  2302. return &tengo.Float{Value: math.Abs(v)}, nil
  2303. },
  2304. },
  2305. },
  2306. })
  2307. // builtin
  2308. expectRun(t, `math := import("math"); out = math.abs(1)`, m, 1.0)
  2309. expectRun(t, `math := import("math"); out = math.abs(-1)`, m, 1.0)
  2310. expectRun(t, `math := import("math"); out = math.abs(1.0)`, m, 1.0)
  2311. expectRun(t, `math := import("math"); out = math.abs(-1.0)`, m, 1.0)
  2312. }
  2313. func TestUserModules(t *testing.T) {
  2314. // export none
  2315. expectRun(t, `out = import("mod1")`,
  2316. Opts().Module("mod1", `fn := func() { return 5.0 }; a := 2`),
  2317. tengo.UndefinedValue)
  2318. // export values
  2319. expectRun(t, `out = import("mod1")`,
  2320. Opts().Module("mod1", `export 5`), 5)
  2321. expectRun(t, `out = import("mod1")`,
  2322. Opts().Module("mod1", `export "foo"`), "foo")
  2323. // export compound types
  2324. expectRun(t, `out = import("mod1")`,
  2325. Opts().Module("mod1", `export [1, 2, 3]`), IARR{1, 2, 3})
  2326. expectRun(t, `out = import("mod1")`,
  2327. Opts().Module("mod1", `export {a: 1, b: 2}`), IMAP{"a": 1, "b": 2})
  2328. // export value is immutable
  2329. expectError(t, `m1 := import("mod1"); m1.a = 5`,
  2330. Opts().Module("mod1", `export {a: 1, b: 2}`), "not index-assignable")
  2331. expectError(t, `m1 := import("mod1"); m1[1] = 5`,
  2332. Opts().Module("mod1", `export [1, 2, 3]`), "not index-assignable")
  2333. // code after export statement will not be executed
  2334. expectRun(t, `out = import("mod1")`,
  2335. Opts().Module("mod1", `a := 10; export a; a = 20`), 10)
  2336. expectRun(t, `out = import("mod1")`,
  2337. Opts().Module("mod1", `a := 10; export a; a = 20; export a`), 10)
  2338. // export function
  2339. expectRun(t, `out = import("mod1")()`,
  2340. Opts().Module("mod1", `export func() { return 5.0 }`), 5.0)
  2341. // export function that reads module-global variable
  2342. expectRun(t, `out = import("mod1")()`,
  2343. Opts().Module("mod1", `a := 1.5; export func() { return a + 5.0 }`), 6.5)
  2344. // export function that read local variable
  2345. expectRun(t, `out = import("mod1")()`,
  2346. Opts().Module("mod1", `export func() { a := 1.5; return a + 5.0 }`), 6.5)
  2347. // export function that read free variables
  2348. expectRun(t, `out = import("mod1")()`,
  2349. Opts().Module("mod1", `export func() { a := 1.5; return func() { return a + 5.0 }() }`), 6.5)
  2350. // recursive function in module
  2351. expectRun(t, `out = import("mod1")`,
  2352. Opts().Module(
  2353. "mod1", `
  2354. a := func(x) {
  2355. return x == 0 ? 0 : x + a(x-1)
  2356. }
  2357. export a(5)
  2358. `), 15)
  2359. expectRun(t, `out = import("mod1")`,
  2360. Opts().Module(
  2361. "mod1", `
  2362. export func() {
  2363. a := func(x) {
  2364. return x == 0 ? 0 : x + a(x-1)
  2365. }
  2366. return a(5)
  2367. }()
  2368. `), 15)
  2369. // (main) -> mod1 -> mod2
  2370. expectRun(t, `out = import("mod1")()`,
  2371. Opts().Module("mod1", `export import("mod2")`).
  2372. Module("mod2", `export func() { return 5.0 }`),
  2373. 5.0)
  2374. // (main) -> mod1 -> mod2
  2375. // -> mod2
  2376. expectRun(t, `import("mod1"); out = import("mod2")()`,
  2377. Opts().Module("mod1", `export import("mod2")`).
  2378. Module("mod2", `export func() { return 5.0 }`),
  2379. 5.0)
  2380. // (main) -> mod1 -> mod2 -> mod3
  2381. // -> mod2 -> mod3
  2382. expectRun(t, `import("mod1"); out = import("mod2")()`,
  2383. Opts().Module("mod1", `export import("mod2")`).
  2384. Module("mod2", `export import("mod3")`).
  2385. Module("mod3", `export func() { return 5.0 }`),
  2386. 5.0)
  2387. // cyclic imports
  2388. // (main) -> mod1 -> mod2 -> mod1
  2389. expectError(t, `import("mod1")`,
  2390. Opts().Module("mod1", `import("mod2")`).
  2391. Module("mod2", `import("mod1")`),
  2392. "Compile Error: cyclic module import: mod1\n\tat mod2:1:1")
  2393. // (main) -> mod1 -> mod2 -> mod3 -> mod1
  2394. expectError(t, `import("mod1")`,
  2395. Opts().Module("mod1", `import("mod2")`).
  2396. Module("mod2", `import("mod3")`).
  2397. Module("mod3", `import("mod1")`),
  2398. "Compile Error: cyclic module import: mod1\n\tat mod3:1:1")
  2399. // (main) -> mod1 -> mod2 -> mod3 -> mod2
  2400. expectError(t, `import("mod1")`,
  2401. Opts().Module("mod1", `import("mod2")`).
  2402. Module("mod2", `import("mod3")`).
  2403. Module("mod3", `import("mod2")`),
  2404. "Compile Error: cyclic module import: mod2\n\tat mod3:1:1")
  2405. // unknown modules
  2406. expectError(t, `import("mod0")`,
  2407. Opts().Module("mod1", `a := 5`), "module 'mod0' not found")
  2408. expectError(t, `import("mod1")`,
  2409. Opts().Module("mod1", `import("mod2")`), "module 'mod2' not found")
  2410. // module is immutable but its variables is not necessarily immutable.
  2411. expectRun(t, `m1 := import("mod1"); m1.a.b = 5; out = m1.a.b`,
  2412. Opts().Module("mod1", `export {a: {b: 3}}`),
  2413. 5)
  2414. // make sure module has same builtin functions
  2415. expectRun(t, `out = import("mod1")`,
  2416. Opts().Module("mod1", `export func() { return type_name(0) }()`),
  2417. "int")
  2418. // 'export' statement is ignored outside module
  2419. expectRun(t, `a := 5; export func() { a = 10 }(); out = a`,
  2420. Opts().Skip2ndPass(), 5)
  2421. // 'export' must be in the top-level
  2422. expectError(t, `import("mod1")`,
  2423. Opts().Module("mod1", `func() { export 5 }()`),
  2424. "Compile Error: export not allowed inside function\n\tat mod1:1:10")
  2425. expectError(t, `import("mod1")`,
  2426. Opts().Module("mod1", `func() { func() { export 5 }() }()`),
  2427. "Compile Error: export not allowed inside function\n\tat mod1:1:19")
  2428. // module cannot access outer scope
  2429. expectError(t, `a := 5; import("mod1")`,
  2430. Opts().Module("mod1", `export a`),
  2431. "Compile Error: unresolved reference 'a'\n\tat mod1:1:8")
  2432. // runtime error within modules
  2433. expectError(t, `
  2434. a := 1;
  2435. b := import("mod1");
  2436. b(a)`,
  2437. Opts().Module("mod1", `
  2438. export func(a) {
  2439. a()
  2440. }
  2441. `), "Runtime Error: not callable: int\n\tat mod1:3:4\n\tat test:4:1")
  2442. // module skipping export
  2443. expectRun(t, `out = import("mod0")`,
  2444. Opts().Module("mod0", ``), tengo.UndefinedValue)
  2445. expectRun(t, `out = import("mod0")`,
  2446. Opts().Module("mod0", `if 1 { export true }`), true)
  2447. expectRun(t, `out = import("mod0")`,
  2448. Opts().Module("mod0", `if 0 { export true }`),
  2449. tengo.UndefinedValue)
  2450. expectRun(t, `out = import("mod0")`,
  2451. Opts().Module("mod0", `if 1 { } else { export true }`),
  2452. tengo.UndefinedValue)
  2453. expectRun(t, `out = import("mod0")`,
  2454. Opts().Module("mod0", `for v:=0;;v++ { if v == 3 { export true } }`),
  2455. true)
  2456. expectRun(t, `out = import("mod0")`,
  2457. Opts().Module("mod0", `for v:=0;;v++ { if v == 3 { break } }`),
  2458. tengo.UndefinedValue)
  2459. // duplicate compiled functions
  2460. // NOTE: module "mod" has a function with some local variable, and it's
  2461. // imported twice by the main script. That causes the same CompiledFunction
  2462. // put in constants twice and the Bytecode optimization (removing duplicate
  2463. // constants) should still work correctly.
  2464. expectRun(t, `
  2465. m1 := import("mod")
  2466. m2 := import("mod")
  2467. out = m1.x
  2468. `,
  2469. Opts().Module("mod", `
  2470. f1 := func(a, b) {
  2471. c := a + b + 1
  2472. return a + b + 1
  2473. }
  2474. export { x: 1 }
  2475. `),
  2476. 1)
  2477. }
  2478. func TestModuleBlockScopes(t *testing.T) {
  2479. m := Opts().Module("rand",
  2480. &tengo.BuiltinModule{
  2481. Attrs: map[string]tengo.Object{
  2482. "intn": &tengo.UserFunction{
  2483. Name: "abs",
  2484. Value: func(a ...tengo.Object) (tengo.Object, error) {
  2485. v, _ := tengo.ToInt64(a[0])
  2486. return &tengo.Int{Value: rand.Int63n(v)}, nil
  2487. },
  2488. },
  2489. },
  2490. })
  2491. // block scopes in module
  2492. expectRun(t, `out = import("mod1")()`, m.Module(
  2493. "mod1", `
  2494. rand := import("rand")
  2495. foo := func() { return 1 }
  2496. export func() {
  2497. rand.intn(3)
  2498. return foo()
  2499. }`), 1)
  2500. expectRun(t, `out = import("mod1")()`, m.Module(
  2501. "mod1", `
  2502. rand := import("rand")
  2503. foo := func() { return 1 }
  2504. export func() {
  2505. rand.intn(3)
  2506. if foo() {}
  2507. return 10
  2508. }
  2509. `), 10)
  2510. expectRun(t, `out = import("mod1")()`, m.Module(
  2511. "mod1", `
  2512. rand := import("rand")
  2513. foo := func() { return 1 }
  2514. export func() {
  2515. rand.intn(3)
  2516. if true { foo() }
  2517. return 10
  2518. }
  2519. `), 10)
  2520. }
  2521. func TestBangOperator(t *testing.T) {
  2522. expectRun(t, `out = !true`, nil, false)
  2523. expectRun(t, `out = !false`, nil, true)
  2524. expectRun(t, `out = !0`, nil, true)
  2525. expectRun(t, `out = !5`, nil, false)
  2526. expectRun(t, `out = !!true`, nil, true)
  2527. expectRun(t, `out = !!false`, nil, false)
  2528. expectRun(t, `out = !!5`, nil, true)
  2529. }
  2530. func TestObjectsLimit(t *testing.T) {
  2531. testAllocsLimit(t, `5`, 0)
  2532. testAllocsLimit(t, `5 + 5`, 1)
  2533. testAllocsLimit(t, `a := [1, 2, 3]`, 1)
  2534. testAllocsLimit(t, `a := 1; b := 2; c := 3; d := [a, b, c]`, 1)
  2535. testAllocsLimit(t, `a := {foo: 1, bar: 2}`, 1)
  2536. testAllocsLimit(t, `a := 1; b := 2; c := {foo: a, bar: b}`, 1)
  2537. testAllocsLimit(t, `
  2538. f := func() {
  2539. return 5 + 5
  2540. }
  2541. a := f() + 5
  2542. `, 2)
  2543. testAllocsLimit(t, `
  2544. f := func() {
  2545. return 5 + 5
  2546. }
  2547. a := f()
  2548. `, 1)
  2549. testAllocsLimit(t, `
  2550. a := []
  2551. f := func() {
  2552. a = append(a, 5)
  2553. }
  2554. f()
  2555. f()
  2556. f()
  2557. `, 4)
  2558. }
  2559. func testAllocsLimit(t *testing.T, src string, limit int64) {
  2560. expectRun(t, src,
  2561. Opts().Skip2ndPass(), tengo.UndefinedValue) // no limit
  2562. expectRun(t, src,
  2563. Opts().MaxAllocs(limit).Skip2ndPass(), tengo.UndefinedValue)
  2564. expectRun(t, src,
  2565. Opts().MaxAllocs(limit+1).Skip2ndPass(), tengo.UndefinedValue)
  2566. if limit > 1 {
  2567. expectError(t, src,
  2568. Opts().MaxAllocs(limit-1).Skip2ndPass(),
  2569. "allocation limit exceeded")
  2570. }
  2571. if limit > 2 {
  2572. expectError(t, src,
  2573. Opts().MaxAllocs(limit-2).Skip2ndPass(),
  2574. "allocation limit exceeded")
  2575. }
  2576. }
  2577. func TestReturn(t *testing.T) {
  2578. expectRun(t, `out = func() { return 10; }()`, nil, 10)
  2579. expectRun(t, `out = func() { return 10; return 9; }()`, nil, 10)
  2580. expectRun(t, `out = func() { return 2 * 5; return 9 }()`, nil, 10)
  2581. expectRun(t, `out = func() { 9; return 2 * 5; return 9 }()`, nil, 10)
  2582. expectRun(t, `
  2583. out = func() {
  2584. if (10 > 1) {
  2585. if (10 > 1) {
  2586. return 10;
  2587. }
  2588. return 1;
  2589. }
  2590. }()`, nil, 10)
  2591. expectRun(t, `f1 := func() { return 2 * 5; }; out = f1()`, nil, 10)
  2592. }
  2593. func TestVMScopes(t *testing.T) {
  2594. // shadowed global variable
  2595. expectRun(t, `
  2596. c := 5
  2597. if a := 3; a {
  2598. c := 6
  2599. } else {
  2600. c := 7
  2601. }
  2602. out = c
  2603. `, nil, 5)
  2604. // shadowed local variable
  2605. expectRun(t, `
  2606. func() {
  2607. c := 5
  2608. if a := 3; a {
  2609. c := 6
  2610. } else {
  2611. c := 7
  2612. }
  2613. out = c
  2614. }()
  2615. `, nil, 5)
  2616. // 'b' is declared in 2 separate blocks
  2617. expectRun(t, `
  2618. c := 5
  2619. if a := 3; a {
  2620. b := 8
  2621. c = b
  2622. } else {
  2623. b := 9
  2624. c = b
  2625. }
  2626. out = c
  2627. `, nil, 8)
  2628. // shadowing inside for statement
  2629. expectRun(t, `
  2630. a := 4
  2631. b := 5
  2632. for i:=0;i<3;i++ {
  2633. b := 6
  2634. for j:=0;j<2;j++ {
  2635. b := 7
  2636. a = i*j
  2637. }
  2638. }
  2639. out = a`, nil, 2)
  2640. // shadowing variable declared in init statement
  2641. expectRun(t, `
  2642. if a := 5; a {
  2643. a := 6
  2644. out = a
  2645. }`, nil, 6)
  2646. expectRun(t, `
  2647. a := 4
  2648. if a := 5; a {
  2649. a := 6
  2650. out = a
  2651. }`, nil, 6)
  2652. expectRun(t, `
  2653. a := 4
  2654. if a := 0; a {
  2655. a := 6
  2656. out = a
  2657. } else {
  2658. a := 7
  2659. out = a
  2660. }`, nil, 7)
  2661. expectRun(t, `
  2662. a := 4
  2663. if a := 0; a {
  2664. out = a
  2665. } else {
  2666. out = a
  2667. }`, nil, 0)
  2668. // shadowing function level
  2669. expectRun(t, `
  2670. a := 5
  2671. func() {
  2672. a := 6
  2673. a = 7
  2674. }()
  2675. out = a
  2676. `, nil, 5)
  2677. expectRun(t, `
  2678. a := 5
  2679. func() {
  2680. if a := 7; true {
  2681. a = 8
  2682. }
  2683. }()
  2684. out = a
  2685. `, nil, 5)
  2686. }
  2687. func TestSelector(t *testing.T) {
  2688. expectRun(t, `a := {k1: 5, k2: "foo"}; out = a.k1`,
  2689. nil, 5)
  2690. expectRun(t, `a := {k1: 5, k2: "foo"}; out = a.k2`,
  2691. nil, "foo")
  2692. expectRun(t, `a := {k1: 5, k2: "foo"}; out = a.k3`,
  2693. nil, tengo.UndefinedValue)
  2694. expectRun(t, `
  2695. a := {
  2696. b: {
  2697. c: 4,
  2698. a: false
  2699. },
  2700. c: "foo bar"
  2701. }
  2702. out = a.b.c`, nil, 4)
  2703. expectRun(t, `
  2704. a := {
  2705. b: {
  2706. c: 4,
  2707. a: false
  2708. },
  2709. c: "foo bar"
  2710. }
  2711. b := a.x.c`, nil, tengo.UndefinedValue)
  2712. expectRun(t, `
  2713. a := {
  2714. b: {
  2715. c: 4,
  2716. a: false
  2717. },
  2718. c: "foo bar"
  2719. }
  2720. b := a.x.y`, nil, tengo.UndefinedValue)
  2721. expectRun(t, `a := {b: 1, c: "foo"}; a.b = 2; out = a.b`,
  2722. nil, 2)
  2723. expectRun(t, `a := {b: 1, c: "foo"}; a.c = 2; out = a.c`,
  2724. nil, 2) // type not checked on sub-field
  2725. expectRun(t, `a := {b: {c: 1}}; a.b.c = 2; out = a.b.c`,
  2726. nil, 2)
  2727. expectRun(t, `a := {b: 1}; a.c = 2; out = a`,
  2728. nil, MAP{"b": 1, "c": 2})
  2729. expectRun(t, `a := {b: {c: 1}}; a.b.d = 2; out = a`,
  2730. nil, MAP{"b": MAP{"c": 1, "d": 2}})
  2731. expectRun(t, `func() { a := {b: 1, c: "foo"}; a.b = 2; out = a.b }()`,
  2732. nil, 2)
  2733. expectRun(t, `func() { a := {b: 1, c: "foo"}; a.c = 2; out = a.c }()`,
  2734. nil, 2) // type not checked on sub-field
  2735. expectRun(t, `func() { a := {b: {c: 1}}; a.b.c = 2; out = a.b.c }()`,
  2736. nil, 2)
  2737. expectRun(t, `func() { a := {b: 1}; a.c = 2; out = a }()`,
  2738. nil, MAP{"b": 1, "c": 2})
  2739. expectRun(t, `func() { a := {b: {c: 1}}; a.b.d = 2; out = a }()`,
  2740. nil, MAP{"b": MAP{"c": 1, "d": 2}})
  2741. expectRun(t, `func() { a := {b: 1, c: "foo"}; func() { a.b = 2 }(); out = a.b }()`,
  2742. nil, 2)
  2743. expectRun(t, `func() { a := {b: 1, c: "foo"}; func() { a.c = 2 }(); out = a.c }()`,
  2744. nil, 2) // type not checked on sub-field
  2745. expectRun(t, `func() { a := {b: {c: 1}}; func() { a.b.c = 2 }(); out = a.b.c }()`,
  2746. nil, 2)
  2747. expectRun(t, `func() { a := {b: 1}; func() { a.c = 2 }(); out = a }()`,
  2748. nil, MAP{"b": 1, "c": 2})
  2749. expectRun(t, `func() { a := {b: {c: 1}}; func() { a.b.d = 2 }(); out = a }()`,
  2750. nil, MAP{"b": MAP{"c": 1, "d": 2}})
  2751. expectRun(t, `
  2752. a := {
  2753. b: [1, 2, 3],
  2754. c: {
  2755. d: 8,
  2756. e: "foo",
  2757. f: [9, 8]
  2758. }
  2759. }
  2760. out = [a.b[2], a.c.d, a.c.e, a.c.f[1]]
  2761. `, nil, ARR{3, 8, "foo", 8})
  2762. expectRun(t, `
  2763. func() {
  2764. a := [1, 2, 3]
  2765. b := 9
  2766. a[1] = b
  2767. b = 7 // make sure a[1] has a COPY of value of 'b'
  2768. out = a[1]
  2769. }()
  2770. `, nil, 9)
  2771. expectError(t, `a := {b: {c: 1}}; a.d.c = 2`,
  2772. nil, "not index-assignable")
  2773. expectError(t, `a := [1, 2, 3]; a.b = 2`,
  2774. nil, "invalid index type")
  2775. expectError(t, `a := "foo"; a.b = 2`,
  2776. nil, "not index-assignable")
  2777. expectError(t, `func() { a := {b: {c: 1}}; a.d.c = 2 }()`,
  2778. nil, "not index-assignable")
  2779. expectError(t, `func() { a := [1, 2, 3]; a.b = 2 }()`,
  2780. nil, "invalid index type")
  2781. expectError(t, `func() { a := "foo"; a.b = 2 }()`,
  2782. nil, "not index-assignable")
  2783. }
  2784. func TestSourceModules(t *testing.T) {
  2785. testEnumModule(t, `out = enum.key(0, 20)`, 0)
  2786. testEnumModule(t, `out = enum.key(10, 20)`, 10)
  2787. testEnumModule(t, `out = enum.value(0, 0)`, 0)
  2788. testEnumModule(t, `out = enum.value(10, 20)`, 20)
  2789. testEnumModule(t, `out = enum.all([], enum.value)`, true)
  2790. testEnumModule(t, `out = enum.all([1], enum.value)`, true)
  2791. testEnumModule(t, `out = enum.all([true, 1], enum.value)`, true)
  2792. testEnumModule(t, `out = enum.all([true, 0], enum.value)`, false)
  2793. testEnumModule(t, `out = enum.all([true, 0, 1], enum.value)`, false)
  2794. testEnumModule(t, `out = enum.all(immutable([true, 0, 1]), enum.value)`,
  2795. false) // immutable-array
  2796. testEnumModule(t, `out = enum.all({}, enum.value)`, true)
  2797. testEnumModule(t, `out = enum.all({a:1}, enum.value)`, true)
  2798. testEnumModule(t, `out = enum.all({a:true, b:1}, enum.value)`, true)
  2799. testEnumModule(t, `out = enum.all(immutable({a:true, b:1}), enum.value)`,
  2800. true) // immutable-map
  2801. testEnumModule(t, `out = enum.all({a:true, b:0}, enum.value)`, false)
  2802. testEnumModule(t, `out = enum.all({a:true, b:0, c:1}, enum.value)`, false)
  2803. testEnumModule(t, `out = enum.all(0, enum.value)`,
  2804. tengo.UndefinedValue) // non-enumerable: undefined
  2805. testEnumModule(t, `out = enum.all("123", enum.value)`,
  2806. tengo.UndefinedValue) // non-enumerable: undefined
  2807. testEnumModule(t, `out = enum.any([], enum.value)`, false)
  2808. testEnumModule(t, `out = enum.any([1], enum.value)`, true)
  2809. testEnumModule(t, `out = enum.any([true, 1], enum.value)`, true)
  2810. testEnumModule(t, `out = enum.any([true, 0], enum.value)`, true)
  2811. testEnumModule(t, `out = enum.any([true, 0, 1], enum.value)`, true)
  2812. testEnumModule(t, `out = enum.any(immutable([true, 0, 1]), enum.value)`,
  2813. true) // immutable-array
  2814. testEnumModule(t, `out = enum.any([false], enum.value)`, false)
  2815. testEnumModule(t, `out = enum.any([false, 0], enum.value)`, false)
  2816. testEnumModule(t, `out = enum.any({}, enum.value)`, false)
  2817. testEnumModule(t, `out = enum.any({a:1}, enum.value)`, true)
  2818. testEnumModule(t, `out = enum.any({a:true, b:1}, enum.value)`, true)
  2819. testEnumModule(t, `out = enum.any({a:true, b:0}, enum.value)`, true)
  2820. testEnumModule(t, `out = enum.any({a:true, b:0, c:1}, enum.value)`, true)
  2821. testEnumModule(t, `out = enum.any(immutable({a:true, b:0, c:1}), enum.value)`,
  2822. true) // immutable-map
  2823. testEnumModule(t, `out = enum.any({a:false}, enum.value)`, false)
  2824. testEnumModule(t, `out = enum.any({a:false, b:0}, enum.value)`, false)
  2825. testEnumModule(t, `out = enum.any(0, enum.value)`,
  2826. tengo.UndefinedValue) // non-enumerable: undefined
  2827. testEnumModule(t, `out = enum.any("123", enum.value)`,
  2828. tengo.UndefinedValue) // non-enumerable: undefined
  2829. testEnumModule(t, `out = enum.chunk([], 1)`, ARR{})
  2830. testEnumModule(t, `out = enum.chunk([1], 1)`, ARR{ARR{1}})
  2831. testEnumModule(t, `out = enum.chunk([1,2,3], 1)`,
  2832. ARR{ARR{1}, ARR{2}, ARR{3}})
  2833. testEnumModule(t, `out = enum.chunk([1,2,3], 2)`,
  2834. ARR{ARR{1, 2}, ARR{3}})
  2835. testEnumModule(t, `out = enum.chunk([1,2,3], 3)`,
  2836. ARR{ARR{1, 2, 3}})
  2837. testEnumModule(t, `out = enum.chunk([1,2,3], 4)`,
  2838. ARR{ARR{1, 2, 3}})
  2839. testEnumModule(t, `out = enum.chunk([1,2,3,4], 3)`,
  2840. ARR{ARR{1, 2, 3}, ARR{4}})
  2841. testEnumModule(t, `out = enum.chunk([], 0)`,
  2842. tengo.UndefinedValue) // size=0: undefined
  2843. testEnumModule(t, `out = enum.chunk([1], 0)`,
  2844. tengo.UndefinedValue) // size=0: undefined
  2845. testEnumModule(t, `out = enum.chunk([1,2,3], 0)`,
  2846. tengo.UndefinedValue) // size=0: undefined
  2847. testEnumModule(t, `out = enum.chunk({a:1,b:2,c:3}, 1)`,
  2848. tengo.UndefinedValue) // map: undefined
  2849. testEnumModule(t, `out = enum.chunk(0, 1)`,
  2850. tengo.UndefinedValue) // non-enumerable: undefined
  2851. testEnumModule(t, `out = enum.chunk("123", 1)`,
  2852. tengo.UndefinedValue) // non-enumerable: undefined
  2853. testEnumModule(t, `out = enum.at([], 0)`,
  2854. tengo.UndefinedValue)
  2855. testEnumModule(t, `out = enum.at([], 1)`,
  2856. tengo.UndefinedValue)
  2857. testEnumModule(t, `out = enum.at([], -1)`,
  2858. tengo.UndefinedValue)
  2859. testEnumModule(t, `out = enum.at(["one"], 0)`,
  2860. "one")
  2861. testEnumModule(t, `out = enum.at(["one"], 1)`,
  2862. tengo.UndefinedValue)
  2863. testEnumModule(t, `out = enum.at(["one"], -1)`,
  2864. tengo.UndefinedValue)
  2865. testEnumModule(t, `out = enum.at(["one","two","three"], 0)`,
  2866. "one")
  2867. testEnumModule(t, `out = enum.at(["one","two","three"], 1)`,
  2868. "two")
  2869. testEnumModule(t, `out = enum.at(["one","two","three"], 2)`,
  2870. "three")
  2871. testEnumModule(t, `out = enum.at(["one","two","three"], -1)`,
  2872. tengo.UndefinedValue)
  2873. testEnumModule(t, `out = enum.at(["one","two","three"], 3)`,
  2874. tengo.UndefinedValue)
  2875. testEnumModule(t, `out = enum.at(["one","two","three"], "1")`,
  2876. tengo.UndefinedValue) // non-int index: undefined
  2877. testEnumModule(t, `out = enum.at({}, "a")`,
  2878. tengo.UndefinedValue)
  2879. testEnumModule(t, `out = enum.at({a:"one"}, "a")`,
  2880. "one")
  2881. testEnumModule(t, `out = enum.at({a:"one"}, "b")`,
  2882. tengo.UndefinedValue)
  2883. testEnumModule(t, `out = enum.at({a:"one",b:"two",c:"three"}, "a")`,
  2884. "one")
  2885. testEnumModule(t, `out = enum.at({a:"one",b:"two",c:"three"}, "b")`,
  2886. "two")
  2887. testEnumModule(t, `out = enum.at({a:"one",b:"two",c:"three"}, "c")`,
  2888. "three")
  2889. testEnumModule(t, `out = enum.at({a:"one",b:"two",c:"three"}, "d")`,
  2890. tengo.UndefinedValue)
  2891. testEnumModule(t, `out = enum.at({a:"one",b:"two",c:"three"}, 'a')`,
  2892. tengo.UndefinedValue) // non-string index: undefined
  2893. testEnumModule(t, `out = enum.at(0, 1)`,
  2894. tengo.UndefinedValue) // non-enumerable: undefined
  2895. testEnumModule(t, `out = enum.at("abc", 1)`,
  2896. tengo.UndefinedValue) // non-enumerable: undefined
  2897. testEnumModule(t, `out=0; enum.each([],func(k,v){out+=v})`, 0)
  2898. testEnumModule(t, `out=0; enum.each([1,2,3],func(k,v){out+=v})`, 6)
  2899. testEnumModule(t, `out=0; enum.each([1,2,3],func(k,v){out+=k})`, 3)
  2900. testEnumModule(t, `out=0; enum.each({a:1,b:2,c:3},func(k,v){out+=v})`, 6)
  2901. testEnumModule(t, `out=""; enum.each({a:1,b:2,c:3},func(k,v){out+=k}); out=len(out)`,
  2902. 3)
  2903. testEnumModule(t, `out=0; enum.each(5,func(k,v){out+=v})`, 0) // non-enumerable: no iteration
  2904. testEnumModule(t, `out=0; enum.each("123",func(k,v){out+=v})`, 0) // non-enumerable: no iteration
  2905. testEnumModule(t, `out = enum.filter([], enum.value)`,
  2906. ARR{})
  2907. testEnumModule(t, `out = enum.filter([false,1,2], enum.value)`,
  2908. ARR{1, 2})
  2909. testEnumModule(t, `out = enum.filter([false,1,0,2], enum.value)`,
  2910. ARR{1, 2})
  2911. testEnumModule(t, `out = enum.filter({}, enum.value)`,
  2912. tengo.UndefinedValue) // non-array: undefined
  2913. testEnumModule(t, `out = enum.filter(0, enum.value)`,
  2914. tengo.UndefinedValue) // non-array: undefined
  2915. testEnumModule(t, `out = enum.filter("123", enum.value)`,
  2916. tengo.UndefinedValue) // non-array: undefined
  2917. testEnumModule(t, `out = enum.find([], enum.value)`,
  2918. tengo.UndefinedValue)
  2919. testEnumModule(t, `out = enum.find([0], enum.value)`,
  2920. tengo.UndefinedValue)
  2921. testEnumModule(t, `out = enum.find([1], enum.value)`, 1)
  2922. testEnumModule(t, `out = enum.find([false,0,undefined,1], enum.value)`, 1)
  2923. testEnumModule(t, `out = enum.find([1,2,3], enum.value)`, 1)
  2924. testEnumModule(t, `out = enum.find({}, enum.value)`,
  2925. tengo.UndefinedValue)
  2926. testEnumModule(t, `out = enum.find({a:0}, enum.value)`,
  2927. tengo.UndefinedValue)
  2928. testEnumModule(t, `out = enum.find({a:1}, enum.value)`, 1)
  2929. testEnumModule(t, `out = enum.find({a:false,b:0,c:undefined,d:1}, enum.value)`,
  2930. 1)
  2931. //testEnumModule(t, `out = enum.find({a:1,b:2,c:3}, enum.value)`, 1)
  2932. testEnumModule(t, `out = enum.find(0, enum.value)`,
  2933. tengo.UndefinedValue) // non-enumerable: undefined
  2934. testEnumModule(t, `out = enum.find("123", enum.value)`,
  2935. tengo.UndefinedValue) // non-enumerable: undefined
  2936. testEnumModule(t, `out = enum.find_key([], enum.value)`,
  2937. tengo.UndefinedValue)
  2938. testEnumModule(t, `out = enum.find_key([0], enum.value)`,
  2939. tengo.UndefinedValue)
  2940. testEnumModule(t, `out = enum.find_key([1], enum.value)`, 0)
  2941. testEnumModule(t, `out = enum.find_key([false,0,undefined,1], enum.value)`,
  2942. 3)
  2943. testEnumModule(t, `out = enum.find_key([1,2,3], enum.value)`, 0)
  2944. testEnumModule(t, `out = enum.find_key({}, enum.value)`,
  2945. tengo.UndefinedValue)
  2946. testEnumModule(t, `out = enum.find_key({a:0}, enum.value)`,
  2947. tengo.UndefinedValue)
  2948. testEnumModule(t, `out = enum.find_key({a:1}, enum.value)`,
  2949. "a")
  2950. testEnumModule(t, `out = enum.find_key({a:false,b:0,c:undefined,d:1}, enum.value)`,
  2951. "d")
  2952. //testEnumModule(t, `out = enum.find_key({a:1,b:2,c:3}, enum.value)`, "a")
  2953. testEnumModule(t, `out = enum.find_key(0, enum.value)`,
  2954. tengo.UndefinedValue) // non-enumerable: undefined
  2955. testEnumModule(t, `out = enum.find_key("123", enum.value)`,
  2956. tengo.UndefinedValue) // non-enumerable: undefined
  2957. testEnumModule(t, `out = enum.map([], enum.value)`,
  2958. ARR{})
  2959. testEnumModule(t, `out = enum.map([1,2,3], enum.value)`,
  2960. ARR{1, 2, 3})
  2961. testEnumModule(t, `out = enum.map([1,2,3], enum.key)`,
  2962. ARR{0, 1, 2})
  2963. testEnumModule(t, `out = enum.map([1,2,3], func(k,v) { return v*2 })`,
  2964. ARR{2, 4, 6})
  2965. testEnumModule(t, `out = enum.map({}, enum.value)`,
  2966. ARR{})
  2967. testEnumModule(t, `out = enum.map({a:1}, func(k,v) { return v*2 })`,
  2968. ARR{2})
  2969. testEnumModule(t, `out = enum.map(0, enum.value)`,
  2970. tengo.UndefinedValue) // non-enumerable: undefined
  2971. testEnumModule(t, `out = enum.map("123", enum.value)`,
  2972. tengo.UndefinedValue) // non-enumerable: undefined
  2973. }
  2974. func testEnumModule(t *testing.T, input string, expected interface{}) {
  2975. expectRun(t, `enum := import("enum"); `+input,
  2976. Opts().Module("enum", stdlib.SourceModules["enum"]),
  2977. expected)
  2978. }
  2979. func TestSrcModEnum(t *testing.T) {
  2980. expectRun(t, `
  2981. x := import("enum")
  2982. out = x.all([1, 2, 3], func(_, v) { return v >= 1 })
  2983. `, Opts().Stdlib(), true)
  2984. expectRun(t, `
  2985. x := import("enum")
  2986. out = x.all([1, 2, 3], func(_, v) { return v >= 2 })
  2987. `, Opts().Stdlib(), false)
  2988. expectRun(t, `
  2989. x := import("enum")
  2990. out = x.any([1, 2, 3], func(_, v) { return v >= 1 })
  2991. `, Opts().Stdlib(), true)
  2992. expectRun(t, `
  2993. x := import("enum")
  2994. out = x.any([1, 2, 3], func(_, v) { return v >= 2 })
  2995. `, Opts().Stdlib(), true)
  2996. expectRun(t, `
  2997. x := import("enum")
  2998. out = x.chunk([1, 2, 3], 1)
  2999. `, Opts().Stdlib(), ARR{ARR{1}, ARR{2}, ARR{3}})
  3000. expectRun(t, `
  3001. x := import("enum")
  3002. out = x.chunk([1, 2, 3], 2)
  3003. `, Opts().Stdlib(), ARR{ARR{1, 2}, ARR{3}})
  3004. expectRun(t, `
  3005. x := import("enum")
  3006. out = x.chunk([1, 2, 3], 3)
  3007. `, Opts().Stdlib(), ARR{ARR{1, 2, 3}})
  3008. expectRun(t, `
  3009. x := import("enum")
  3010. out = x.chunk([1, 2, 3], 4)
  3011. `, Opts().Stdlib(), ARR{ARR{1, 2, 3}})
  3012. expectRun(t, `
  3013. x := import("enum")
  3014. out = x.chunk([1, 2, 3, 4, 5, 6], 2)
  3015. `, Opts().Stdlib(), ARR{ARR{1, 2}, ARR{3, 4}, ARR{5, 6}})
  3016. expectRun(t, `
  3017. x := import("enum")
  3018. out = x.at([1, 2, 3], 0)
  3019. `, Opts().Stdlib(), 1)
  3020. }
  3021. func TestVMStackOverflow(t *testing.T) {
  3022. expectError(t, `f := func() { return f() + 1 }; f()`,
  3023. nil, "stack overflow")
  3024. }
  3025. func TestString(t *testing.T) {
  3026. expectRun(t, `out = "Hello World!"`, nil, "Hello World!")
  3027. expectRun(t, `out = "Hello" + " " + "World!"`, nil, "Hello World!")
  3028. expectRun(t, `out = "Hello" == "Hello"`, nil, true)
  3029. expectRun(t, `out = "Hello" == "World"`, nil, false)
  3030. expectRun(t, `out = "Hello" != "Hello"`, nil, false)
  3031. expectRun(t, `out = "Hello" != "World"`, nil, true)
  3032. expectRun(t, `out = "Hello" > "World"`, nil, false)
  3033. expectRun(t, `out = "World" < "Hello"`, nil, false)
  3034. expectRun(t, `out = "Hello" < "World"`, nil, true)
  3035. expectRun(t, `out = "World" > "Hello"`, nil, true)
  3036. expectRun(t, `out = "Hello" >= "World"`, nil, false)
  3037. expectRun(t, `out = "Hello" <= "World"`, nil, true)
  3038. expectRun(t, `out = "Hello" >= "Hello"`, nil, true)
  3039. expectRun(t, `out = "World" <= "World"`, nil, true)
  3040. // index operator
  3041. str := "abcdef"
  3042. strStr := `"abcdef"`
  3043. strLen := 6
  3044. for idx := 0; idx < strLen; idx++ {
  3045. expectRun(t, fmt.Sprintf("out = %s[%d]", strStr, idx),
  3046. nil, str[idx])
  3047. expectRun(t, fmt.Sprintf("out = %s[0 + %d]", strStr, idx),
  3048. nil, str[idx])
  3049. expectRun(t, fmt.Sprintf("out = %s[1 + %d - 1]", strStr, idx),
  3050. nil, str[idx])
  3051. expectRun(t, fmt.Sprintf("idx := %d; out = %s[idx]", idx, strStr),
  3052. nil, str[idx])
  3053. }
  3054. expectRun(t, fmt.Sprintf("%s[%d]", strStr, -1),
  3055. nil, tengo.UndefinedValue)
  3056. expectRun(t, fmt.Sprintf("%s[%d]", strStr, strLen),
  3057. nil, tengo.UndefinedValue)
  3058. // slice operator
  3059. for low := 0; low <= strLen; low++ {
  3060. expectRun(t, fmt.Sprintf("out = %s[%d:%d]", strStr, low, low),
  3061. nil, "")
  3062. for high := low; high <= strLen; high++ {
  3063. expectRun(t, fmt.Sprintf("out = %s[%d:%d]", strStr, low, high),
  3064. nil, str[low:high])
  3065. expectRun(t,
  3066. fmt.Sprintf("out = %s[0 + %d : 0 + %d]", strStr, low, high),
  3067. nil, str[low:high])
  3068. expectRun(t,
  3069. fmt.Sprintf("out = %s[1 + %d - 1 : 1 + %d - 1]",
  3070. strStr, low, high),
  3071. nil, str[low:high])
  3072. expectRun(t,
  3073. fmt.Sprintf("out = %s[:%d]", strStr, high),
  3074. nil, str[:high])
  3075. expectRun(t,
  3076. fmt.Sprintf("out = %s[%d:]", strStr, low),
  3077. nil, str[low:])
  3078. }
  3079. }
  3080. expectRun(t, fmt.Sprintf("out = %s[:]", strStr),
  3081. nil, str[:])
  3082. expectRun(t, fmt.Sprintf("out = %s[:]", strStr),
  3083. nil, str)
  3084. expectRun(t, fmt.Sprintf("out = %s[%d:]", strStr, -1),
  3085. nil, str)
  3086. expectRun(t, fmt.Sprintf("out = %s[:%d]", strStr, strLen+1),
  3087. nil, str)
  3088. expectRun(t, fmt.Sprintf("out = %s[%d:%d]", strStr, 2, 2),
  3089. nil, "")
  3090. expectError(t, fmt.Sprintf("%s[:%d]", strStr, -1),
  3091. nil, "invalid slice index")
  3092. expectError(t, fmt.Sprintf("%s[%d:]", strStr, strLen+1),
  3093. nil, "invalid slice index")
  3094. expectError(t, fmt.Sprintf("%s[%d:%d]", strStr, 0, -1),
  3095. nil, "invalid slice index")
  3096. expectError(t, fmt.Sprintf("%s[%d:%d]", strStr, 2, 1),
  3097. nil, "invalid slice index")
  3098. // string concatenation with other types
  3099. expectRun(t, `out = "foo" + 1`, nil, "foo1")
  3100. // Float.String() returns the smallest number of digits
  3101. // necessary such that ParseFloat will return f exactly.
  3102. expectRun(t, `out = "foo" + 1.0`, nil, "foo1") // <- note '1' instead of '1.0'
  3103. expectRun(t, `out = "foo" + 1.5`, nil, "foo1.5")
  3104. expectRun(t, `out = "foo" + true`, nil, "footrue")
  3105. expectRun(t, `out = "foo" + 'X'`, nil, "fooX")
  3106. expectRun(t, `out = "foo" + error(5)`, nil, "fooerror: 5")
  3107. expectRun(t, `out = "foo" + undefined`, nil, "foo<undefined>")
  3108. expectRun(t, `out = "foo" + [1,2,3]`, nil, "foo[1, 2, 3]")
  3109. // also works with "+=" operator
  3110. expectRun(t, `out = "foo"; out += 1.5`, nil, "foo1.5")
  3111. // string concats works only when string is LHS
  3112. expectError(t, `1 + "foo"`, nil, "invalid operation")
  3113. expectError(t, `"foo" - "bar"`, nil, "invalid operation")
  3114. }
  3115. func TestTailCall(t *testing.T) {
  3116. expectRun(t, `
  3117. fac := func(n, a) {
  3118. if n == 1 {
  3119. return a
  3120. }
  3121. return fac(n-1, n*a)
  3122. }
  3123. out = fac(5, 1)`, nil, 120)
  3124. expectRun(t, `
  3125. fac := func(n, a) {
  3126. if n == 1 {
  3127. return a
  3128. }
  3129. x := {foo: fac} // indirection for test
  3130. return x.foo(n-1, n*a)
  3131. }
  3132. out = fac(5, 1)`, nil, 120)
  3133. expectRun(t, `
  3134. fib := func(x, s) {
  3135. if x == 0 {
  3136. return 0 + s
  3137. } else if x == 1 {
  3138. return 1 + s
  3139. }
  3140. return fib(x-1, fib(x-2, s))
  3141. }
  3142. out = fib(15, 0)`, nil, 610)
  3143. expectRun(t, `
  3144. fib := func(n, a, b) {
  3145. if n == 0 {
  3146. return a
  3147. } else if n == 1 {
  3148. return b
  3149. }
  3150. return fib(n-1, b, a + b)
  3151. }
  3152. out = fib(15, 0, 1)`, nil, 610)
  3153. // global variable and no return value
  3154. expectRun(t, `
  3155. out = 0
  3156. foo := func(a) {
  3157. if a == 0 {
  3158. return
  3159. }
  3160. out += a
  3161. foo(a-1)
  3162. }
  3163. foo(10)`, nil, 55)
  3164. expectRun(t, `
  3165. f1 := func() {
  3166. f2 := 0 // TODO: this might be fixed in the future
  3167. f2 = func(n, s) {
  3168. if n == 0 { return s }
  3169. return f2(n-1, n + s)
  3170. }
  3171. return f2(5, 0)
  3172. }
  3173. out = f1()`, nil, 15)
  3174. // tail-call replacing loop
  3175. // without tail-call optimization, this code will cause stack overflow
  3176. expectRun(t, `
  3177. iter := func(n, max) {
  3178. if n == max {
  3179. return n
  3180. }
  3181. return iter(n+1, max)
  3182. }
  3183. out = iter(0, 9999)
  3184. `, nil, 9999)
  3185. expectRun(t, `
  3186. c := 0
  3187. iter := func(n, max) {
  3188. if n == max {
  3189. return
  3190. }
  3191. c++
  3192. iter(n+1, max)
  3193. }
  3194. iter(0, 9999)
  3195. out = c
  3196. `, nil, 9999)
  3197. }
  3198. // tail call with free vars
  3199. func TestTailCallFreeVars(t *testing.T) {
  3200. expectRun(t, `
  3201. func() {
  3202. a := 10
  3203. f2 := 0
  3204. f2 = func(n, s) {
  3205. if n == 0 {
  3206. return s + a
  3207. }
  3208. return f2(n-1, n+s)
  3209. }
  3210. out = f2(5, 0)
  3211. }()`, nil, 25)
  3212. }
  3213. func TestSpread(t *testing.T) {
  3214. expectRun(t, `
  3215. f := func(...a) {
  3216. return append(a, 3)
  3217. }
  3218. out = f([1, 2]...)
  3219. `, nil, ARR{1, 2, 3})
  3220. expectRun(t, `
  3221. f := func(a, ...b) {
  3222. return append([a], append(b, 3)...)
  3223. }
  3224. out = f([1, 2]...)
  3225. `, nil, ARR{1, 2, 3})
  3226. expectRun(t, `
  3227. f := func(a, ...b) {
  3228. return append(append([a], b), 3)
  3229. }
  3230. out = f(1, [2]...)
  3231. `, nil, ARR{1, ARR{2}, 3})
  3232. expectRun(t, `
  3233. f1 := func(...a){
  3234. return append([3], a...)
  3235. }
  3236. f2 := func(a, ...b) {
  3237. return f1(append([a], b...)...)
  3238. }
  3239. out = f2([1, 2]...)
  3240. `, nil, ARR{3, 1, 2})
  3241. expectRun(t, `
  3242. f := func(a, ...b) {
  3243. return func(...a) {
  3244. return append([3], append(a, 4)...)
  3245. }(a, b...)
  3246. }
  3247. out = f([1, 2]...)
  3248. `, nil, ARR{3, 1, 2, 4})
  3249. expectRun(t, `
  3250. f := func(a, ...b) {
  3251. c := append(b, 4)
  3252. return func(){
  3253. return append(append([a], b...), c...)
  3254. }()
  3255. }
  3256. out = f(1, immutable([2, 3])...)
  3257. `, nil, ARR{1, 2, 3, 2, 3, 4})
  3258. expectError(t, `func(a) {}([1, 2]...)`, nil,
  3259. "Runtime Error: wrong number of arguments: want=1, got=2")
  3260. expectError(t, `func(a, b, c) {}([1, 2]...)`, nil,
  3261. "Runtime Error: wrong number of arguments: want=3, got=2")
  3262. }
  3263. func TestSliceIndex(t *testing.T) {
  3264. expectError(t, `undefined[:1]`, nil, "Runtime Error: not indexable")
  3265. expectError(t, `123[-1:2]`, nil, "Runtime Error: not indexable")
  3266. expectError(t, `{}[:]`, nil, "Runtime Error: not indexable")
  3267. expectError(t, `a := 123[-1:2] ; a += 1`, nil, "Runtime Error: not indexable")
  3268. }
  3269. func expectRun(
  3270. t *testing.T,
  3271. input string,
  3272. opts *testopts,
  3273. expected interface{},
  3274. ) {
  3275. if opts == nil {
  3276. opts = Opts()
  3277. }
  3278. symbols := opts.symbols
  3279. modules := opts.modules
  3280. maxAllocs := opts.maxAllocs
  3281. expectedObj := toObject(expected)
  3282. if symbols == nil {
  3283. symbols = make(map[string]tengo.Object)
  3284. }
  3285. symbols[testOut] = objectZeroCopy(expectedObj)
  3286. // first pass: run the code normally
  3287. {
  3288. // parse
  3289. file := parse(t, input)
  3290. if file == nil {
  3291. return
  3292. }
  3293. // compiler/VM
  3294. res, trace, err := traceCompileRun(file, symbols, modules, maxAllocs)
  3295. require.NoError(t, err, "\n"+strings.Join(trace, "\n"))
  3296. require.Equal(t, expectedObj, res[testOut],
  3297. "\n"+strings.Join(trace, "\n"))
  3298. }
  3299. // second pass: run the code as import module
  3300. if !opts.skip2ndPass {
  3301. file := parse(t, `out = import("__code__")`)
  3302. if file == nil {
  3303. return
  3304. }
  3305. expectedObj := toObject(expected)
  3306. switch eo := expectedObj.(type) {
  3307. case *tengo.Array:
  3308. expectedObj = &tengo.ImmutableArray{Value: eo.Value}
  3309. case *tengo.Map:
  3310. expectedObj = &tengo.ImmutableMap{Value: eo.Value}
  3311. }
  3312. modules.AddSourceModule("__code__",
  3313. []byte(fmt.Sprintf("out := undefined; %s; export out", input)))
  3314. res, trace, err := traceCompileRun(file, symbols, modules, maxAllocs)
  3315. require.NoError(t, err, "\n"+strings.Join(trace, "\n"))
  3316. require.Equal(t, expectedObj, res[testOut],
  3317. "\n"+strings.Join(trace, "\n"))
  3318. }
  3319. }
  3320. func expectError(
  3321. t *testing.T,
  3322. input string,
  3323. opts *testopts,
  3324. expected string,
  3325. ) {
  3326. if opts == nil {
  3327. opts = Opts()
  3328. }
  3329. symbols := opts.symbols
  3330. modules := opts.modules
  3331. maxAllocs := opts.maxAllocs
  3332. expected = strings.TrimSpace(expected)
  3333. if expected == "" {
  3334. panic("expected must not be empty")
  3335. }
  3336. // parse
  3337. program := parse(t, input)
  3338. if program == nil {
  3339. return
  3340. }
  3341. // compiler/VM
  3342. _, trace, err := traceCompileRun(program, symbols, modules, maxAllocs)
  3343. require.Error(t, err, "\n"+strings.Join(trace, "\n"))
  3344. require.True(t, strings.Contains(err.Error(), expected),
  3345. "expected error string: %s, got: %s\n%s",
  3346. expected, err.Error(), strings.Join(trace, "\n"))
  3347. }
  3348. func expectErrorIs(
  3349. t *testing.T,
  3350. input string,
  3351. opts *testopts,
  3352. expected error,
  3353. ) {
  3354. if opts == nil {
  3355. opts = Opts()
  3356. }
  3357. symbols := opts.symbols
  3358. modules := opts.modules
  3359. maxAllocs := opts.maxAllocs
  3360. // parse
  3361. program := parse(t, input)
  3362. if program == nil {
  3363. return
  3364. }
  3365. // compiler/VM
  3366. _, trace, err := traceCompileRun(program, symbols, modules, maxAllocs)
  3367. require.Error(t, err, "\n"+strings.Join(trace, "\n"))
  3368. require.True(t, errors.Is(err, expected),
  3369. "expected error is: %s, got: %s\n%s",
  3370. expected.Error(), err.Error(), strings.Join(trace, "\n"))
  3371. }
  3372. func expectErrorAs(
  3373. t *testing.T,
  3374. input string,
  3375. opts *testopts,
  3376. expected interface{},
  3377. ) {
  3378. if opts == nil {
  3379. opts = Opts()
  3380. }
  3381. symbols := opts.symbols
  3382. modules := opts.modules
  3383. maxAllocs := opts.maxAllocs
  3384. // parse
  3385. program := parse(t, input)
  3386. if program == nil {
  3387. return
  3388. }
  3389. // compiler/VM
  3390. _, trace, err := traceCompileRun(program, symbols, modules, maxAllocs)
  3391. require.Error(t, err, "\n"+strings.Join(trace, "\n"))
  3392. require.True(t, errors.As(err, expected),
  3393. "expected error as: %v, got: %v\n%s",
  3394. expected, err, strings.Join(trace, "\n"))
  3395. }
  3396. type vmTracer struct {
  3397. Out []string
  3398. }
  3399. func (o *vmTracer) Write(p []byte) (n int, err error) {
  3400. o.Out = append(o.Out, string(p))
  3401. return len(p), nil
  3402. }
  3403. func traceCompileRun(
  3404. file *parser.File,
  3405. symbols map[string]tengo.Object,
  3406. modules *tengo.ModuleMap,
  3407. maxAllocs int64,
  3408. ) (res map[string]tengo.Object, trace []string, err error) {
  3409. var v *tengo.VM
  3410. defer func() {
  3411. if e := recover(); e != nil {
  3412. err = fmt.Errorf("panic: %v", e)
  3413. // stack trace
  3414. var stackTrace []string
  3415. for i := 2; ; i += 1 {
  3416. _, file, line, ok := _runtime.Caller(i)
  3417. if !ok {
  3418. break
  3419. }
  3420. stackTrace = append(stackTrace,
  3421. fmt.Sprintf(" %s:%d", file, line))
  3422. }
  3423. trace = append(trace,
  3424. fmt.Sprintf("[Error Trace]\n\n %s\n",
  3425. strings.Join(stackTrace, "\n ")))
  3426. }
  3427. }()
  3428. globals := make([]tengo.Object, tengo.GlobalsSize)
  3429. symTable := tengo.NewSymbolTable()
  3430. for name, value := range symbols {
  3431. sym := symTable.Define(name)
  3432. // should not store pointer to 'value' variable
  3433. // which is re-used in each iteration.
  3434. valueCopy := value
  3435. globals[sym.Index] = valueCopy
  3436. }
  3437. for idx, fn := range tengo.GetAllBuiltinFunctions() {
  3438. symTable.DefineBuiltin(idx, fn.Name)
  3439. }
  3440. tr := &vmTracer{}
  3441. c := tengo.NewCompiler(file.InputFile, symTable, nil, modules, tr)
  3442. err = c.Compile(file)
  3443. trace = append(trace,
  3444. fmt.Sprintf("\n[Compiler Trace]\n\n%s",
  3445. strings.Join(tr.Out, "")))
  3446. if err != nil {
  3447. return
  3448. }
  3449. bytecode := c.Bytecode()
  3450. bytecode.RemoveDuplicates()
  3451. trace = append(trace, fmt.Sprintf("\n[Compiled Constants]\n\n%s",
  3452. strings.Join(bytecode.FormatConstants(), "\n")))
  3453. trace = append(trace, fmt.Sprintf("\n[Compiled Instructions]\n\n%s\n",
  3454. strings.Join(bytecode.FormatInstructions(), "\n")))
  3455. v = tengo.NewVM(bytecode, globals, maxAllocs)
  3456. err = v.Run()
  3457. {
  3458. res = make(map[string]tengo.Object)
  3459. for name := range symbols {
  3460. sym, depth, ok := symTable.Resolve(name, false)
  3461. if !ok || depth != 0 {
  3462. err = fmt.Errorf("symbol not found: %s", name)
  3463. return
  3464. }
  3465. res[name] = globals[sym.Index]
  3466. }
  3467. trace = append(trace, fmt.Sprintf("\n[Globals]\n\n%s",
  3468. strings.Join(formatGlobals(globals), "\n")))
  3469. }
  3470. if err == nil && !v.IsStackEmpty() {
  3471. err = errors.New("non empty stack after execution")
  3472. }
  3473. return
  3474. }
  3475. func formatGlobals(globals []tengo.Object) (formatted []string) {
  3476. for idx, global := range globals {
  3477. if global == nil {
  3478. return
  3479. }
  3480. formatted = append(formatted, fmt.Sprintf("[% 3d] %s (%s|%p)",
  3481. idx, global.String(), reflect.TypeOf(global).Elem().Name(), global))
  3482. }
  3483. return
  3484. }
  3485. func parse(t *testing.T, input string) *parser.File {
  3486. testFileSet := parser.NewFileSet()
  3487. testFile := testFileSet.AddFile("test", -1, len(input))
  3488. p := parser.NewParser(testFile, []byte(input), nil)
  3489. file, err := p.ParseFile()
  3490. require.NoError(t, err)
  3491. return file
  3492. }
  3493. func errorObject(v interface{}) *tengo.Error {
  3494. return &tengo.Error{Value: toObject(v)}
  3495. }
  3496. func toObject(v interface{}) tengo.Object {
  3497. switch v := v.(type) {
  3498. case tengo.Object:
  3499. return v
  3500. case string:
  3501. return &tengo.String{Value: v}
  3502. case int64:
  3503. return &tengo.Int{Value: v}
  3504. case int: // for convenience
  3505. return &tengo.Int{Value: int64(v)}
  3506. case bool:
  3507. if v {
  3508. return tengo.TrueValue
  3509. }
  3510. return tengo.FalseValue
  3511. case rune:
  3512. return &tengo.Char{Value: v}
  3513. case byte: // for convenience
  3514. return &tengo.Char{Value: rune(v)}
  3515. case float64:
  3516. return &tengo.Float{Value: v}
  3517. case []byte:
  3518. return &tengo.Bytes{Value: v}
  3519. case MAP:
  3520. objs := make(map[string]tengo.Object)
  3521. for k, v := range v {
  3522. objs[k] = toObject(v)
  3523. }
  3524. return &tengo.Map{Value: objs}
  3525. case ARR:
  3526. var objs []tengo.Object
  3527. for _, e := range v {
  3528. objs = append(objs, toObject(e))
  3529. }
  3530. return &tengo.Array{Value: objs}
  3531. case IMAP:
  3532. objs := make(map[string]tengo.Object)
  3533. for k, v := range v {
  3534. objs[k] = toObject(v)
  3535. }
  3536. return &tengo.ImmutableMap{Value: objs}
  3537. case IARR:
  3538. var objs []tengo.Object
  3539. for _, e := range v {
  3540. objs = append(objs, toObject(e))
  3541. }
  3542. return &tengo.ImmutableArray{Value: objs}
  3543. }
  3544. panic(fmt.Errorf("unknown type: %T", v))
  3545. }
  3546. func objectZeroCopy(o tengo.Object) tengo.Object {
  3547. switch o.(type) {
  3548. case *tengo.Int:
  3549. return &tengo.Int{}
  3550. case *tengo.Float:
  3551. return &tengo.Float{}
  3552. case *tengo.Bool:
  3553. return &tengo.Bool{}
  3554. case *tengo.Char:
  3555. return &tengo.Char{}
  3556. case *tengo.String:
  3557. return &tengo.String{}
  3558. case *tengo.Array:
  3559. return &tengo.Array{}
  3560. case *tengo.Map:
  3561. return &tengo.Map{}
  3562. case *tengo.Undefined:
  3563. return tengo.UndefinedValue
  3564. case *tengo.Error:
  3565. return &tengo.Error{}
  3566. case *tengo.Bytes:
  3567. return &tengo.Bytes{}
  3568. case *tengo.ImmutableArray:
  3569. return &tengo.ImmutableArray{}
  3570. case *tengo.ImmutableMap:
  3571. return &tengo.ImmutableMap{}
  3572. case nil:
  3573. panic("nil")
  3574. default:
  3575. panic(fmt.Errorf("unknown object type: %s", o.TypeName()))
  3576. }
  3577. }