vm_test.go 108 KB

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